lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
b6fc291a2d8ce4a7d3446452e21dd8741fe90e16
0
tbrooks8/Agrona,real-logic/Agrona
/* * Copyright 2014 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.agrona.concurrent.ringbuffer; import uk.co.real_logic.agrona.DirectBuffer; import uk.co.real_logic.agrona.concurrent.AtomicBuffer; import uk.co.real_logic.agrona.concurrent.MessageHandler; /** * Ring-buffer for the concurrent exchanging of binary encoded messages from producer to consumer in a FIFO manner. */ public interface RingBuffer { /** * Get the capacity of the ring-buffer in bytes for exchange. * * @return the capacity of the ring-buffer in bytes for exchange. */ int capacity(); /** * Non-blocking write of an message to an underlying ring-buffer. * * @param msgTypeId type of the message encoding. * @param srcBuffer containing the encoded binary message. * @param srcIndex at which the encoded message begins. * @param length of the encoded message in bytes. * @return true if written to the ring-buffer, or false if insufficient space exists. * @throws IllegalArgumentException if the length is greater than {@link RingBuffer#maxMsgLength()} */ boolean write(int msgTypeId, DirectBuffer srcBuffer, int srcIndex, int length); /** * Read as many messages as are available from the ring buffer. * * @param handler to be called for processing each message in turn. * @return the number of messages that have been processed. */ int read(MessageHandler handler); /** * Read as many messages as are available from the ring buffer to up a supplied maximum. * * @param handler to be called for processing each message in turn. * @param messageCountLimit the number of messages will be read in a single invocation. * @return the number of messages that have been processed. */ int read(MessageHandler handler, int messageCountLimit); /** * The maximum message length in bytes supported by the underlying ring buffer. * * @return the maximum message length in bytes supported by the underlying ring buffer. */ int maxMsgLength(); /** * Get the next value that can be used for a correlation id on an message when a response needs to be correlated. * * This method should be thread safe. * * @return the next value in the correlation sequence. */ long nextCorrelationId(); /** * Get the underlying buffer used by the RingBuffer for storage. * * @return the underlying buffer used by the RingBuffer for storage. */ AtomicBuffer buffer(); /** * Set the time of the last consumer heartbeat. * * <b>Note:</b> The value for time must be valid across processes which means {@link System#nanoTime()} * is not a valid option. * * @param time of the last consumer heartbeat. */ void consumerHeartbeatTime(long time); /** * The time of the last consumer heartbeat. * * @return the time of the last consumer heartbeat. */ long consumerHeartbeatTime(); /** * The count in bytes from start up of the producers. The figure includes the headers. * This is the range they are working with but could still be in the act of working with. * * @return number of bytes produced by the producers in claimed space. */ long producerCount(); /** * The count in bytes from start up for the consumers. The figure includes the headers. * * @return the count of bytes consumed by the consumers. */ long consumerCount(); /** * Size of the backlog of bytes in the buffer between producers and consumers. The figure includes the size of headers. * * @return size of the backlog of bytes in the buffer between producers and consumers. */ int size(); }
src/main/java/uk/co/real_logic/agrona/concurrent/ringbuffer/RingBuffer.java
/* * Copyright 2014 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.agrona.concurrent.ringbuffer; import uk.co.real_logic.agrona.DirectBuffer; import uk.co.real_logic.agrona.concurrent.AtomicBuffer; import uk.co.real_logic.agrona.concurrent.MessageHandler; /** * Ring-buffer for the concurrent exchanging of binary encoded messages from producer to consumer in a FIFO manner. */ public interface RingBuffer { /** * Get the capacity of the ring-buffer in bytes for exchange. * * @return the capacity of the ring-buffer in bytes for exchange. */ int capacity(); /** * Non-blocking write of an message to an underlying ring-buffer. * * @param msgTypeId type of the message encoding. * @param srcBuffer containing the encoded binary message. * @param srcIndex at which the encoded message begins. * @param length of the encoded message in bytes. * @return true if written to the ring-buffer, or false if insufficient space exists. * @throws IllegalArgumentException if the length is greater than {@link RingBuffer#maxMsgLength()} */ boolean write(int msgTypeId, DirectBuffer srcBuffer, int srcIndex, int length); /** * Read as many messages as are available from the ring buffer. * * @param handler to be called for processing each message in turn. * @return the number of messages that have been processed. */ int read(MessageHandler handler); /** * Read as many messages as are available from the ring buffer to up a supplied maximum. * * @param handler to be called for processing each message in turn. * @param messageCountLimit the number of messages will be read in a single invocation. * @return the number of messages that have been processed. */ int read(MessageHandler handler, int messageCountLimit); /** * The maximum message length in bytes supported by the underlying ring buffer. * * @return the maximum message length in bytes supported by the underlying ring buffer. */ int maxMsgLength(); /** * Get the next value that can be used for a correlation id on an message when a response needs to be correlated. * * This method should be thread safe. * * @return the next value in the correlation sequence. */ long nextCorrelationId(); /** * Get the underlying buffer used by the RingBuffer for storage. * * @return the underlying buffer used by the RingBuffer for storage. */ AtomicBuffer buffer(); /** * Set the time of the last consumer heartbeat. * * <b>Note:</b> The value for time must be valid across processes which means {@link System#nanoTime()} * is not a valid option. * * @param time of the last consumer heartbeat. */ void consumerHeartbeatTime(long time); /** * The time of the last consumer heartbeat. * * @return the time of the last consumer heartbeat. */ long consumerHeartbeatTime(); /** * The count in bytes from start up of the producers. This is the range they are working with but could still * be in the act of working with. * * @return number of bytes produced by the producers in claimed space. */ long producerCount(); /** * The count in bytes from start up for the consumers. * * @return the count of bytes consumed by the consumers. */ long consumerCount(); /** * Size of the backlog of bytes in the buffer between producers and consumers. * * @return size of the backlog of bytes in the buffer between producers and consumers. */ int size(); }
[Java]: Javadoc.
src/main/java/uk/co/real_logic/agrona/concurrent/ringbuffer/RingBuffer.java
[Java]: Javadoc.
Java
apache-2.0
64fe899ac5d15a48dbcfaca9ac0bc5c79d2e6526
0
RussellWilby/Aeron,tbrooks8/Aeron,galderz/Aeron,lennartj/Aeron,buybackoff/Aeron,oleksiyp/Aeron,gkamal/Aeron,RussellWilby/Aeron,EvilMcJerkface/Aeron,tbrooks8/Aeron,lennartj/Aeron,oleksiyp/Aeron,mikeb01/Aeron,UIKit0/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,jerrinot/Aeron,galderz/Aeron,real-logic/Aeron,strangelydim/Aeron,lennartj/Aeron,oleksiyp/Aeron,gkamal/Aeron,EvilMcJerkface/Aeron,tbrooks8/Aeron,UIKit0/Aeron,jerrinot/Aeron,mikeb01/Aeron,jerrinot/Aeron,real-logic/Aeron,strangelydim/Aeron,RussellWilby/Aeron,UIKit0/Aeron,buybackoff/Aeron,strangelydim/Aeron,real-logic/Aeron,galderz/Aeron,real-logic/Aeron,gkamal/Aeron,EvilMcJerkface/Aeron,buybackoff/Aeron,mikeb01/Aeron,galderz/Aeron
/* * Copyright 2014 - 2015 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.aeron; import org.junit.After; import org.junit.Test; import org.junit.experimental.theories.Theories; import org.junit.runner.RunWith; import uk.co.real_logic.aeron.driver.MediaDriver; import uk.co.real_logic.aeron.logbuffer.FragmentHandler; import uk.co.real_logic.agrona.BitUtil; import uk.co.real_logic.agrona.collections.MutableInteger; import uk.co.real_logic.agrona.concurrent.UnsafeBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test that a second subscriber can be stopped and started again while data is being published. */ @RunWith(Theories.class) public class StopStartSecondSubscriberTest { public static final String CHANNEL1 = "udp://localhost:54325"; public static final String CHANNEL2 = "udp://localhost:54326"; //@DataPoint //public static final String UNICAST_URI = "udp://localhost:54325"; //@DataPoint //public static final String MULTICAST_URI = "udp://[email protected]:54326"; private static final int STREAM_ID1 = 1; private static final int STREAM_ID2 = 2; private final MediaDriver.Context mediaDriverContext1 = new MediaDriver.Context(); private final MediaDriver.Context mediaDriverContext2 = new MediaDriver.Context(); private final Aeron.Context publishingAeronContext1 = new Aeron.Context(); private final Aeron.Context subscribingAeronContext1 = new Aeron.Context(); private final Aeron.Context publishingAeronContext2 = new Aeron.Context(); private final Aeron.Context subscribingAeronContext2 = new Aeron.Context(); private Aeron publishingClient1; private Aeron subscribingClient1; private Aeron publishingClient2; private Aeron subscribingClient2; private MediaDriver driver1; private MediaDriver driver2; private Subscription subscription1; private Publication publication1; private Subscription subscription2; private Publication publication2; private UnsafeBuffer buffer = new UnsafeBuffer(new byte[8192]); private int subscriber1Count = 0; private FragmentHandler dataHandler1 = (buffer, offset, length, header) -> subscriber1Count++; private int subscriber2Count = 0; private FragmentHandler dataHandler2 = (buffer, offset, length, header) -> subscriber2Count++; private void launch(final String channel1, final int stream1, final String channel2, final int stream2) throws Exception { mediaDriverContext1.dirsDeleteOnExit(true); mediaDriverContext2.dirsDeleteOnExit(true); driver1 = MediaDriver.launchEmbedded(mediaDriverContext1); driver2 = MediaDriver.launchEmbedded(mediaDriverContext2); publishingAeronContext1.dirName(driver1.contextDirName()); publishingAeronContext2.dirName(driver1.contextDirName()); subscribingAeronContext1.dirName(driver2.contextDirName()); subscribingAeronContext2.dirName(driver2.contextDirName()); publishingClient1 = Aeron.connect(publishingAeronContext1); subscribingClient1 = Aeron.connect(subscribingAeronContext1); publishingClient2 = Aeron.connect(publishingAeronContext2); subscribingClient2 = Aeron.connect(subscribingAeronContext2); publication1 = publishingClient1.addPublication(channel1, stream1); subscription1 = subscribingClient1.addSubscription(channel1, stream1); publication2 = publishingClient2.addPublication(channel2, stream2); subscription2 = subscribingClient2.addSubscription(channel2, stream2); } @After public void closeEverything() throws Exception { if (null != publication1) { publication1.close(); } if (null != publication2) { publication2.close(); } if (null != subscription1) { subscription1.close(); } if (null != subscription2) { subscription2.close(); } subscribingClient1.close(); publishingClient1.close(); subscribingClient2.close(); publishingClient2.close(); driver1.close(); //FileSystemException deleting logbuffer with message The process cannot access the file ... unless we do a gc System.gc(); driver2.close(); } @Test(timeout = 10000) public void shouldSpinUpAndShutdown() throws Exception { launch(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); } @Test(timeout = 10000) public void shouldReceivePublishedMessage() throws Exception { launch(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); buffer.putInt(0, 1); final int numMessagesPerPublication = 1; while (publication1.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } while (publication2.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } final int fragmentsRead[] = new int[2]; SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessagesPerPublication && fragmentsRead[1] >= numMessagesPerPublication, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 10); fragmentsRead[1] += subscription2.poll(dataHandler2, 10); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(9900)); assertEquals(numMessagesPerPublication, subscriber1Count); assertEquals(numMessagesPerPublication, subscriber2Count); } public void doPublisherWork(Publication publication, AtomicBoolean running) { while (running.get()) { while (running.get() && publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } } } public void shouldReceiveMessagesAfterStopStart(final String channel1, final int stream1, final String channel2, final int stream2) throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(2); final int numMessages = 1; final MutableInteger subscriber2AfterRestartCount = new MutableInteger(); final AtomicBoolean running = new AtomicBoolean(true); final FragmentHandler dataHandler2b = (buffer, offset, length, header) -> subscriber2AfterRestartCount.value++; launch(channel1, stream1, channel2, stream2); buffer.putInt(0, 1); executor.execute(() -> doPublisherWork(publication1, running)); executor.execute(() -> doPublisherWork(publication2, running)); final int fragmentsRead[] = new int[2]; SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessages && fragmentsRead[1] >= numMessages, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 1); fragmentsRead[1] += subscription2.poll(dataHandler2, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(4900)); assertTrue(subscriber1Count >= numMessages); assertTrue(subscriber2Count >= numMessages); //Stop the second subscriber subscription2.close(); //Zero out the counters fragmentsRead[0] = 0; fragmentsRead[1] = 0; //Start the second subscriber again subscription2 = subscribingClient2.addSubscription(channel2, stream2); SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessages && fragmentsRead[1] >= numMessages, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 1); fragmentsRead[1] += subscription2.poll(dataHandler2b, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(4900)); running.set(false); assertTrue("Expecting subscriber1 to receive messages the entire time", subscriber1Count >= numMessages * 2); assertTrue("Expecting subscriber2 to receive messages before being stopped and started", subscriber2Count >= numMessages); assertTrue("Expecting subscriber2 to receive messages after being stopped and started", subscriber2AfterRestartCount.value >= numMessages); executor.shutdown(); executor.awaitTermination(100, TimeUnit.MILLISECONDS); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnSameChannelSameStream() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL1, STREAM_ID1); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnSameChannelDifferentStreams() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL1, STREAM_ID2); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnDifferentChannelsSameStream() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID1); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnDifferentChannelsDifferentStreams() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); } }
aeron-system-tests/src/test/java/uk/co/real_logic/aeron/StopStartSecondSubscriberTest.java
/* * Copyright 2014 - 2015 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.aeron; import org.junit.After; import org.junit.Test; import org.junit.experimental.theories.Theories; import org.junit.runner.RunWith; import uk.co.real_logic.aeron.driver.MediaDriver; import uk.co.real_logic.aeron.logbuffer.FragmentHandler; import uk.co.real_logic.agrona.BitUtil; import uk.co.real_logic.agrona.collections.MutableInteger; import uk.co.real_logic.agrona.concurrent.UnsafeBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test that a second subscriber can be stopped and started again while data is being published. */ @RunWith(Theories.class) public class StopStartSecondSubscriberTest { public static final String CHANNEL1 = "udp://localhost:54325"; public static final String CHANNEL2 = "udp://localhost:54326"; //@DataPoint //public static final String UNICAST_URI = "udp://localhost:54325"; //@DataPoint //public static final String MULTICAST_URI = "udp://[email protected]:54326"; private static final int STREAM_ID1 = 1; private static final int STREAM_ID2 = 2; private final MediaDriver.Context mediaDriverContext1 = new MediaDriver.Context(); private final MediaDriver.Context mediaDriverContext2 = new MediaDriver.Context(); private final Aeron.Context publishingAeronContext1 = new Aeron.Context(); private final Aeron.Context subscribingAeronContext1 = new Aeron.Context(); private final Aeron.Context publishingAeronContext2 = new Aeron.Context(); private final Aeron.Context subscribingAeronContext2 = new Aeron.Context(); private Aeron publishingClient1; private Aeron subscribingClient1; private Aeron publishingClient2; private Aeron subscribingClient2; private MediaDriver driver1; private MediaDriver driver2; private Subscription subscription1; private Publication publication1; private Subscription subscription2; private Publication publication2; private UnsafeBuffer buffer = new UnsafeBuffer(new byte[8192]); private int subscriber1Count = 0; private FragmentHandler dataHandler1 = (buffer, offset, length, header) -> subscriber1Count++; private int subscriber2Count = 0; private FragmentHandler dataHandler2 = (buffer, offset, length, header) -> subscriber2Count++; private void launch(final String channel1, final int stream1, final String channel2, final int stream2) throws Exception { mediaDriverContext1.dirsDeleteOnExit(true); mediaDriverContext2.dirsDeleteOnExit(true); driver1 = MediaDriver.launchEmbedded(mediaDriverContext1); driver2 = MediaDriver.launch(mediaDriverContext2); publishingAeronContext1.dirName(driver1.contextDirName()); publishingAeronContext2.dirName(driver1.contextDirName()); subscribingAeronContext1.dirName(driver2.contextDirName()); subscribingAeronContext2.dirName(driver2.contextDirName()); publishingClient1 = Aeron.connect(publishingAeronContext1); subscribingClient1 = Aeron.connect(subscribingAeronContext1); publishingClient2 = Aeron.connect(publishingAeronContext2); subscribingClient2 = Aeron.connect(subscribingAeronContext2); publication1 = publishingClient1.addPublication(channel1, stream1); subscription1 = subscribingClient1.addSubscription(channel1, stream1); publication2 = publishingClient2.addPublication(channel2, stream2); subscription2 = subscribingClient2.addSubscription(channel2, stream2); } @After public void closeEverything() throws Exception { if (null != publication1) { publication1.close(); } if (null != publication2) { publication2.close(); } if (null != subscription1) { subscription1.close(); } if (null != subscription2) { subscription2.close(); } subscribingClient1.close(); publishingClient1.close(); subscribingClient2.close(); publishingClient2.close(); driver1.close(); driver2.close(); } @Test(timeout = 10000) public void shouldSpinUpAndShutdown() throws Exception { launch(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); } @Test(timeout = 10000) public void shouldReceivePublishedMessage() throws Exception { launch(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); buffer.putInt(0, 1); final int numMessagesPerPublication = 1; while (publication1.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } while (publication2.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } final int fragmentsRead[] = new int[2]; SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessagesPerPublication && fragmentsRead[1] >= numMessagesPerPublication, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 10); fragmentsRead[1] += subscription2.poll(dataHandler2, 10); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(9900)); assertEquals(numMessagesPerPublication, subscriber1Count); assertEquals(numMessagesPerPublication, subscriber2Count); } public void doPublisherWork(Publication publication, AtomicBoolean running) { while (running.get()) { while (running.get() && publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); } } } public void shouldReceiveMessagesAfterStopStart(final String channel1, final int stream1, final String channel2, final int stream2) throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(2); final int numMessages = 1; final MutableInteger subscriber2AfterRestartCount = new MutableInteger(); final AtomicBoolean running = new AtomicBoolean(true); final FragmentHandler dataHandler2b = (buffer, offset, length, header) -> subscriber2AfterRestartCount.value++; launch(channel1, stream1, channel2, stream2); buffer.putInt(0, 1); executor.execute(() -> doPublisherWork(publication1, running)); executor.execute(() -> doPublisherWork(publication2, running)); final int fragmentsRead[] = new int[2]; SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessages && fragmentsRead[1] >= numMessages, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 1); fragmentsRead[1] += subscription2.poll(dataHandler2, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(4900)); assertTrue(subscriber1Count >= numMessages); assertTrue(subscriber2Count >= numMessages); //Stop the second subscriber subscription2.close(); //Zero out the counters fragmentsRead[0] = 0; fragmentsRead[1] = 0; //Start the second subscriber again subscription2 = subscribingClient2.addSubscription(channel2, stream2); SystemTestHelper.executeUntil( () -> fragmentsRead[0] >= numMessages && fragmentsRead[1] >= numMessages, (i) -> { fragmentsRead[0] += subscription1.poll(dataHandler1, 1); fragmentsRead[1] += subscription2.poll(dataHandler2b, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(4900)); running.set(false); assertTrue("Expecting subscriber1 to receive messages the entire time", subscriber1Count >= numMessages * 2); assertTrue("Expecting subscriber2 to receive messages before being stopped and started", subscriber2Count >= numMessages); assertTrue("Expecting subscriber2 to receive messages after being stopped and started", subscriber2AfterRestartCount.value >= numMessages); executor.shutdown(); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnSameChannelSameStream() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL1, STREAM_ID1); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnSameChannelDifferentStreams() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL1, STREAM_ID2); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnDifferentChannelsSameStream() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID1); } @Test(timeout = 10000) public void shouldReceiveMessagesAfterStopStartOnDifferentChannelsDifferentStreams() throws Exception { shouldReceiveMessagesAfterStopStart(CHANNEL1, STREAM_ID1, CHANNEL2, STREAM_ID2); } }
Updated to use two embedded media drivers.
aeron-system-tests/src/test/java/uk/co/real_logic/aeron/StopStartSecondSubscriberTest.java
Updated to use two embedded media drivers.
Java
apache-2.0
652dd4a7203988c44228a4576e42af2176f85bbc
0
apache/jena,jianglili007/jena,apache/jena,kidaa/jena,apache/jena,kamir/jena,tr3vr/jena,samaitra/jena,atsolakid/jena,CesarPantoja/jena,apache/jena,samaitra/jena,jianglili007/jena,apache/jena,adrapereira/jena,apache/jena,CesarPantoja/jena,adrapereira/jena,adrapereira/jena,samaitra/jena,atsolakid/jena,adrapereira/jena,jianglili007/jena,kamir/jena,jianglili007/jena,kidaa/jena,samaitra/jena,atsolakid/jena,CesarPantoja/jena,kamir/jena,adrapereira/jena,apache/jena,kamir/jena,atsolakid/jena,kamir/jena,kidaa/jena,CesarPantoja/jena,atsolakid/jena,tr3vr/jena,tr3vr/jena,tr3vr/jena,kidaa/jena,CesarPantoja/jena,kidaa/jena,samaitra/jena,kidaa/jena,jianglili007/jena,adrapereira/jena,kidaa/jena,CesarPantoja/jena,samaitra/jena,jianglili007/jena,kamir/jena,tr3vr/jena,samaitra/jena,apache/jena,tr3vr/jena,kamir/jena,jianglili007/jena,adrapereira/jena,tr3vr/jena,atsolakid/jena,atsolakid/jena,CesarPantoja/jena
/** * 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.jena.query.text.assembler; import static org.junit.Assert.assertTrue ; import java.util.Iterator; import org.apache.jena.query.text.* ; import org.junit.Test ; import com.hp.hpl.jena.assembler.Assembler ; import com.hp.hpl.jena.assembler.exceptions.AssemblerException ; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.NodeFactory; import com.hp.hpl.jena.query.Dataset ; import com.hp.hpl.jena.query.ReadWrite; import com.hp.hpl.jena.rdf.model.Resource ; import com.hp.hpl.jena.sparql.core.DatasetGraph ; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.QuadAction ; import com.hp.hpl.jena.tdb.assembler.AssemblerTDB ; import com.hp.hpl.jena.vocabulary.RDF ; /** * Test the text dataset assembler. */ public class TestTextDatasetAssembler extends AbstractTestTextAssembler { private static final String TESTBASE = "http://example.org/testDatasetAssembler/"; private static final Resource spec1; private static final Resource noDatasetPropertySpec; private static final Resource noIndexPropertySpec; private static final Resource customTextDocProducerSpec; private static final Resource customDyadicTextDocProducerSpec; @Test public void testSimpleDatasetAssembler() { Dataset dataset = (Dataset) Assembler.general.open(spec1); assertTrue(dataset.getContext().get(TextQuery.textIndex) instanceof TextIndexLucene); } @Test(expected = AssemblerException.class) public void testErrorOnNoDataset() { Assembler.general.open(noDatasetPropertySpec); } @Test(expected = AssemblerException.class) public void testErrorOnNoIndex() { Assembler.general.open(noIndexPropertySpec); } @Test public void testCustomTextDocProducer() { Dataset dataset = (Dataset)Assembler.general.open(customTextDocProducerSpec) ; DatasetGraphText dsgText = (DatasetGraphText)dataset.asDatasetGraph() ; assertTrue(dsgText.getMonitor() instanceof CustomTextDocProducer) ; dataset.close(); } @Test public void testCustomTextDocProducerDyadicConstructor() { Dataset dataset = (Dataset)Assembler.general.open(customDyadicTextDocProducerSpec) ; DatasetGraphText dsgText = (DatasetGraphText)dataset.asDatasetGraph() ; assertTrue(dsgText.getMonitor() instanceof CustomDyadicTextDocProducer) ; Node G= NodeFactory.createURI("http://example.com/G"); Node S = NodeFactory.createURI("http://example.com/S"); Node P = NodeFactory.createURI("http://example.com/P"); Node O = NodeFactory.createLiteral("http://example.com/O"); dsgText.begin(ReadWrite.WRITE); dsgText.add(G, S, P, O); dsgText.commit(); dataset.close(); } static { TextAssembler.init(); AssemblerTDB.init(); spec1 = model.createResource(TESTBASE + "spec1") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC3); noDatasetPropertySpec = model.createResource(TESTBASE + "noDatasetPropertySpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC4); noIndexPropertySpec = model.createResource(TESTBASE + "noIndexPropertySpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC); customTextDocProducerSpec = model.createResource(TESTBASE + "customTextDocProducerSpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC5) .addProperty(TextVocab.pTextDocProducer, model.createResource("java:org.apache.jena.query.text.assembler.TestTextDatasetAssembler$CustomTextDocProducer")); customDyadicTextDocProducerSpec = model.createResource(TESTBASE + "customDyadicTextDocProducerSpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC5) .addProperty(TextVocab.pTextDocProducer, model.createResource("java:org.apache.jena.query.text.assembler.TestTextDatasetAssembler$CustomDyadicTextDocProducer")); } private static class CustomTextDocProducer implements TextDocProducer { public CustomTextDocProducer(TextIndex textIndex) { } @Override public void start() { } @Override public void finish() { } @Override public void change(QuadAction qaction, Node g, Node s, Node p, Node o) { } } private static class CustomDyadicTextDocProducer implements TextDocProducer { final DatasetGraph dg; Node lastSubject = null; public CustomDyadicTextDocProducer(DatasetGraph dg, TextIndex textIndex) { this.dg = dg; } @Override public void start() { } @Override public void finish() { Iterator<Quad> qi = dg.find(null, lastSubject, Node.ANY, Node.ANY); while (qi.hasNext()) qi.next(); } @Override public void change(QuadAction qaction, Node g, Node s, Node p, Node o) { lastSubject = s; } } }
jena-text/src/test/java/org/apache/jena/query/text/assembler/TestTextDatasetAssembler.java
/** * 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.jena.query.text.assembler; import static org.junit.Assert.assertTrue ; import java.util.Iterator; import org.apache.jena.query.text.* ; import org.junit.Test ; import com.hp.hpl.jena.assembler.Assembler ; import com.hp.hpl.jena.assembler.exceptions.AssemblerException ; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.NodeFactory; import com.hp.hpl.jena.query.Dataset ; import com.hp.hpl.jena.query.ReadWrite; import com.hp.hpl.jena.rdf.model.Resource ; import com.hp.hpl.jena.sparql.core.DatasetGraph ; import com.hp.hpl.jena.sparql.core.Quad; import com.hp.hpl.jena.sparql.core.QuadAction ; import com.hp.hpl.jena.tdb.assembler.AssemblerTDB ; import com.hp.hpl.jena.vocabulary.RDF ; /** * Test the text dataset assembler. */ public class TestTextDatasetAssembler extends AbstractTestTextAssembler { private static final String TESTBASE = "http://example.org/testDatasetAssembler/"; private static final Resource spec1; private static final Resource noDatasetPropertySpec; private static final Resource noIndexPropertySpec; private static final Resource customTextDocProducerSpec; private static final Resource customDyadicTextDocProducerSpec; @Test public void testSimpleDatasetAssembler() { Dataset dataset = (Dataset) Assembler.general.open(spec1); assertTrue(dataset.getContext().get(TextQuery.textIndex) instanceof TextIndexLucene); } @Test(expected = AssemblerException.class) public void testErrorOnNoDataset() { Assembler.general.open(noDatasetPropertySpec); } @Test(expected = AssemblerException.class) public void testErrorOnNoIndex() { Assembler.general.open(noIndexPropertySpec); } @Test public void testCustomTextDocProducer() { Dataset dataset = (Dataset)Assembler.general.open(customTextDocProducerSpec) ; DatasetGraphText dsgText = (DatasetGraphText)dataset.asDatasetGraph() ; assertTrue(dsgText.getMonitor() instanceof CustomTextDocProducer) ; dataset.close(); } @Test public void testCustomTextDocProducerDyadicConstructor() { Dataset dataset = (Dataset)Assembler.general.open(customDyadicTextDocProducerSpec) ; DatasetGraphText dsgText = (DatasetGraphText)dataset.asDatasetGraph() ; assertTrue(dsgText.getMonitor() instanceof CustomDyadicTextDocProducer) ; Node G= NodeFactory.createURI("http://example.com/G"); Node S = NodeFactory.createURI("http://example.com/S"); Node P = NodeFactory.createURI("http://example.com/P"); Node O = NodeFactory.createLiteral("http://example.com/O"); dsgText.begin(ReadWrite.WRITE); dsgText.add(G, S, P, O); dsgText.commit(); dataset.close(); } static { TextAssembler.init(); AssemblerTDB.init(); spec1 = model.createResource(TESTBASE + "spec1") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC3); noDatasetPropertySpec = model.createResource(TESTBASE + "noDatasetPropertySpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC4); noIndexPropertySpec = model.createResource(TESTBASE + "noIndexPropertySpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC); customTextDocProducerSpec = model.createResource(TESTBASE + "customTextDocProducerSpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC5) .addProperty(TextVocab.pTextDocProducer, model.createResource("java:org.apache.jena.query.text.assembler.TestTextDatasetAssembler$CustomTextDocProducer")); customDyadicTextDocProducerSpec = model.createResource(TESTBASE + "customDyadicTextDocProducerSpec") .addProperty(RDF.type, TextVocab.textDataset) .addProperty(TextVocab.pDataset, SIMPLE_DATASET_SPEC) .addProperty(TextVocab.pIndex, SIMPLE_INDEX_SPEC5) .addProperty(TextVocab.pTextDocProducer, model.createResource("java:org.apache.jena.query.text.assembler.TestTextDatasetAssembler$CustomDyadicTextDocProducer")); } private static class CustomTextDocProducer implements TextDocProducer { public CustomTextDocProducer(TextIndex textIndex) { } @Override public void start() { } @Override public void finish() { } @Override public void change(QuadAction qaction, Node g, Node s, Node p, Node o) { } } private static class CustomDyadicTextDocProducer implements TextDocProducer { final DatasetGraph dg; Node lastSubject = null; public CustomDyadicTextDocProducer(DatasetGraph dg, TextIndex textIndex) { this.dg = dg; } @Override public void start() { } @Override public void finish() { Iterator<Quad> qi = dg.find(null, lastSubject, Node.ANY, Node.ANY); while (qi.hasNext()) qi.next(); } @Override public void change(QuadAction qaction, Node g, Node s, Node p, Node o) { lastSubject = s; } } }
More layout change -- introducing to reduce PR diffsize.
jena-text/src/test/java/org/apache/jena/query/text/assembler/TestTextDatasetAssembler.java
More layout change -- introducing to reduce PR diffsize.
Java
bsd-2-clause
f7043cc540359d2d26498bdc578463962a4dfa57
0
antag99/entreri
package com.lhkbob.entreri; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * <p> * The Requires annotation can be used to specify dependencies within a package * of components. If one component requires the use of another, such as a scene * or light component needing a transform, this can be a convenient way to * specify this relationship and reduce the amount of explicit configuration * during entity initialization. * <p> * When a component type that has been annotated with this annotation is added * to an entity, all required component types that are not already attached to * the entity are added. All newly added components have their owner set to the * initial component so that when it's removed, the required components are * cleaned up as well. * * @author Michael Ludwig * */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Requires { /** * @return All ComponentData types required by the annotated component type */ Class<? extends ComponentData<?>>[] value(); }
src/main/java/com/lhkbob/entreri/Requires.java
package com.lhkbob.entreri; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Requires { Class<? extends ComponentData<?>>[] value(); }
Document Requires annotation
src/main/java/com/lhkbob/entreri/Requires.java
Document Requires annotation
Java
bsd-2-clause
6ad9ccaace49188f0de992331b6a9742f9fdeb32
0
markovmodel/stallone,markovmodel/stallone
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stallone.util; /** * * @author noe */ import java.io.*; public class JobTools { public static void sleep(long millis) { try { Thread.currentThread().sleep(millis); } catch (InterruptedException e) { } } public static boolean isAlive(Process p) { try { p.exitValue(); return (false); } catch (IllegalThreadStateException e) { return (true); } } public static void executePoor(String wdir, String command, String strInputFile, String strOutputFile) throws Exception { String strStarter = wdir + "/___starter" + MathTools.randomInt(0, Integer.MAX_VALUE) + ".exe"; // writing the starter FileOutputStream starter = new FileOutputStream(strStarter); String cmdfull = "cd " + wdir + "\n" + command; if (strInputFile != null) { cmdfull = cmdfull + " < " + strInputFile; } if (strOutputFile != null) { cmdfull = cmdfull + " > " + strOutputFile; } cmdfull = cmdfull + " \n"; starter.write(cmdfull.getBytes()); // making the starter executable Process p = Runtime.getRuntime().exec("chmod 700 " + strStarter); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); // execute and wait p = Runtime.getRuntime().exec("bash " + strStarter); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); // delete starter starter.close(); new File(strStarter).delete(); } public static String writeStarter(String wdir, String content) throws Exception { String strStarter = wdir + "/___starter" + MathTools.randomInt(0, Integer.MAX_VALUE) + ".exe"; FileOutputStream starter = new FileOutputStream(strStarter); starter.write(content.getBytes()); starter.close(); // making the starter executable Process p = Runtime.getRuntime().exec("chmod 700 " + strStarter); p.waitFor(); return (strStarter); } /** Generates a temporary directory, copies the needed files into it. Returns the name of the directory. It is left to the user to remove the directory when it is no longer needed. @param neededFiles a list of file (full pathname) which are needed in the directory to execute the command @param wdir the directory in which the temporary subdirectory should be generated, e.g. "." or "tmp". @return the name of the generated directory. */ public static String tempDir(String[] neededFiles, String wdir) throws Exception { int id = 0; File tmpdir = null; String dirname = null; // determine id and directory name. do { id = MathTools.randomInt(0, Integer.MAX_VALUE); dirname = wdir + "/___tmp_" + id; tmpdir = new File(dirname); } while (tmpdir.exists()); // generate directory tmpdir.mkdir(); // copy files into directory, if available if (neededFiles != null) { for (int i = 0; i < neededFiles.length; i++) { execute("cp " + neededFiles[i] + " " + dirname); } } return (dirname); } public static void execute(String command) { try { Process p = Runtime.getRuntime().exec(command); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void execute(String command, String strInputFile, String strOutputFile) throws IOException { Process p = startJob(command, strInputFile, strOutputFile); try { p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); } catch (InterruptedException e) { e.printStackTrace(); System.exit(-1); } } /** Starts a new job which reads the given input file from stdin and writes to the given output file from stdout. */ public static Process startJob(String command, String strInputFile, String strOutputFile) throws IOException { Process p = Runtime.getRuntime().exec(command); FileInputStream inFile = new FileInputStream(strInputFile); byte[] byteIn = new byte[inFile.available()]; inFile.read(byteIn); inFile.close(); FileOutputStream outFile = new FileOutputStream(strOutputFile); // stream input file into Charmm process OutputStream pOut = p.getOutputStream(); pOut.write(byteIn); pOut.flush(); readToEnd(p.getInputStream(), outFile); return (p); } /** read from the input stream and writes to the output stream as long as something is available. */ public static void readToEnd(InputStream in, OutputStream out) { try { int c = 0; while (c != -1) { c = in.read(); System.out.print((char) c); out.write(c); } } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } }
src/stallone/util/JobTools.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package stallone.util; /** * * @author noe */ import java.io.*; public class JobTools { public static void sleep(long millis) { try { Thread.currentThread().sleep(millis); } catch (InterruptedException e) { } } public static boolean isAlive(Process p) { try { p.exitValue(); return (false); } catch (IllegalThreadStateException e) { return (true); } } public static void executePoor(String wdir, String command, String strInputFile, String strOutputFile) throws Exception { String strStarter = wdir + "/___starter" + MathTools.randomInt(0, Integer.MAX_VALUE) + ".exe"; // writing the starter FileOutputStream starter = new FileOutputStream(strStarter); String cmdfull = "cd " + wdir + "\n" + command; if (strInputFile != null) { cmdfull = cmdfull + " < " + strInputFile; } if (strOutputFile != null) { cmdfull = cmdfull + " > " + strOutputFile; } cmdfull = cmdfull + " \n"; starter.write(cmdfull.getBytes()); // making the starter executable Process p = Runtime.getRuntime().exec("chmod 700 " + strStarter); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); // execute and wait p = Runtime.getRuntime().exec("bash " + strStarter); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); // delete starter starter.close(); new File(strStarter).delete(); } public static String writeStarter(String wdir, String content) throws Exception { String strStarter = wdir + "/___starter" + MathTools.randomInt(0, Integer.MAX_VALUE) + ".exe"; FileOutputStream starter = new FileOutputStream(strStarter); starter.write(content.getBytes()); // making the starter executable Process p = Runtime.getRuntime().exec("chmod 700 " + strStarter); p.waitFor(); return (strStarter); } /** Generates a temporary directory, copies the needed files into it. Returns the name of the directory. It is left to the user to remove the directory when it is no longer needed. @param neededFiles a list of file (full pathname) which are needed in the directory to execute the command @param wdir the directory in which the temporary subdirectory should be generated, e.g. "." or "tmp". @return the name of the generated directory. */ public static String tempDir(String[] neededFiles, String wdir) throws Exception { int id = 0; File tmpdir = null; String dirname = null; // determine id and directory name. do { id = MathTools.randomInt(0, Integer.MAX_VALUE); dirname = wdir + "/___tmp_" + id; tmpdir = new File(dirname); } while (tmpdir.exists()); // generate directory tmpdir.mkdir(); // copy files into directory, if available if (neededFiles != null) { for (int i = 0; i < neededFiles.length; i++) { execute("cp " + neededFiles[i] + " " + dirname); } } return (dirname); } public static void execute(String command) { try { Process p = Runtime.getRuntime().exec(command); p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public static void execute(String command, String strInputFile, String strOutputFile) throws IOException { Process p = startJob(command, strInputFile, strOutputFile); try { p.waitFor(); p.getErrorStream().close(); p.getInputStream().close(); p.getOutputStream().close(); p.destroy(); } catch (InterruptedException e) { e.printStackTrace(); System.exit(-1); } } /** Starts a new job which reads the given input file from stdin and writes to the given output file from stdout. */ public static Process startJob(String command, String strInputFile, String strOutputFile) throws IOException { Process p = Runtime.getRuntime().exec(command); FileInputStream inFile = new FileInputStream(strInputFile); byte[] byteIn = new byte[inFile.available()]; inFile.read(byteIn); FileOutputStream outFile = new FileOutputStream(strOutputFile); // stream input file into Charmm process OutputStream pOut = p.getOutputStream(); pOut.write(byteIn); pOut.flush(); readToEnd(p.getInputStream(), outFile); return (p); } /** read from the input stream and writes to the output stream as long as something is available. */ public static void readToEnd(InputStream in, OutputStream out) { try { int c = 0; while (c != -1) { c = in.read(); System.out.print((char) c); out.write(c); } } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } }
[JobTools] close files, which are not needed anymore
src/stallone/util/JobTools.java
[JobTools] close files, which are not needed anymore
Java
bsd-2-clause
0e4f878da94d6fe34250632720f08c62073e6032
0
malensek/sing
package io.sigpipe.sing.query; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import io.sigpipe.sing.dataset.feature.FeatureType; import io.sigpipe.sing.graph.DataContainer; import io.sigpipe.sing.graph.GraphMetrics; import io.sigpipe.sing.graph.Vertex; import io.sigpipe.sing.serialization.SerializationOutputStream; public class RelationalQuery extends Query { private Set<Vertex> pruned; private GraphMetrics metrics; public RelationalQuery() { } public RelationalQuery(GraphMetrics metrics) { this.metrics = metrics; } @Override public void execute(Vertex root) throws IOException, QueryException { if (this.metrics != null) { /* To make sure we don't spend time resizing the pruned HashSet, set * it to the number of vertices in the graph divided by the default * load factor. */ this.pruned = new HashSet<Vertex>( (int) (metrics.getVertexCount() / 0.75)); } else { this.pruned = new HashSet<>(); } System.out.println("expressions: " + expressions.size()); prune(root, 0); System.out.println("Pruned " + pruned.size() + " vertices"); public void serializeResults(Vertex vertex, SerializationOutputStream out) throws IOException { if (pruned.contains(vertex)) { return; } vertex.getLabel().serialize(out); if (vertex.hasData() == false) { vertex.setData(new DataContainer()); } vertex.getData().serialize(out); /* How many neighbors are still valid after the pruning process? */ int numNeighbors = 0; for (Vertex v : vertex.getAllNeighbors()) { if (pruned.contains(v) == false) { numNeighbors++; } } out.writeInt(numNeighbors); for (Vertex v : vertex.getAllNeighbors()) { if (pruned.contains(v) == false) { serializeResults(v, out); } } } private boolean prune(Vertex vertex, int expressionsEvaluated) throws QueryException { if (expressionsEvaluated == this.expressions.size()) { /* There are no further expressions to evaluate. Therefore, we must * assume all children from this point are relevant to the query. */ return true; } boolean foundSubMatch = false; String childFeature = vertex.getFirstNeighbor().getLabel().getName(); List<Expression> expList = this.expressions.get(childFeature); if (expList != null) { Set<Vertex> matches = evaluate(vertex, expList); if (matches.size() == 0) { pruned.add(vertex); return false; } for (Vertex match : matches) { if (match == null) { continue; } if (match.getLabel().getType() == FeatureType.NULL) { continue; } if (prune(match, expressionsEvaluated + 1) == true) { foundSubMatch = true; } } Set<Vertex> nonMatches = new HashSet<>(vertex.getAllNeighbors()); nonMatches.removeAll(matches); for (Vertex nonMatch : nonMatches) { pruned.add(nonMatch); } } else { /* No expression operates on this vertex. Consider all children. */ for (Vertex neighbor : vertex.getAllNeighbors()) { if (prune(neighbor, expressionsEvaluated) == true) { foundSubMatch = true; } } } if (foundSubMatch == false) { pruned.add(vertex); } return foundSubMatch; } }
src/main/java/io/sigpipe/sing/query/RelationalQuery.java
package io.sigpipe.sing.query; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import io.sigpipe.sing.dataset.feature.FeatureType; import io.sigpipe.sing.graph.DataContainer; import io.sigpipe.sing.graph.Vertex; import io.sigpipe.sing.serialization.SerializationOutputStream; public class RelationalQuery extends Query { private Set<Vertex> pruned; public RelationalQuery() { } @Override public void execute(Vertex root) throws IOException, QueryException { this.pruned = new HashSet<Vertex>(); System.out.println("expressions: " + expressions.size()); prune(root, 0); System.out.println("Pruned " + pruned.size() + " vertices"); public void serializeResults(Vertex vertex, SerializationOutputStream out) throws IOException { if (pruned.contains(vertex)) { return; } vertex.getLabel().serialize(out); if (vertex.hasData() == false) { vertex.setData(new DataContainer()); } vertex.getData().serialize(out); /* How many neighbors are still valid after the pruning process? */ int numNeighbors = 0; for (Vertex v : vertex.getAllNeighbors()) { if (pruned.contains(v) == false) { numNeighbors++; } } out.writeInt(numNeighbors); for (Vertex v : vertex.getAllNeighbors()) { if (pruned.contains(v) == false) { serializeResults(v, out); } } } private boolean prune(Vertex vertex, int expressionsEvaluated) throws QueryException { if (expressionsEvaluated == this.expressions.size()) { /* There are no further expressions to evaluate. Therefore, we must * assume all children from this point are relevant to the query. */ return true; } boolean foundSubMatch = false; String childFeature = vertex.getFirstNeighbor().getLabel().getName(); List<Expression> expList = this.expressions.get(childFeature); if (expList != null) { Set<Vertex> matches = evaluate(vertex, expList); if (matches.size() == 0) { pruned.add(vertex); return false; } for (Vertex match : matches) { if (match == null) { continue; } if (match.getLabel().getType() == FeatureType.NULL) { continue; } if (prune(match, expressionsEvaluated + 1) == true) { foundSubMatch = true; } } Set<Vertex> nonMatches = new HashSet<>(vertex.getAllNeighbors()); nonMatches.removeAll(matches); for (Vertex nonMatch : nonMatches) { pruned.add(nonMatch); } } else { /* No expression operates on this vertex. Consider all children. */ for (Vertex neighbor : vertex.getAllNeighbors()) { if (prune(neighbor, expressionsEvaluated) == true) { foundSubMatch = true; } } } if (foundSubMatch == false) { pruned.add(vertex); } return foundSubMatch; } }
Add smart set construction based on graph metrics
src/main/java/io/sigpipe/sing/query/RelationalQuery.java
Add smart set construction based on graph metrics
Java
epl-1.0
341652722375f485093ad04a4a601b91e5cda6f5
0
Berloe/SDMapGen
org.smapgen/scl/repo/maven/Artifact.java
package org.smapgen.scl.repo.maven; /** * @author Alberto Fuentes Gómez * */ public class Artifact { private String group; private String artifact; private String version; private String scope; /** * @return the scope */ protected String getScope() { return scope; } /** * @param scope the scope to set */ protected void setScope(String scope) { this.scope = scope; } /** * @return the group */ protected String getGroup() { return group; } /** * @param group the group to set */ protected void setGroup(String group) { this.group = group; } /** * @return the artifact */ protected String getArtifact() { return artifact; } /** * @param artifact the artifact to set */ protected void setArtifact(String artifact) { this.artifact = artifact; } /** * @return the version */ protected String getVersion() { return version; } /** * @param version the version to set */ protected void setVersion(String version) { this.version = version; } public String getPomName(){ return getArtifact().concat("-").concat(getVersion()).concat(".pom"); } public String getRelativePath(){ return System.getProperty("file.separator").concat(getGroup().replace(".", System.getProperty("file.separator")).concat(System.getProperty("file.separator").concat(getArtifact())).concat(System.getProperty("file.separator")).concat(getVersion()!=null?getVersion():"")); } }
Delete Artifact.java
org.smapgen/scl/repo/maven/Artifact.java
Delete Artifact.java
Java
mit
6fc9762bf838ba82b2281cbc8288ec8c7c58c63d
0
pinussilvestrus/bncl,pinussilvestrus/bncl,pinussilvestrus/bncl,pinussilvestrus/bncl
package de.niklaskiefer.bnclWeb; import de.niklaskiefer.bnclCore.BnclToXmlWriter; import de.niklaskiefer.bnclCore.parser.BnclElementParser; import de.niklaskiefer.bnclCore.parser.BnclEventParser; import de.niklaskiefer.bnclCore.parser.BnclGatewayParser; import de.niklaskiefer.bnclCore.parser.BnclParser; import de.niklaskiefer.bnclCore.parser.BnclSequenceFlowParser; import de.niklaskiefer.bnclCore.parser.BnclTaskParser; import de.niklaskiefer.bnclWeb.model.BnclStatement; import de.niklaskiefer.bnclWeb.model.BnclStatementRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Controller public class MainController { private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class); private static final String BNCL_PARSER_ERROR = "Error in parsing bncl statement!"; private static final String BNCL_PARSER_SUCCESS = "Successfully parsing bncl statement!"; private static final String testBncl = "lets create a process with " + "signalstartevent signed startEvent1 called message incoming with " + "errorevent signed event1 called 3 Stunden vergangen with " + "scripttask signed usertask1 called dosomething with " + "usertask signed usertask2 with " + "parallelgateway signed gateway1 with " + "parallelgateway signed gateway2 with " + "sequenceflow comesfrom startevent1 goesto event1 with " + "sequenceflow comesfrom event1 goesto gateway1 with " + "sequenceflow comesfrom gateway1 goesto usertask1 with " + "sequenceflow comesfrom gateway1 goesto usertask2 with " + "sequenceflow comesfrom usertask1 goesto gateway2 with " + "sequenceflow comesfrom usertask2 goesto gateway2 with " + "messagethrowevent signed endevent1 called terminated with " + "sequenceflow comesfrom gateway2 goesto endevent1"; @Autowired private BnclStatementRepository bnclStatementRepository; @ModelAttribute("bnclWords") public List<String> bnclWords() { return getAllBnclWords(); } @RequestMapping("/") public String main(Model model) { model.addAttribute("xml", ""); return "main"; } @RequestMapping(value = "/convertBncl", method = RequestMethod.POST) public String convert(@RequestParam(value="bncl", required=true) String bncl, Model model) { model.addAttribute("bncl", bncl); try { model.addAttribute("xml", convertBnclToXML(bncl)); model.addAttribute("notificationMessage", BNCL_PARSER_SUCCESS); } catch (Exception e) { LOGGER.info(BNCL_PARSER_ERROR); model.addAttribute("err", true); model.addAttribute("notificationMessage", e.getMessage()); model.addAttribute("xml", ""); } // db should be independent from converting try { // this.saveBnclStatementToDatabase(bncl); } catch (Exception e) { e.printStackTrace(); System.out.println(e); } return "main"; } private String convertBnclToXML(String bncl) throws Exception { BnclToXmlWriter writer = new BnclToXmlWriter(); return writer.convertBnclToXML(bncl); } private List<String> getAllBnclWords() { final List<String> words = new ArrayList<>(); // basic words words.add(BnclParser.BEGINNING_GROUP); words.add(BnclParser.ELEMENT_BEGINNING); // attributes BnclElementParser elementParser = new BnclElementParser(); for(BnclElementParser.AttributeElement element : elementParser.getAttributeTypes()) { words.add(element.getBncl()); } // events BnclEventParser eventParser = new BnclEventParser(); for(BnclEventParser.EventElement element : eventParser.getEventTypes()) { words.add(element.getKeyword()); } // tasks BnclTaskParser taskParser = new BnclTaskParser(); for(BnclTaskParser.TaskElement element : taskParser.getTaskTypes()) { words.add(element.getKeyword()); } // gateways BnclGatewayParser gatewayParser = new BnclGatewayParser(); for(BnclGatewayParser.GatewayType element : gatewayParser.getGatewayTypes()) { words.add(element.getKeyword()); } // sequence flows words.add(BnclSequenceFlowParser.COMES_FROM); words.add(BnclSequenceFlowParser.SEQUENCE_FLOW_KEYWORD); words.add(BnclSequenceFlowParser.GOES_TO); return words; } private void saveBnclStatementToDatabase(String bncl) { bnclStatementRepository.save(new BnclStatement(bncl)); } }
web/src/main/java/de/niklaskiefer/bnclWeb/MainController.java
package de.niklaskiefer.bnclWeb; import de.niklaskiefer.bnclCore.BnclToXmlWriter; import de.niklaskiefer.bnclCore.parser.BnclElementParser; import de.niklaskiefer.bnclCore.parser.BnclEventParser; import de.niklaskiefer.bnclCore.parser.BnclGatewayParser; import de.niklaskiefer.bnclCore.parser.BnclParser; import de.niklaskiefer.bnclCore.parser.BnclSequenceFlowParser; import de.niklaskiefer.bnclCore.parser.BnclTaskParser; import de.niklaskiefer.bnclWeb.model.BnclStatement; import de.niklaskiefer.bnclWeb.model.BnclStatementRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Controller public class MainController { private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class); private static final String BNCL_PARSER_ERROR = "Error in parsing bncl statement!"; private static final String BNCL_PARSER_SUCCESS = "Successfully parsing bncl statement!"; private static final String testBncl = "lets create a process with " + "signalstartevent signed startEvent1 called message incoming with " + "errorevent signed event1 called 3 Stunden vergangen with " + "scripttask signed usertask1 called dosomething with " + "usertask signed usertask2 with " + "parallelgateway signed gateway1 with " + "parallelgateway signed gateway2 with " + "sequenceflow comesfrom startevent1 goesto event1 with " + "sequenceflow comesfrom event1 goesto gateway1 with " + "sequenceflow comesfrom gateway1 goesto usertask1 with " + "sequenceflow comesfrom gateway1 goesto usertask2 with " + "sequenceflow comesfrom usertask1 goesto gateway2 with " + "sequenceflow comesfrom usertask2 goesto gateway2 with " + "messagethrowevent signed endevent1 called terminated with " + "sequenceflow comesfrom gateway2 goesto endevent1"; @Autowired private BnclStatementRepository bnclStatementRepository; @ModelAttribute("bnclWords") public List<String> bnclWords() { return getAllBnclWords(); } @RequestMapping("/") public String main(Model model) { model.addAttribute("xml", ""); return "main"; } @RequestMapping(value = "/convertBncl", method = RequestMethod.POST) public String convert(@RequestParam(value="bncl", required=true) String bncl, Model model) { model.addAttribute("bncl", bncl); try { model.addAttribute("xml", convertBnclToXML(bncl)); model.addAttribute("notificationMessage", BNCL_PARSER_SUCCESS); } catch (Exception e) { LOGGER.info(BNCL_PARSER_ERROR); model.addAttribute("err", true); model.addAttribute("notificationMessage", e.getMessage()); model.addAttribute("xml", ""); } // db should be independent from converting try { this.saveBnclStatementToDatabase(bncl); } catch (Exception e) { e.printStackTrace(); System.out.println(e); } return "main"; } private String convertBnclToXML(String bncl) throws Exception { BnclToXmlWriter writer = new BnclToXmlWriter(); return writer.convertBnclToXML(bncl); } private List<String> getAllBnclWords() { final List<String> words = new ArrayList<>(); // basic words words.add(BnclParser.BEGINNING_GROUP); words.add(BnclParser.ELEMENT_BEGINNING); // attributes BnclElementParser elementParser = new BnclElementParser(); for(BnclElementParser.AttributeElement element : elementParser.getAttributeTypes()) { words.add(element.getBncl()); } // events BnclEventParser eventParser = new BnclEventParser(); for(BnclEventParser.EventElement element : eventParser.getEventTypes()) { words.add(element.getKeyword()); } // tasks BnclTaskParser taskParser = new BnclTaskParser(); for(BnclTaskParser.TaskElement element : taskParser.getTaskTypes()) { words.add(element.getKeyword()); } // gateways BnclGatewayParser gatewayParser = new BnclGatewayParser(); for(BnclGatewayParser.GatewayType element : gatewayParser.getGatewayTypes()) { words.add(element.getKeyword()); } // sequence flows words.add(BnclSequenceFlowParser.COMES_FROM); words.add(BnclSequenceFlowParser.SEQUENCE_FLOW_KEYWORD); words.add(BnclSequenceFlowParser.GOES_TO); return words; } private void saveBnclStatementToDatabase(String bncl) { bnclStatementRepository.save(new BnclStatement(bncl)); } }
chore(web): disable db saving for now
web/src/main/java/de/niklaskiefer/bnclWeb/MainController.java
chore(web): disable db saving for now
Java
mit
6c19b43fb5ed6bb83b814205729151e7c444146a
0
jgrabenstein/Rapture,scarabus/Rapture,RapturePlatform/Rapture,jonathan-major/Rapture,amkimian/Rapture,dukenguyen/Rapture,dukenguyen/Rapture,jonathan-major/Rapture,dukenguyen/Rapture,amkimian/Rapture,jgrabenstein/Rapture,jonathan-major/Rapture,dukenguyen/Rapture,RapturePlatform/Rapture,RapturePlatform/Rapture,amkimian/Rapture,RapturePlatform/Rapture,amkimian/Rapture,jgrabenstein/Rapture,dukenguyen/Rapture,jgrabenstein/Rapture,dukenguyen/Rapture,scarabus/Rapture,jonathan-major/Rapture,jonathan-major/Rapture,jonathan-major/Rapture,amkimian/Rapture,scarabus/Rapture,jgrabenstein/Rapture,RapturePlatform/Rapture,jonathan-major/Rapture,jgrabenstein/Rapture,scarabus/Rapture,RapturePlatform/Rapture,dukenguyen/Rapture,jgrabenstein/Rapture,scarabus/Rapture,amkimian/Rapture,scarabus/Rapture,scarabus/Rapture,RapturePlatform/Rapture,amkimian/Rapture
/** * The MIT License (MIT) * * Copyright (c) 2011-2016 Incapture Technologies LLC * * 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 rapture.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import org.apache.log4j.Logger; /** * Utility around networks * * @author amkimian * */ public class NetworkUtil { private static final Logger log = Logger.getLogger(NetworkUtil.class); private NetworkUtil() { } public static String getServerIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.error("Unable to get the IP address of this machine", e); return null; } } /** * Get the IP address of the local machine, but only if it's a site local address, not the public internet facing address. This is usually a class-C type * address and allows access from within a network or subnet, for example. * * @return */ public static String getSiteLocalServerIP() { Enumeration<NetworkInterface> nics; try { nics = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { log.error("Unable to access network interfaces on this machine", e); return null; } while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); if (log.isDebugEnabled()) { log.debug("Processing nic: " + nic.getName() + ":" + nic.getDisplayName()); } Enumeration<InetAddress> addrs = nic.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); log.debug("IP addr is: " + addr.getHostAddress()); if (addr.isSiteLocalAddress() || (addr.isLoopbackAddress())) { return addr.getHostAddress(); } } } return null; } public static String getServerName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.error("Unable to get hostname of this machine", e); return null; } } }
Libs/RaptureCommon/src/main/java/rapture/util/NetworkUtil.java
/** * The MIT License (MIT) * * Copyright (c) 2011-2016 Incapture Technologies LLC * * 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 rapture.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import org.apache.log4j.Logger; /** * Utility around networks * * @author amkimian * */ public class NetworkUtil { private static final Logger log = Logger.getLogger(NetworkUtil.class); private NetworkUtil() { } public static String getServerIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.error("Unable to get the IP address of this machine", e); return null; } } /** * Get the IP address of the local machine, but only if it's a site local address, not the public internet facing address. This is usually a class-C type * address and allows access from within a network or subnet, for example. * * @return */ public static String getSiteLocalServerIP() { Enumeration<NetworkInterface> nics; try { nics = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { log.error("Unable to access network interfaces on this machine", e); return null; } while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); if (log.isDebugEnabled()) { log.debug("Processing nic: " + nic.getName() + ":" + nic.getDisplayName()); } Enumeration<InetAddress> addrs = nic.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); log.debug("IP addr is: " + addr.getHostAddress()); if (addr.isSiteLocalAddress()) { return addr.getHostAddress(); } } } return null; } public static String getServerName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.error("Unable to get hostname of this machine", e); return null; } } }
UNFILED: handle loopback address
Libs/RaptureCommon/src/main/java/rapture/util/NetworkUtil.java
UNFILED: handle loopback address
Java
mit
bdb2dec49c96fa6baccb2909e4d6d09e4f6c1714
0
Winwardo/rultor-example
package rultor.example; public class Calculator { public Calculator() { } public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } }
src/main/java/rultor/example/Calculator.java
package rultor.example; public class Calculator { public Calculator() { } public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a + b; } }
Fix Calculator.multiply using +
src/main/java/rultor/example/Calculator.java
Fix Calculator.multiply using +
Java
mit
c8b6585eb013af61b81b7b45e8bd6dbfef3b00bf
0
AgeOfWar/Telejam
package io.github.ageofwar.telejam.text; import io.github.ageofwar.telejam.chats.Channel; import io.github.ageofwar.telejam.chats.Chat; import io.github.ageofwar.telejam.chats.SuperGroup; import io.github.ageofwar.telejam.messages.Message; import io.github.ageofwar.telejam.messages.MessageEntity; import io.github.ageofwar.telejam.users.User; import java.util.ArrayList; import java.util.Optional; /** * Factory class for {@link Text}. * * @author Michi Palazzo * @see Text */ public class TextBuilder { static final String TEXT_MENTION_LINK = "tg://user?id="; static final String TELEGRAM_LINK = "https://t.me"; /** * Builder of the string of the Text. */ private final StringBuilder builder; /** * Array of entities. */ private final ArrayList<MessageEntity> entities; /** * Constructs a TextBuilder. */ public TextBuilder() { entities = new ArrayList<>(); builder = new StringBuilder(); } /** * Appends a text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder append(String text) { builder.append(text); return this; } /** * Appends a text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder append(Text text) { for (MessageEntity entity : text.getEntities()) { append( entity.move(entity.getOffset() + length(), entity.getLength()), entity.getType() != MessageEntity.Type.BOT_COMMAND && entity.getType() != MessageEntity.Type.URL && entity.getType() != MessageEntity.Type.HASHTAG && entity.getType() != MessageEntity.Type.EMAIL ); } builder.append(text); return this; } /** * Appends a text builder to this TextBuilder. * * @param builder the builder to append * @return this instance */ public TextBuilder append(TextBuilder builder) { for (MessageEntity entity : builder.entities) { append( entity.move(entity.getOffset() + length(), entity.getLength()), entity.getType() != MessageEntity.Type.BOT_COMMAND && entity.getType() != MessageEntity.Type.URL && entity.getType() != MessageEntity.Type.HASHTAG && entity.getType() != MessageEntity.Type.EMAIL ); } builder.append(builder.builder.toString()); return this; } /** * Appends a bold text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendBold(String text) { return append(text, MessageEntity.Type.BOLD, true); } /** * Appends a italic text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendItalic(String text) { return append(text, MessageEntity.Type.ITALIC, true); } /** * Appends a code text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendCode(String text) { return append(text, MessageEntity.Type.CODE, true); } /** * Appends a code block text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendCodeBlock(String text) { return append(text, MessageEntity.Type.CODE_BLOCK, true); } /** * Appends a link to this TextBuilder. * * @param link the link to append * @return this instance */ public TextBuilder appendLink(Link link) { return append(link.getText(), link.getUrl(), true); } /** * Appends a link to this TextBuilder. * * @param text the text of the link * @param url the url of the link * @return this instance */ public TextBuilder appendLink(String text, String url) { return append(text, url, true); } /** * Appends a link to a message to this TextBuilder. * * @param text the text of the link * @param message the message to link * @return this instance */ public TextBuilder appendLink(String text, Message message) { return append(text, toLink(message), true); } /** * Appends a mention to this TextBuilder. * * @param text the username to mention, without <code>@</code> * @return this instance */ public TextBuilder appendMention(String text) { return append("@" + text, MessageEntity.Type.MENTION, false); } /** * Appends a mention to this TextBuilder, or a text mention * if the username is not available. * * @param mention mentioned user * @return this instance */ public TextBuilder appendMention(User mention) { return mention.getUsername() .map(this::appendMention) .orElseGet(() -> appendTextMention(mention)); } /** * Appends a text mention to this TextBuilder. * * @param mention the mentioned to append * @return this instance */ public TextBuilder appendTextMention(Mention mention) { return append(mention.getText(), mention.getUser(), true); } /** * Appends a text mention to this TextBuilder. * * @param text the text of the mention * @param mention the mention * @return this instance */ public TextBuilder appendTextMention(String text, User mention) { return append(text, mention, true); } /** * Appends a text mention to this TextBuilder. * * @param mention the mentioned user * @return this instance */ public TextBuilder appendTextMention(User mention) { return append(mention.getName(), mention, true); } /** * Appends an hashtag to this TextBuilder. * * @param hashtag the hashtag to append, without <code>#</code> * @return this instance */ public TextBuilder appendHashtag(String hashtag) { return append("#" + hashtag, MessageEntity.Type.HASHTAG, false); } /** * Appends a bot command to this TextBuilder. * * @param botCommand the bot command to append, without <code>/</code> * @return this instance */ public TextBuilder appendBotCommand(String botCommand) { return append("/" + botCommand, MessageEntity.Type.BOT_COMMAND, false); } /** * Appends an url to this TextBuilder. * * @param url the url to append * @return this instance */ public TextBuilder appendUrl(String url) { return append(url, MessageEntity.Type.URL, false); } /** * Appends a link to a message to this TextBuilder. * * @param message message to link * @return this instance */ public TextBuilder appendUrl(Message message) { return append(toLink(message), MessageEntity.Type.URL, false); } /** * Appends an email to this TextBuilder. * * @param email the email to append * @return this instance */ public TextBuilder appendEmail(String email) { return append(email, MessageEntity.Type.EMAIL, false); } /** * Appends a phone number to this TextBuilder. * * @param phoneNumber the phone number to append * @return this instance */ public TextBuilder appendPhoneNumber(String phoneNumber) { return append(phoneNumber, MessageEntity.Type.PHONE_NUMBER, false); } /** * Appends a cashtag to this TextBuilder. * * @param cashtag the cashtag to append * @return this instance */ public TextBuilder appendCashtag(String cashtag) { return append("$" + cashtag.toUpperCase(), MessageEntity.Type.CASHTAG, false); } /** * Appends a mention to this TextBuilder. * * @param text the text of the mention * @param mention the id of the mentioned user * @return this instance * @deprecated use this method only if you can't * obtain the user relative to its id */ @Deprecated public TextBuilder appendMention(String text, long mention) { return appendLink(text, TEXT_MENTION_LINK + mention); } private String toLink(Message message) { Chat chat = message.getChat(); if (chat instanceof SuperGroup || chat instanceof Channel) { Optional<String> username = chat instanceof SuperGroup ? ((SuperGroup) chat).getUsername() : ((Channel) chat).getUsername(); if (username.isPresent()) { return TELEGRAM_LINK + "/" + username.get() + "/" + message.getId(); } else { return TELEGRAM_LINK + "/c/" + Long.toString(message.getChat().getId()).substring(4) + "/" + message.getId(); } } return TELEGRAM_LINK + "/c/" + message.getChat().getId() + "/" + message.getId(); } private TextBuilder append(String text, MessageEntity.Type type, boolean concat) { append(new MessageEntity(type, builder.length(), text.length()), concat); builder.append(text); return this; } private TextBuilder append(String text, String url, boolean concat) { append(new MessageEntity(url, builder.length(), text.length()), concat); builder.append(text); return this; } private TextBuilder append(String text, User user, boolean concat) { append(new MessageEntity(user, builder.length(), text.length()), concat); builder.append(text); return this; } private void append(MessageEntity entity, boolean concat) { if (entity.getLength() > 0) { if (!concat || entities.isEmpty()) { entities.add(entity); } else { MessageEntity lastEntity = entities.get(entities.size() - 1); if (lastEntity.getType() == entity.getType() && entity.getUrl().equals(lastEntity.getUrl()) && entity.getUser().equals(lastEntity.getUser()) && lastEntity.getOffset() + lastEntity.getLength() == entity.getOffset()) { entities.set( entities.size() - 1, lastEntity.move(lastEntity.getOffset(), lastEntity.getLength() + entity.getLength()) ); } else { entities.add(entity); } } } } /** * Returns the length of the text. * * @return the length of the text */ public int length() { return builder.length(); } /** * Sets the length of the text. * * @param length the new length * @throws StringIndexOutOfBoundsException if the {@code newLength} argument is negative. */ public void setLength(int length) { if (length < 0) throw new StringIndexOutOfBoundsException(length); builder.setLength(length); for (int i = entities.size() - 1; i >= 0; i--) { MessageEntity entity = entities.get(i); if (entity.getOffset() > length) { entities.remove(entity); } else if (entity.getOffset() + entity.getLength() > length) { entities.remove(entity); int newLength = length - entity.getOffset(); entities.add(entity.move(entity.getOffset(), newLength)); } else { break; } } } /** * Builds the Text. * * @return the created text */ public Text build() { return new Text(builder.toString(), entities); } }
src/main/java/io/github/ageofwar/telejam/text/TextBuilder.java
package io.github.ageofwar.telejam.text; import io.github.ageofwar.telejam.chats.Chat; import io.github.ageofwar.telejam.chats.SuperGroup; import io.github.ageofwar.telejam.messages.Message; import io.github.ageofwar.telejam.messages.MessageEntity; import io.github.ageofwar.telejam.users.User; import java.util.ArrayList; import java.util.Optional; /** * Factory class for {@link Text}. * * @author Michi Palazzo * @see Text */ public class TextBuilder { static final String TEXT_MENTION_LINK = "tg://user?id="; static final String TELEGRAM_LINK = "https://t.me"; /** * Builder of the string of the Text. */ private final StringBuilder builder; /** * Array of entities. */ private final ArrayList<MessageEntity> entities; /** * Constructs a TextBuilder. */ public TextBuilder() { entities = new ArrayList<>(); builder = new StringBuilder(); } /** * Appends a text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder append(String text) { builder.append(text); return this; } /** * Appends a text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder append(Text text) { for (MessageEntity entity : text.getEntities()) { append( entity.move(entity.getOffset() + length(), entity.getLength()), entity.getType() != MessageEntity.Type.BOT_COMMAND && entity.getType() != MessageEntity.Type.URL && entity.getType() != MessageEntity.Type.HASHTAG && entity.getType() != MessageEntity.Type.EMAIL ); } builder.append(text); return this; } /** * Appends a text builder to this TextBuilder. * * @param builder the builder to append * @return this instance */ public TextBuilder append(TextBuilder builder) { for (MessageEntity entity : builder.entities) { append( entity.move(entity.getOffset() + length(), entity.getLength()), entity.getType() != MessageEntity.Type.BOT_COMMAND && entity.getType() != MessageEntity.Type.URL && entity.getType() != MessageEntity.Type.HASHTAG && entity.getType() != MessageEntity.Type.EMAIL ); } builder.append(builder.builder.toString()); return this; } /** * Appends a bold text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendBold(String text) { return append(text, MessageEntity.Type.BOLD, true); } /** * Appends a italic text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendItalic(String text) { return append(text, MessageEntity.Type.ITALIC, true); } /** * Appends a code text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendCode(String text) { return append(text, MessageEntity.Type.CODE, true); } /** * Appends a code block text to this TextBuilder. * * @param text the text to append * @return this instance */ public TextBuilder appendCodeBlock(String text) { return append(text, MessageEntity.Type.CODE_BLOCK, true); } /** * Appends a link to this TextBuilder. * * @param link the link to append * @return this instance */ public TextBuilder appendLink(Link link) { return append(link.getText(), link.getUrl(), true); } /** * Appends a link to this TextBuilder. * * @param text the text of the link * @param url the url of the link * @return this instance */ public TextBuilder appendLink(String text, String url) { return append(text, url, true); } /** * Appends a link to a message to this TextBuilder. * * @param text the text of the link * @param message the message to link * @return this instance */ public TextBuilder appendLink(String text, Message message) { return append(text, toLink(message), true); } /** * Appends a mention to this TextBuilder. * * @param text the username to mention, without <code>@</code> * @return this instance */ public TextBuilder appendMention(String text) { return append("@" + text, MessageEntity.Type.MENTION, false); } /** * Appends a mention to this TextBuilder, or a text mention * if the username is not available. * * @param mention mentioned user * @return this instance */ public TextBuilder appendMention(User mention) { return mention.getUsername() .map(this::appendMention) .orElseGet(() -> appendTextMention(mention)); } /** * Appends a text mention to this TextBuilder. * * @param mention the mentioned to append * @return this instance */ public TextBuilder appendTextMention(Mention mention) { return append(mention.getText(), mention.getUser(), true); } /** * Appends a text mention to this TextBuilder. * * @param text the text of the mention * @param mention the mention * @return this instance */ public TextBuilder appendTextMention(String text, User mention) { return append(text, mention, true); } /** * Appends a text mention to this TextBuilder. * * @param mention the mentioned user * @return this instance */ public TextBuilder appendTextMention(User mention) { return append(mention.getName(), mention, true); } /** * Appends an hashtag to this TextBuilder. * * @param hashtag the hashtag to append, without <code>#</code> * @return this instance */ public TextBuilder appendHashtag(String hashtag) { return append("#" + hashtag, MessageEntity.Type.HASHTAG, false); } /** * Appends a bot command to this TextBuilder. * * @param botCommand the bot command to append, without <code>/</code> * @return this instance */ public TextBuilder appendBotCommand(String botCommand) { return append("/" + botCommand, MessageEntity.Type.BOT_COMMAND, false); } /** * Appends an url to this TextBuilder. * * @param url the url to append * @return this instance */ public TextBuilder appendUrl(String url) { return append(url, MessageEntity.Type.URL, false); } /** * Appends a link to a message to this TextBuilder. * * @param message message to link * @return this instance */ public TextBuilder appendUrl(Message message) { return append(toLink(message), MessageEntity.Type.URL, false); } /** * Appends an email to this TextBuilder. * * @param email the email to append * @return this instance */ public TextBuilder appendEmail(String email) { return append(email, MessageEntity.Type.EMAIL, false); } /** * Appends a phone number to this TextBuilder. * * @param phoneNumber the phone number to append * @return this instance */ public TextBuilder appendPhoneNumber(String phoneNumber) { return append(phoneNumber, MessageEntity.Type.PHONE_NUMBER, false); } /** * Appends a cashtag to this TextBuilder. * * @param cashtag the cashtag to append * @return this instance */ public TextBuilder appendCashtag(String cashtag) { return append("$" + cashtag.toUpperCase(), MessageEntity.Type.CASHTAG, false); } /** * Appends a mention to this TextBuilder. * * @param text the text of the mention * @param mention the id of the mentioned user * @return this instance * @deprecated use this method only if you can't * obtain the user relative to its id */ @Deprecated public TextBuilder appendMention(String text, long mention) { return appendLink(text, TEXT_MENTION_LINK + mention); } private String toLink(Message message) { Chat chat = message.getChat(); if (chat instanceof SuperGroup) { Optional<String> username = ((SuperGroup) chat).getUsername(); if (username.isPresent()) { return TELEGRAM_LINK + "/" + username.get() + "/" + message.getId(); } } return TELEGRAM_LINK + "/c/" + message.getChat().getId() + "/" + message.getId(); } private TextBuilder append(String text, MessageEntity.Type type, boolean concat) { append(new MessageEntity(type, builder.length(), text.length()), concat); builder.append(text); return this; } private TextBuilder append(String text, String url, boolean concat) { append(new MessageEntity(url, builder.length(), text.length()), concat); builder.append(text); return this; } private TextBuilder append(String text, User user, boolean concat) { append(new MessageEntity(user, builder.length(), text.length()), concat); builder.append(text); return this; } private void append(MessageEntity entity, boolean concat) { if (entity.getLength() > 0) { if (!concat || entities.isEmpty()) { entities.add(entity); } else { MessageEntity lastEntity = entities.get(entities.size() - 1); if (lastEntity.getType() == entity.getType() && entity.getUrl().equals(lastEntity.getUrl()) && entity.getUser().equals(lastEntity.getUser()) && lastEntity.getOffset() + lastEntity.getLength() == entity.getOffset()) { entities.set( entities.size() - 1, lastEntity.move(lastEntity.getOffset(), lastEntity.getLength() + entity.getLength()) ); } else { entities.add(entity); } } } } /** * Returns the length of the text. * * @return the length of the text */ public int length() { return builder.length(); } /** * Sets the length of the text. * * @param length the new length * @throws StringIndexOutOfBoundsException if the {@code newLength} argument is negative. */ public void setLength(int length) { if (length < 0) throw new StringIndexOutOfBoundsException(length); builder.setLength(length); for (int i = entities.size() - 1; i >= 0; i--) { MessageEntity entity = entities.get(i); if (entity.getOffset() > length) { entities.remove(entity); } else if (entity.getOffset() + entity.getLength() > length) { entities.remove(entity); int newLength = length - entity.getOffset(); entities.add(entity.move(entity.getOffset(), newLength)); } else { break; } } } /** * Builds the Text. * * @return the created text */ public Text build() { return new Text(builder.toString(), entities); } }
Fix link to message for private supergroups and channels
src/main/java/io/github/ageofwar/telejam/text/TextBuilder.java
Fix link to message for private supergroups and channels
Java
mit
c89623feec6443e5ed76a9801dcf79e4a6665817
0
ligoj/ligoj,ligoj/ligoj,ligoj/ligoj,ligoj/ligoj
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.resource.security; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * User. */ @Getter @Setter @EqualsAndHashCode(of = "name") @NoArgsConstructor @AllArgsConstructor public class User { @NotBlank @NotNull private String name; @NotBlank @NotNull @Length(max = 4096) private String password; }
app-api/src/main/java/org/ligoj/app/resource/security/User.java
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.resource.security; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * User. */ @Getter @Setter @EqualsAndHashCode(of = "name") @NoArgsConstructor @AllArgsConstructor public class User { @NotBlank @NotNull private String name; @NotBlank @NotNull @Length(max = 250) private String password; }
Allow up to 4K credential data
app-api/src/main/java/org/ligoj/app/resource/security/User.java
Allow up to 4K credential data
Java
mit
163d4bb64af6c046b1f85e0b42696ff79ae54715
0
Enthri/Balloon
package DragAndDrop; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JFrame; import com.troi.balloon.Panel; import com.troi.balloon.UiManager; public class DragAndDrop{ ArrayList<Panel> currentPanels = new ArrayList<Panel>(); HashMap<String, Panel> Instances; UiManager manager; JFrame frame; public DragAndDrop(JFrame frame, UiManager manager) { this.manager = manager; this.frame = frame; initializeEditer(); } public void initializeEditer() { currentPanels.add(new Settings(manager.getFileDimension(),"FileViewer")); currentPanels.add(new PackageTools(manager.getToolDimension(),"ToolViewer")); currentPanels.add(new PackageManager(manager.getMainDimension(),"MainViewer")); } public void changeEditer(Panel panel) { if (panel instanceof PackageManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new PackageTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, new Settings(manager.getFileDimension(),"Settings")); } else if (panel instanceof ClassManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new ClassTools(manager.getToolDimension(),"ToolViewer")); System.out.println(panel.getReference().getSize().getX()); panel.getReference().getContainer().getReference().setContainer(new MethodManager(manager.getFileDimension(),"fileViewer")); currentPanels.set(0, panel.getReference().getContainer()); currentPanels.get(0).setSize(manager.getFileDimension()); } else if (panel instanceof MethodManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new MethodTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, panel.getReference().getContainer()); } else if (panel instanceof CommandManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new CommandTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, panel.getReference().getContainer()); } else System.out.println("it's working"); } public void changeTool (Panel panel) { currentPanels.set(1, panel); } public void changeFileViewer(Panel panel) { currentPanels.set(0,panel); } public void addNewTool() { if (currentPanels.get(2) instanceof PackageManager) { currentPanels.set(1, new PackageTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof ClassManager) { currentPanels.set(1, new ClassTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof MethodManager) { currentPanels.set(1, new MethodTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof CommandManager) { currentPanels.set(1, new CommandTools(manager.getToolDimension(),"ToolViewer")); } } public void addNewEditer() { if (currentPanels.get(0) instanceof ClassManager) { currentPanels.set(2, new MethodManager(manager.getMainDimension(),"MainViewer")); addNewTool(); } else if (currentPanels.get(0) instanceof MethodManager) { currentPanels.set(2, new CommandManager(manager.getMainDimension(),"MainViewer")); addNewTool(); } else if (currentPanels.get(0) instanceof PackageManager ) { currentPanels.set(2, new ClassManager(manager.getToolDimension(),"MainViewer")); addNewTool(); } } public ArrayList<Panel> getCurrentPanels() { return currentPanels; } public Panel getMainViewer() { return (Panel)currentPanels.get(2); } public Panel getToolViewer() { return currentPanels.get(1); } public Panel getFileViewer() { return currentPanels.get(0); } public void addNewFileManager() { if (currentPanels.get(2) instanceof ClassManager) { currentPanels.set(1, new PackageManager(manager.getFileDimension(),"FileManager")); } else if (currentPanels.get(2) instanceof MethodManager) { currentPanels.set(1, new ClassManager(manager.getFileDimension(),"FileManager")); } else if (currentPanels.get(0) instanceof CommandManager) { currentPanels.set(1, new MethodManager(manager.getFileDimension(),"FileManager")); } else System.out.println("no File manager matchable"); } public String getPanel(int index) { System.out.println("getPanel check"); return currentPanels.get(index).getType(); } public void replaceCurrentTool() { } public void replaceCurrentEditer() { } public void removeCurrentTool() { } public void removeCurrentEditer() { } }
src/DragAndDrop/DragAndDrop.java
package DragAndDrop; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JFrame; import com.troi.balloon.Panel; import com.troi.balloon.UiManager; public class DragAndDrop{ ArrayList<Panel> currentPanels = new ArrayList<Panel>(); HashMap<String, Panel> Instances; UiManager manager; JFrame frame; public DragAndDrop(JFrame frame, UiManager manager) { this.manager = manager; this.frame = frame; initializeEditer(); } public void initializeEditer() { currentPanels.add(new Settings(manager.getFileDimension(),"FileViewer")); currentPanels.add(new PackageTools(manager.getToolDimension(),"ToolViewer")); currentPanels.add(new PackageManager(manager.getMainDimension(),"MainViewer")); } public void changeEditer(Panel panel) { if (panel instanceof PackageManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new PackageTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, new Settings(manager.getFileDimension(),"Settings")); } else if (panel instanceof ClassManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new ClassTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, panel.getReference().getContainer()); currentPanels.get(0).setSize(manager.getFileDimension()); } else if (panel instanceof MethodManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new MethodTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, panel.getReference().getContainer()); } else if (panel instanceof CommandManager) { currentPanels.set(2, panel); currentPanels.get(2).setSize(manager.getMainDimension()); currentPanels.set(1, new CommandTools(manager.getToolDimension(),"ToolViewer")); currentPanels.set(0, panel.getReference().getContainer()); } else System.out.println("it's working"); } public void changeTool (Panel panel) { currentPanels.set(1, panel); } public void changeFileViewer(Panel panel) { currentPanels.set(0,panel); } public void addNewTool() { if (currentPanels.get(2) instanceof PackageManager) { currentPanels.set(1, new PackageTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof ClassManager) { currentPanels.set(1, new ClassTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof MethodManager) { currentPanels.set(1, new MethodTools(manager.getToolDimension(),"ToolViewer")); } else if (currentPanels.get(2) instanceof CommandManager) { currentPanels.set(1, new CommandTools(manager.getToolDimension(),"ToolViewer")); } } public void addNewEditer() { if (currentPanels.get(0) instanceof ClassManager) { currentPanels.set(2, new MethodManager(manager.getMainDimension(),"MainViewer")); addNewTool(); } else if (currentPanels.get(0) instanceof MethodManager) { currentPanels.set(2, new CommandManager(manager.getMainDimension(),"MainViewer")); addNewTool(); } else if (currentPanels.get(0) instanceof PackageManager ) { currentPanels.set(2, new ClassManager(manager.getToolDimension(),"MainViewer")); addNewTool(); } } public ArrayList<Panel> getCurrentPanels() { return currentPanels; } public Panel getMainViewer() { return (Panel)currentPanels.get(2); } public Panel getToolViewer() { return currentPanels.get(1); } public Panel getFileViewer() { return currentPanels.get(0); } public void addNewFileManager() { if (currentPanels.get(2) instanceof ClassManager) { currentPanels.set(1, new PackageManager(manager.getFileDimension(),"FileManager")); } else if (currentPanels.get(2) instanceof MethodManager) { currentPanels.set(1, new ClassManager(manager.getFileDimension(),"FileManager")); } else if (currentPanels.get(0) instanceof CommandManager) { currentPanels.set(1, new MethodManager(manager.getFileDimension(),"FileManager")); } else System.out.println("no File manager matchable"); } public String getPanel(int index) { System.out.println("getPanel check"); return currentPanels.get(index).getType(); } public void replaceCurrentTool() { } public void replaceCurrentEditer() { } public void removeCurrentTool() { } public void removeCurrentEditer() { } }
'lk'lk'kl;
src/DragAndDrop/DragAndDrop.java
'lk'lk'kl;
Java
mit
a861d381763ab5a39a982dc4f5b9d2cd115296fc
0
DoSomething/ds-android
package org.dosomething.android.activities; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.dosomething.android.R; import org.dosomething.android.analytics.Analytics; import org.dosomething.android.context.UserContext; import org.dosomething.android.tasks.AbstractWebserviceTask; import org.dosomething.android.widget.CustomActionBar; import org.json.JSONObject; import roboguice.inject.InjectView; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Typeface; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.inject.Inject; import com.google.inject.name.Named; public class Register extends AbstractActivity { private static final String DATE_FORMAT = "MM/dd/yyyy"; @Inject private UserContext userContext; @Inject @Named("DINComp-CondBold")Typeface headerTypeface; @InjectView(R.id.actionbar) private CustomActionBar actionBar; @InjectView(R.id.username_name) private EditText username; @InjectView(R.id.mobile) private EditText mobile; @InjectView(R.id.first_name) private EditText firstName; @InjectView(R.id.last_name) private EditText lastName; @InjectView(R.id.email) private EditText email; @InjectView(R.id.password) private EditText password; @InjectView(R.id.confirm_password) private EditText confirmPassword; @InjectView(R.id.birthday) private EditText birthday; @InjectView(R.id.disclaimer) private TextView disclaimer; @InjectView(R.id.cancel) private Button cancel; @InjectView(R.id.submit) private Button submit; private Date savedBirthday; private Context context; @Override protected String getPageName() { return "register"; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); context = this; actionBar.setHomeAction(Campaigns.getHomeAction(context)); birthday.setOnFocusChangeListener(birthdayFocusListener); birthday.setOnClickListener(birthdayClickListener); disclaimer.setMovementMethod(LinkMovementMethod.getInstance()); disclaimer.setText(Html.fromHtml(getString(R.string.register_disclaimer))); cancel.setTypeface(headerTypeface, Typeface.BOLD); submit.setTypeface(headerTypeface, Typeface.BOLD); } private final OnClickListener birthdayClickListener = new OnClickListener() { @Override public void onClick(View v) { showBirthdayPicker(); } }; private final OnFocusChangeListener birthdayFocusListener = new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { showBirthdayPicker(); } } }; private void showBirthdayPicker(){ new DatePickerDialog(this, dateListener, 1995, 0, 1).show(); } public void register(View v){ String username = this.username.getText().toString(); String mobile = this.mobile.getText().toString(); String first = this.firstName.getText().toString(); String last = this.lastName.getText().toString(); String email = this.email.getText().toString(); String password = this.password.getText().toString(); String confirmPassword = this.confirmPassword.getText().toString(); String birthday = this.birthday.getText().toString(); if(!password.equals(confirmPassword)) { new AlertDialog.Builder(Register.this) .setMessage(getString(R.string.confirm_password_failed)) .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } else { new MyTask(username, mobile, first, last, email, password, birthday).execute(); } } private final OnDateSetListener dateListener = new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { savedBirthday = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime(); birthday.setText(new SimpleDateFormat(DATE_FORMAT).format(savedBirthday)); } }; public void cancel(View v){ setResult(RESULT_CANCELED); finish(); } private class MyTask extends AbstractWebserviceTask { private String username; private String mobile; private String first; private String last; private String email; private String password; private String birthday; private boolean registerSuccess; private String validationMessage; private ProgressDialog pd; public MyTask(String username, String mobile, String first, String last, String email, String password, String birthday) { super(userContext); this.username = username; this.first = first; this.last = last; this.email = email; this.password = password; this.birthday = birthday; } @Override protected void onPreExecute() { super.onPreExecute(); pd = ProgressDialog.show(context, null, getString(R.string.registering)); } @Override protected void onSuccess() { if(registerSuccess) { HashMap<String, String> param = new HashMap<String, String>(); param.put("success", "true"); Analytics.logEvent(getPageName(), param); setResult(RESULT_OK); finish(); } else { new AlertDialog.Builder(Register.this) .setMessage(validationMessage) .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } } @Override protected void onFinish() { pd.dismiss(); } @Override protected void onError(Exception e) { Toast.makeText(Register.this, getString(R.string.register_failed), Toast.LENGTH_LONG).show(); } @Override protected void doWebOperation() throws Exception { String url = "http://www.dosomething.org/?q=rest/user/register.json"; SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", username)); params.add(new BasicNameValuePair("pass", password)); params.add(new BasicNameValuePair("mail", email)); params.add(new BasicNameValuePair("profile_main[field_user_birthday][und][0][value][date]", birthday)); params.add(new BasicNameValuePair("profile_main[field_user_official_rules][und]", "1")); // must be 1 params.add(new BasicNameValuePair("profile_main[field_user_anniversary][und][0][value][date]", dateFormat.format(new Date()))); params.add(new BasicNameValuePair("profile_main[field_user_first_name][und][0][value]", first)); params.add(new BasicNameValuePair("profile_main[field_user_last_name][und][0][value]", last)); params.add(new BasicNameValuePair("profile_main[field_user_mobile][und][0][value]", mobile)); WebserviceResponse response = doPost(url, params); if(response.getStatusCode()>=400 && response.getStatusCode()<500) { validationMessage = response.extractFormErrorsAsMessage(); if(validationMessage==null) { getString(R.string.auth_failed); } registerSuccess = false; } else { JSONObject obj = response.getBodyAsJSONObject(); JSONObject user = obj.getJSONObject("user"); userContext.setLoggedIn(username, user.getString("mail"), user.getString("uid"), obj.getString("sessid"), obj.getString("session_name"), obj.getLong("session_cache_expire")); registerSuccess = true; } } } }
dosomething/src/org/dosomething/android/activities/Register.java
package org.dosomething.android.activities; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.dosomething.android.R; import org.dosomething.android.context.UserContext; import org.dosomething.android.tasks.AbstractWebserviceTask; import org.dosomething.android.widget.CustomActionBar; import org.json.JSONObject; import roboguice.inject.InjectView; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Typeface; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.inject.Inject; import com.google.inject.name.Named; public class Register extends AbstractActivity { private static final String DATE_FORMAT = "MM/dd/yyyy"; @Inject private UserContext userContext; @Inject @Named("DINComp-CondBold")Typeface headerTypeface; @InjectView(R.id.actionbar) private CustomActionBar actionBar; @InjectView(R.id.username_name) private EditText username; @InjectView(R.id.mobile) private EditText mobile; @InjectView(R.id.first_name) private EditText firstName; @InjectView(R.id.last_name) private EditText lastName; @InjectView(R.id.email) private EditText email; @InjectView(R.id.password) private EditText password; @InjectView(R.id.confirm_password) private EditText confirmPassword; @InjectView(R.id.birthday) private EditText birthday; @InjectView(R.id.disclaimer) private TextView disclaimer; @InjectView(R.id.cancel) private Button cancel; @InjectView(R.id.submit) private Button submit; private Date savedBirthday; private Context context; @Override protected String getPageName() { return "register"; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); context = this; actionBar.setHomeAction(Campaigns.getHomeAction(context)); birthday.setOnFocusChangeListener(birthdayFocusListener); birthday.setOnClickListener(birthdayClickListener); disclaimer.setMovementMethod(LinkMovementMethod.getInstance()); disclaimer.setText(Html.fromHtml(getString(R.string.register_disclaimer))); cancel.setTypeface(headerTypeface, Typeface.BOLD); submit.setTypeface(headerTypeface, Typeface.BOLD); } private final OnClickListener birthdayClickListener = new OnClickListener() { @Override public void onClick(View v) { showBirthdayPicker(); } }; private final OnFocusChangeListener birthdayFocusListener = new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { showBirthdayPicker(); } } }; private void showBirthdayPicker(){ new DatePickerDialog(this, dateListener, 1995, 0, 1).show(); } public void register(View v){ String username = this.username.getText().toString(); String mobile = this.mobile.getText().toString(); String first = this.firstName.getText().toString(); String last = this.lastName.getText().toString(); String email = this.email.getText().toString(); String password = this.password.getText().toString(); String confirmPassword = this.confirmPassword.getText().toString(); String birthday = this.birthday.getText().toString(); if(!password.equals(confirmPassword)) { new AlertDialog.Builder(Register.this) .setMessage(getString(R.string.confirm_password_failed)) .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } else { new MyTask(username, mobile, first, last, email, password, birthday).execute(); } } private final OnDateSetListener dateListener = new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { savedBirthday = new GregorianCalendar(year, monthOfYear, dayOfMonth).getTime(); birthday.setText(new SimpleDateFormat(DATE_FORMAT).format(savedBirthday)); } }; public void cancel(View v){ setResult(RESULT_CANCELED); finish(); } private class MyTask extends AbstractWebserviceTask { private String username; private String mobile; private String first; private String last; private String email; private String password; private String birthday; private boolean registerSuccess; private String validationMessage; private ProgressDialog pd; public MyTask(String username, String mobile, String first, String last, String email, String password, String birthday) { super(userContext); this.username = username; this.first = first; this.last = last; this.email = email; this.password = password; this.birthday = birthday; } @Override protected void onPreExecute() { super.onPreExecute(); pd = ProgressDialog.show(context, null, getString(R.string.registering)); } @Override protected void onSuccess() { if(registerSuccess) { setResult(RESULT_OK); finish(); } else { new AlertDialog.Builder(Register.this) .setMessage(validationMessage) .setCancelable(false) .setPositiveButton(getString(R.string.ok_upper), null) .create() .show(); } } @Override protected void onFinish() { pd.dismiss(); } @Override protected void onError(Exception e) { Toast.makeText(Register.this, getString(R.string.register_failed), Toast.LENGTH_LONG).show(); } @Override protected void doWebOperation() throws Exception { String url = "http://www.dosomething.org/?q=rest/user/register.json"; SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", username)); params.add(new BasicNameValuePair("pass", password)); params.add(new BasicNameValuePair("mail", email)); params.add(new BasicNameValuePair("profile_main[field_user_birthday][und][0][value][date]", birthday)); params.add(new BasicNameValuePair("profile_main[field_user_official_rules][und]", "1")); // must be 1 params.add(new BasicNameValuePair("profile_main[field_user_anniversary][und][0][value][date]", dateFormat.format(new Date()))); params.add(new BasicNameValuePair("profile_main[field_user_first_name][und][0][value]", first)); params.add(new BasicNameValuePair("profile_main[field_user_last_name][und][0][value]", last)); params.add(new BasicNameValuePair("profile_main[field_user_mobile][und][0][value]", mobile)); WebserviceResponse response = doPost(url, params); if(response.getStatusCode()>=400 && response.getStatusCode()<500) { validationMessage = response.extractFormErrorsAsMessage(); if(validationMessage==null) { getString(R.string.auth_failed); } registerSuccess = false; } else { JSONObject obj = response.getBodyAsJSONObject(); JSONObject user = obj.getJSONObject("user"); userContext.setLoggedIn(username, user.getString("mail"), user.getString("uid"), obj.getString("sessid"), obj.getString("session_name"), obj.getLong("session_cache_expire")); registerSuccess = true; } } } }
Log event for successful user registration
dosomething/src/org/dosomething/android/activities/Register.java
Log event for successful user registration
Java
mit
bb403e44941473970b2030d62203923ce6968529
0
oaplatform/oap,oaplatform/oap
/* * The MIT License (MIT) * * Copyright (c) Open Application Platform Authors * * 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 oap.ws.validate; import lombok.EqualsAndHashCode; import lombok.ToString; import oap.reflect.Reflection; import oap.util.Lists; import oap.util.Mergeable; import oap.ws.WsClientException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static oap.ws.validate.Validators.forParameter; @ToString @EqualsAndHashCode public final class ValidationErrors implements Mergeable<ValidationErrors> { public static final int DEFAULT_CODE = HTTP_BAD_REQUEST; public final List<String> errors = new ArrayList<>(); public int code; private ValidationErrors( int code, List<String> errors ) { this.code = code; this.errors.addAll( errors ); } public static ValidationErrors empty() { return errors( Lists.empty() ); } @Deprecated public static ValidationErrors create( String error ) { return errors( Lists.of( error ) ); } public static ValidationErrors error( String error ) { return errors( Lists.of( error ) ); } public static ValidationErrors error( String message, Object... args ) { return errors( Lists.of( String.format( message, args ) ) ); } @Deprecated public static ValidationErrors create( List<String> errors ) { return new ValidationErrors( DEFAULT_CODE, errors ); } public static ValidationErrors errors( List<String> errors ) { return new ValidationErrors( DEFAULT_CODE, errors ); } @Deprecated public static ValidationErrors create( int code, List<String> errors ) { return new ValidationErrors( code, errors ); } public static ValidationErrors errors( int code, List<String> errors ) { return new ValidationErrors( code, errors ); } @Deprecated public static ValidationErrors create( int code, String error ) { return errors( code, Lists.of( error ) ); } public static ValidationErrors error( int code, String error ) { return errors( code, Lists.of( error ) ); } public static ValidationErrors error( int code, String message, Object... args ) { return errors( code, Lists.of( String.format( message, args ) ) ); } public ValidationErrors merge( ValidationErrors otherErrors ) { if( hasDefaultCode() ) this.code = otherErrors.code; this.errors.addAll( otherErrors.errors ); return this; } public ValidationErrors validateParameters( Map<Reflection.Parameter, Object> values, Reflection.Method method, Object instance, boolean beforeUnmarshaling ) { values.forEach( ( parameter, value ) -> merge( forParameter( method, parameter, instance, beforeUnmarshaling ) .validate( value, values ) ) ); return this; } public boolean failed() { return !errors.isEmpty(); } public boolean hasDefaultCode() { return code == DEFAULT_CODE; } public ValidationErrors throwIfInvalid() throws WsClientException { if( failed() ) throw new WsClientException( errors.size() > 1 ? "validation failed" : errors.get( 0 ), code, errors ); return this; } }
oap-ws/src/main/java/oap/ws/validate/ValidationErrors.java
/* * The MIT License (MIT) * * Copyright (c) Open Application Platform Authors * * 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 oap.ws.validate; import lombok.EqualsAndHashCode; import lombok.ToString; import oap.reflect.Reflection; import oap.util.Lists; import oap.util.Mergeable; import oap.ws.WsClientException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static oap.ws.validate.Validators.forParameter; @ToString @EqualsAndHashCode public final class ValidationErrors implements Mergeable<ValidationErrors> { public static final int DEFAULT_CODE = HTTP_BAD_REQUEST; public final List<String> errors = new ArrayList<>(); public int code; private ValidationErrors( int code, List<String> errors ) { this.code = code; this.errors.addAll( errors ); } public static ValidationErrors empty() { return errors( Lists.empty() ); } @Deprecated public static ValidationErrors create( String error ) { return errors( Lists.of( error ) ); } public static ValidationErrors error( String error ) { return errors( Lists.of( error ) ); } @Deprecated public static ValidationErrors create( List<String> errors ) { return new ValidationErrors( DEFAULT_CODE, errors ); } public static ValidationErrors errors( List<String> errors ) { return new ValidationErrors( DEFAULT_CODE, errors ); } @Deprecated public static ValidationErrors create( int code, List<String> errors ) { return new ValidationErrors( code, errors ); } public static ValidationErrors errors( int code, List<String> errors ) { return new ValidationErrors( code, errors ); } @Deprecated public static ValidationErrors create( int code, String error ) { return errors( code, Lists.of( error ) ); } public static ValidationErrors error( int code, String error ) { return errors( code, Lists.of( error ) ); } public ValidationErrors merge( ValidationErrors otherErrors ) { if( hasDefaultCode() ) this.code = otherErrors.code; this.errors.addAll( otherErrors.errors ); return this; } public ValidationErrors validateParameters( Map<Reflection.Parameter, Object> values, Reflection.Method method, Object instance, boolean beforeUnmarshaling ) { values.forEach( ( parameter, value ) -> merge( forParameter( method, parameter, instance, beforeUnmarshaling ) .validate( value, values ) ) ); return this; } public boolean failed() { return !errors.isEmpty(); } public boolean hasDefaultCode() { return code == DEFAULT_CODE; } public ValidationErrors throwIfInvalid() throws WsClientException { if( failed() ) throw new WsClientException( errors.size() > 1 ? "validation failed" : errors.get( 0 ), code, errors ); return this; } }
added validation errors with String.format
oap-ws/src/main/java/oap/ws/validate/ValidationErrors.java
added validation errors with String.format
Java
epl-1.0
24175de4d76df10b7bd8d99cc0a79f0ba18a3ff8
0
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012-2014 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl; import java.awt.Point; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.core.PortalTexture; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.core.TextureDescription; import org.jtrfp.trcl.file.DirectionVector; import org.jtrfp.trcl.file.TDFFile; import org.jtrfp.trcl.file.TDFFile.TunnelLogic; import org.jtrfp.trcl.gpu.Model; import org.jtrfp.trcl.miss.LoadingProgressReporter; import org.jtrfp.trcl.obj.PortalEntrance; import org.jtrfp.trcl.obj.PortalExit; import org.jtrfp.trcl.obj.TerrainChunk; public final class TerrainSystem extends RenderableSpacePartitioningGrid{ final double gridSquareSize; //final double heightScalar; final ArrayList<TerrainChunk> renderingCubes = new ArrayList<TerrainChunk>(); private final TR tr; private final ExecutorService executor; public static final double Y_NUDGE = -10000; private static class TSThreadFactory implements ThreadFactory{ @Override public Thread newThread(final Runnable runnable) { final Thread result = new Thread("TerrainSystem "+hashCode()){ public void run(){ runnable.run();} }; return result; } }//end TSThreadFactory /* * Y_NUDGE is a kludge. There is a tiny sliver of space * between the ceiling and ground, likely caused by model * vertex quantization in the rendering engine. I would * rather put up with this quirk than re-design the engine, * as the quantization exists as a side-effect of a * memory-space optimization in the GPU and accommodating * the fix of this bug could cause bigger problems further * down the road. */ public TerrainSystem(final AltitudeMap altitude, final TextureMesh textureMesh, final double gridSquareSize, final RenderableSpacePartitioningGrid terrainMirror, final TR tr, final TDFFile tdf, final boolean flatShading, final LoadingProgressReporter terrainReporter, final String debugName) { super(); final int numCores = Runtime.getRuntime().availableProcessors(); this.tr = tr; final int width = (int) altitude.getWidth(); int height = (int) altitude.getHeight(); this.gridSquareSize = gridSquareSize; executor = new ThreadPoolExecutor(numCores * 2, numCores * 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new TSThreadFactory()); final int chunkSideLength = TR.terrainChunkSideLengthInSquares; final double u[] = { 0, 1, 1, 0 }; final double v[] = { 0, 0, 1, 1 }; final double cu[] = { 0, 1, 1, 0 }; final double cv[] = { 1, 1, 0, 0 }; final NormalMap normalMap = new NormalMap(altitude); // Come up with a point list for tunnel entrances and exits TDFFile.Tunnel[] tunnels = tdf.getTunnels(); final HashMap<Integer, TunnelPoint> points = new HashMap<Integer, TunnelPoint>(); final HashMap<String, TDFFile.Tunnel> tunnelsByName = new HashMap<String, TDFFile.Tunnel>(); final ArrayList<Future<Void>> rowTasks = new ArrayList<Future<Void>>(); if (tunnels != null) {// Null means no tunnels for (int i = 0; i < tunnels.length; i++) { final TDFFile.Tunnel tun = tunnels[i]; if (tun.getEntranceLogic() != TunnelLogic.invisible) { final TunnelPoint tp = new TunnelPoint(tun, true); points.put(tp.hashCode(), tp); } if (tun.getExitLogic() != TunnelLogic.invisible) { final TunnelPoint tp = new TunnelPoint(tun, false); points.put(tp.hashCode(), tp); tunnelsByName.put(tun.getTunnelLVLFile(), tunnels[i]); }//end if(invisible) }// end for(tunnels) }// end if(tunnels) final LoadingProgressReporter[] reporters = terrainReporter .generateSubReporters(256/chunkSideLength); int reporterIndex=0; final double worldCeiling = tr.getWorld().sizeY; // For each chunk for (int gZ = 0; gZ < height; gZ += chunkSideLength) { reporters[reporterIndex++].complete(); final int _gZ = gZ; rowTasks.add(executor.submit(new Callable<Void>(){ @Override public Void call() throws Exception { for (int gX = 0; gX < width; gX += chunkSideLength) { // GROUND {// Start scope final double objectX = Math .round(((double) gX + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectZ = Math .round(((double) _gZ + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectY = Math.round(altitude .heightAt(gX*gridSquareSize, _gZ*gridSquareSize)); final Model m = new Model(false, tr,"Terrain Chunk"); m.setDebugName(debugName); // for each square for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) { for (int cX = gX; cX < gX + chunkSideLength; cX++) { final double xPos = cX * gridSquareSize; final double zPos = cZ * gridSquareSize; final double hTL = altitude.heightAt(xPos, cZ* gridSquareSize); final double hTR = altitude.heightAt((cX + 1)* gridSquareSize, cZ* gridSquareSize); final double hBR = altitude.heightAt((cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize); final double hBL = altitude.heightAt(xPos, (cZ + 1)* gridSquareSize); Vector3D norm0, norm1, norm2, norm3; norm3 = normalMap.normalAt(xPos, cZ* gridSquareSize); /*norm3 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm2 = normalMap.normalAt((cX + 1)* gridSquareSize, cZ* gridSquareSize); /*norm2 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm1 = normalMap.normalAt((cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize); /*norm1 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm0 = normalMap.normalAt(xPos, (cZ + 1)* gridSquareSize); /*norm0 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ if (flatShading) norm0 = norm1 = norm2 = norm3 = normalMap .normalAt((cX + .5)* gridSquareSize, (cZ + .5)* gridSquareSize); final Integer tpi = cX + cZ * 256; if(points.containsKey(tpi)){ final Model portalModel = new Model(false, tr,"PortalEntrance"); //Place a PortalEntrance final int Y_OFFSET = -300; final double portalX = xPos+gridSquareSize/2.; final double portalY = (hBL+hBR+hTR+hTL)/4.; final double portalZ = zPos+gridSquareSize/2.; final PortalTexture portalTexture = new PortalTexture(); Triangle[] tris = Triangle .quad2Triangles( // COUNTER-CLOCKWISE // //x new double[] { gridSquareSize/2, -gridSquareSize/2, -gridSquareSize/2, gridSquareSize/2 }, new double[] {-gridSquareSize/2,-gridSquareSize/2,gridSquareSize/2,gridSquareSize/2}, new double[] { 0, 0, 0, 0 }, u, v, portalTexture, RenderMode.STATIC, new Vector3D[] { norm0, norm1, norm2, norm3 }, cX + cZ % 4); portalModel.addTriangles(tris); final PortalExit exit = new PortalExit(tr); final PortalEntrance entrance; entrance = new PortalEntrance(tr,portalModel,exit,tr.getGame().getPlayer()); tr.getGame().getCurrentMission().registerTunnelEntrancePortal(new Point(cX,cZ), entrance); entrance.setPortalTexture(portalTexture); Vector3D heading = normalMap.normalAt(xPos, cZ* gridSquareSize).normalize().negate(); entrance.setHeading(heading); if(heading.getY()>-.99&heading.getNorm()>0)//If the ground is flat this doesn't work. entrance.setTop(Vector3D.PLUS_J.crossProduct(heading).crossProduct(heading).negate()); else entrance.setTop(Vector3D.PLUS_I);// ... so we create a clause for that. entrance.setPosition(new Vector3D(portalX,portalY,portalZ).add(heading.scalarMultiply(2000)).toArray()); entrance.notifyPositionChange(); add(entrance); }//end if(tunnel) TextureDescription td = (TextureDescription) (points .containsKey(tpi) ? points.get(tpi) .getTexture() : textureMesh.textureAt(cX, cZ)); Triangle[] tris = Triangle .quad2Triangles( // COUNTER-CLOCKWISE // //x new double[] { xPos - objectX, xPos + gridSquareSize - objectX, xPos + gridSquareSize - objectX, xPos - objectX }, new double[] { hBL - objectY, hBR - objectY, hTR - objectY, hTL - objectY }, new double[] { zPos + gridSquareSize - objectZ, zPos + gridSquareSize - objectZ, zPos - objectZ, zPos - objectZ }, u, v, td, RenderMode.STATIC, new Vector3D[] { norm0, norm1, norm2, norm3 }, cX + cZ % 4); if(points.containsKey(tpi)){ tris[0].setAlphaBlended(true); tris[1].setAlphaBlended(true); } m.addTriangle(tris[0]); m.addTriangle(tris[1]); }// end for(cX) }// end for(cZ) // Add to grid // if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) { final TerrainChunk chunkToAdd = new TerrainChunk(tr, m, altitude); final double[] chunkPos = chunkToAdd.getPosition(); chunkPos[0] = objectX; chunkPos[1] = objectY; chunkPos[2] = objectZ; chunkToAdd.notifyPositionChange(); add(chunkToAdd); /*} else { System.out.println("Rejected chunk: " + m.getDebugName()); }*/ }// end scope {// start scope ///// CEILING final double objectX = Math .round(((double) gX + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectZ = Math .round(((double) _gZ + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectY = Math.round((2. - altitude.heightAt( gX* gridSquareSize, _gZ* gridSquareSize)) + Y_NUDGE); final Model m = new Model(false, tr,"CeilingChunk"); // for each square for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) { for (int cX = gX; cX < gX + chunkSideLength; cX++) { final double xPos = cX * gridSquareSize; final double zPos = cZ * gridSquareSize; final double hTL = (worldCeiling - altitude.heightAt(xPos, cZ* gridSquareSize)) + Y_NUDGE; final double hTR = (worldCeiling - altitude.heightAt( (cX + 1)* gridSquareSize, cZ* gridSquareSize)) + Y_NUDGE; final double hBR = (worldCeiling - altitude.heightAt( (cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize)) + Y_NUDGE; final double hBL = (worldCeiling - altitude.heightAt(xPos, (cZ + 1)* gridSquareSize)) + Y_NUDGE; Vector3D norm0, norm1, norm2, norm3; norm3=norm2=norm1=norm0 = normalMap.normalAt(xPos, cZ* gridSquareSize); /* norm3 = altitude.heightAt(cX, cZ)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX + 1, cZ); norm2 = altitude.heightAt(cX + 1, cZ)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX + 1, cZ + 1); norm1 = altitude.heightAt(cX + 1 , cZ + 1)< .9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX, cZ + 1); norm0 = altitude.heightAt(cX, cZ + 1)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); */ norm0 = norm1 = norm2 = norm3 = Vector3D.ZERO; // Ceiling texture cell X (Z in this engine) value // is offset by 10. // No tunnelpoints on ceiling TextureDescription td = (TextureDescription) (textureMesh .textureAt(cX, cZ + 10)); // features. Triangle[] tris = Triangle.quad2Triangles( // CLOCKWISE (else backface culling will eat // it) new double[] { xPos - objectX, xPos + gridSquareSize - objectX, xPos + gridSquareSize - objectX, xPos - objectX }, // x new double[] { hTL - objectY, hTR - objectY, hBR - objectY, hBL - objectY }, new double[] { zPos - objectZ, zPos - objectZ, zPos + gridSquareSize - objectZ, zPos + gridSquareSize - objectZ }, cu, cv, td, RenderMode.STATIC, new Vector3D[] { norm3, norm2, norm1, norm0 }, cX + cZ % 4); m.addTriangle(tris[0]); m.addTriangle(tris[1]); }// end for(cX) }// end for(cZ) // Add to grid //if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) { final TerrainChunk chunkToAdd = new TerrainChunk(tr, m, altitude); final double[] chunkPos = chunkToAdd.getPosition(); chunkPos[0] = objectX; chunkPos[1] = objectY; chunkPos[2] = objectZ; chunkToAdd.notifyPositionChange(); chunkToAdd.setCeiling(true); terrainMirror.add(chunkToAdd); /*} else { System.out.println("Rejected chunk: " + m.getDebugName()); }*/ }// end scope(CEILING) }// end for(gX) return null; }})); }// end for(gZ) for(Future<Void> task:rowTasks) try{task.get();}catch(Exception e){throw new RuntimeException(e);} }// end constructor private class TunnelPoint{ final int x,z; TextureDescription textureToInsert; public TunnelPoint(TDFFile.Tunnel tun, boolean entrance){ try{final String texFile = entrance?tun.getEntranceTerrainTextureFile():tun.getExitTerrainTextureFile(); textureToInsert = tr.getResourceManager().getRAWAsTexture(texFile, tr.getGlobalPaletteVL(),null,false);} catch(Exception e){e.printStackTrace();} DirectionVector v = entrance?tun.getEntrance():tun.getExit(); x = (int)TR.legacy2MapSquare(v.getZ()); z = (int)TR.legacy2MapSquare(v.getX()); } public TextureDescription getTexture(){return textureToInsert;} @Override public boolean equals(Object other){ return other.hashCode()==this.hashCode(); } @Override public int hashCode(){ return (int)(x+z*256); } } /** * @return the gridSquareSize */ public double getGridSquareSize(){ return gridSquareSize; } /** * @return the renderingCubes */ public ArrayList<TerrainChunk> getRenderingCubes(){ return renderingCubes; } }//end TerrainSystem
src/main/java/org/jtrfp/trcl/TerrainSystem.java
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012-2014 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl; import java.awt.Point; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.core.PortalTexture; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.core.TextureDescription; import org.jtrfp.trcl.file.DirectionVector; import org.jtrfp.trcl.file.TDFFile; import org.jtrfp.trcl.file.TDFFile.TunnelLogic; import org.jtrfp.trcl.gpu.Model; import org.jtrfp.trcl.miss.LoadingProgressReporter; import org.jtrfp.trcl.obj.PortalEntrance; import org.jtrfp.trcl.obj.PortalExit; import org.jtrfp.trcl.obj.TerrainChunk; public final class TerrainSystem extends RenderableSpacePartitioningGrid{ final double gridSquareSize; //final double heightScalar; final ArrayList<TerrainChunk> renderingCubes = new ArrayList<TerrainChunk>(); private final TR tr; private final ExecutorService executor; public static final double Y_NUDGE = -10000; /* * Y_NUDGE is a kludge. There is a tiny sliver of space * between the ceiling and ground, likely caused by model * vertex quantization in the rendering engine. I would * rather put up with this quirk than re-design the engine, * as the quantization exists as a side-effect of a * memory-space optimization in the GPU and accommodating * the fix of this bug could cause bigger problems further * down the road. */ public TerrainSystem(final AltitudeMap altitude, final TextureMesh textureMesh, final double gridSquareSize, final RenderableSpacePartitioningGrid terrainMirror, final TR tr, final TDFFile tdf, final boolean flatShading, final LoadingProgressReporter terrainReporter, final String debugName) { super(); final int numCores = Runtime.getRuntime().availableProcessors(); this.tr = tr; final int width = (int) altitude.getWidth(); int height = (int) altitude.getHeight(); this.gridSquareSize = gridSquareSize; executor = new ThreadPoolExecutor(numCores * 2, numCores * 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory(){ @Override public Thread newThread(final Runnable runnable) { final Thread result = new Thread("TerrainSystem "+hashCode()){ public void run(){ runnable.run();} }; return result; }}); final int chunkSideLength = TR.terrainChunkSideLengthInSquares; final double u[] = { 0, 1, 1, 0 }; final double v[] = { 0, 0, 1, 1 }; final double cu[] = { 0, 1, 1, 0 }; final double cv[] = { 1, 1, 0, 0 }; final NormalMap normalMap = new NormalMap(altitude); // Come up with a point list for tunnel entrances and exits TDFFile.Tunnel[] tunnels = tdf.getTunnels(); final HashMap<Integer, TunnelPoint> points = new HashMap<Integer, TunnelPoint>(); final HashMap<String, TDFFile.Tunnel> tunnelsByName = new HashMap<String, TDFFile.Tunnel>(); final ArrayList<Future<Void>> rowTasks = new ArrayList<Future<Void>>(); if (tunnels != null) {// Null means no tunnels for (int i = 0; i < tunnels.length; i++) { final TDFFile.Tunnel tun = tunnels[i]; if (tun.getEntranceLogic() != TunnelLogic.invisible) { final TunnelPoint tp = new TunnelPoint(tun, true); points.put(tp.hashCode(), tp); } if (tun.getExitLogic() != TunnelLogic.invisible) { final TunnelPoint tp = new TunnelPoint(tun, false); points.put(tp.hashCode(), tp); tunnelsByName.put(tun.getTunnelLVLFile(), tunnels[i]); }//end if(invisible) }// end for(tunnels) }// end if(tunnels) final LoadingProgressReporter[] reporters = terrainReporter .generateSubReporters(256/chunkSideLength); int reporterIndex=0; final double worldCeiling = tr.getWorld().sizeY; // For each chunk for (int gZ = 0; gZ < height; gZ += chunkSideLength) { reporters[reporterIndex++].complete(); final int _gZ = gZ; rowTasks.add(executor.submit(new Callable<Void>(){ @Override public Void call() throws Exception { for (int gX = 0; gX < width; gX += chunkSideLength) { // GROUND {// Start scope final double objectX = Math .round(((double) gX + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectZ = Math .round(((double) _gZ + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectY = Math.round(altitude .heightAt(gX*gridSquareSize, _gZ*gridSquareSize)); final Model m = new Model(false, tr,"Terrain Chunk"); m.setDebugName(debugName); // for each square for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) { for (int cX = gX; cX < gX + chunkSideLength; cX++) { final double xPos = cX * gridSquareSize; final double zPos = cZ * gridSquareSize; final double hTL = altitude.heightAt(xPos, cZ* gridSquareSize); final double hTR = altitude.heightAt((cX + 1)* gridSquareSize, cZ* gridSquareSize); final double hBR = altitude.heightAt((cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize); final double hBL = altitude.heightAt(xPos, (cZ + 1)* gridSquareSize); Vector3D norm0, norm1, norm2, norm3; norm3 = normalMap.normalAt(xPos, cZ* gridSquareSize); /*norm3 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm2 = normalMap.normalAt((cX + 1)* gridSquareSize, cZ* gridSquareSize); /*norm2 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm1 = normalMap.normalAt((cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize); /*norm1 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ norm0 = normalMap.normalAt(xPos, (cZ + 1)* gridSquareSize); /*norm0 = new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize();*/ if (flatShading) norm0 = norm1 = norm2 = norm3 = normalMap .normalAt((cX + .5)* gridSquareSize, (cZ + .5)* gridSquareSize); final Integer tpi = cX + cZ * 256; if(points.containsKey(tpi)){ final Model portalModel = new Model(false, tr,"PortalEntrance"); //Place a PortalEntrance final int Y_OFFSET = -300; final double portalX = xPos+gridSquareSize/2.; final double portalY = (hBL+hBR+hTR+hTL)/4.; final double portalZ = zPos+gridSquareSize/2.; final PortalTexture portalTexture = new PortalTexture(); Triangle[] tris = Triangle .quad2Triangles( // COUNTER-CLOCKWISE // //x new double[] { gridSquareSize/2, -gridSquareSize/2, -gridSquareSize/2, gridSquareSize/2 }, new double[] {-gridSquareSize/2,-gridSquareSize/2,gridSquareSize/2,gridSquareSize/2}, new double[] { 0, 0, 0, 0 }, u, v, portalTexture, RenderMode.STATIC, new Vector3D[] { norm0, norm1, norm2, norm3 }, cX + cZ % 4); portalModel.addTriangles(tris); final PortalExit exit = new PortalExit(tr); final PortalEntrance entrance; entrance = new PortalEntrance(tr,portalModel,exit,tr.getGame().getPlayer()); tr.getGame().getCurrentMission().registerTunnelEntrancePortal(new Point(cX,cZ), entrance); entrance.setPortalTexture(portalTexture); Vector3D heading = normalMap.normalAt(xPos, cZ* gridSquareSize).normalize().negate(); entrance.setHeading(heading); if(heading.getY()>-.99&heading.getNorm()>0)//If the ground is flat this doesn't work. entrance.setTop(Vector3D.PLUS_J.crossProduct(heading).crossProduct(heading).negate()); else entrance.setTop(Vector3D.PLUS_I);// ... so we create a clause for that. entrance.setPosition(new Vector3D(portalX,portalY,portalZ).add(heading.scalarMultiply(2000)).toArray()); entrance.notifyPositionChange(); add(entrance); }//end if(tunnel) TextureDescription td = (TextureDescription) (points .containsKey(tpi) ? points.get(tpi) .getTexture() : textureMesh.textureAt(cX, cZ)); Triangle[] tris = Triangle .quad2Triangles( // COUNTER-CLOCKWISE // //x new double[] { xPos - objectX, xPos + gridSquareSize - objectX, xPos + gridSquareSize - objectX, xPos - objectX }, new double[] { hBL - objectY, hBR - objectY, hTR - objectY, hTL - objectY }, new double[] { zPos + gridSquareSize - objectZ, zPos + gridSquareSize - objectZ, zPos - objectZ, zPos - objectZ }, u, v, td, RenderMode.STATIC, new Vector3D[] { norm0, norm1, norm2, norm3 }, cX + cZ % 4); if(points.containsKey(tpi)){ tris[0].setAlphaBlended(true); tris[1].setAlphaBlended(true); } m.addTriangle(tris[0]); m.addTriangle(tris[1]); }// end for(cX) }// end for(cZ) // Add to grid // if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) { final TerrainChunk chunkToAdd = new TerrainChunk(tr, m, altitude); final double[] chunkPos = chunkToAdd.getPosition(); chunkPos[0] = objectX; chunkPos[1] = objectY; chunkPos[2] = objectZ; chunkToAdd.notifyPositionChange(); add(chunkToAdd); /*} else { System.out.println("Rejected chunk: " + m.getDebugName()); }*/ }// end scope {// start scope ///// CEILING final double objectX = Math .round(((double) gX + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectZ = Math .round(((double) _gZ + ((double) chunkSideLength / 2.)) * gridSquareSize); final double objectY = Math.round((2. - altitude.heightAt( gX* gridSquareSize, _gZ* gridSquareSize)) + Y_NUDGE); final Model m = new Model(false, tr,"CeilingChunk"); // for each square for (int cZ = _gZ; cZ < _gZ + chunkSideLength; cZ++) { for (int cX = gX; cX < gX + chunkSideLength; cX++) { final double xPos = cX * gridSquareSize; final double zPos = cZ * gridSquareSize; final double hTL = (worldCeiling - altitude.heightAt(xPos, cZ* gridSquareSize)) + Y_NUDGE; final double hTR = (worldCeiling - altitude.heightAt( (cX + 1)* gridSquareSize, cZ* gridSquareSize)) + Y_NUDGE; final double hBR = (worldCeiling - altitude.heightAt( (cX + 1)* gridSquareSize, (cZ + 1)* gridSquareSize)) + Y_NUDGE; final double hBL = (worldCeiling - altitude.heightAt(xPos, (cZ + 1)* gridSquareSize)) + Y_NUDGE; Vector3D norm0, norm1, norm2, norm3; norm3=norm2=norm1=norm0 = normalMap.normalAt(xPos, cZ* gridSquareSize); /* norm3 = altitude.heightAt(cX, cZ)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX + 1, cZ); norm2 = altitude.heightAt(cX + 1, cZ)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX + 1, cZ + 1); norm1 = altitude.heightAt(cX + 1 , cZ + 1)< .9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); norm = altitude.normalAt(cX, cZ + 1); norm0 = altitude.heightAt(cX, cZ + 1)<.9? new Vector3D(norm.getX() * 3, norm.getY()*-1, norm.getZ() * 3).normalize(): new Vector3D(norm.getX() * 3, norm.getY(), norm.getZ() * 3).normalize(); */ norm0 = norm1 = norm2 = norm3 = Vector3D.ZERO; // Ceiling texture cell X (Z in this engine) value // is offset by 10. // No tunnelpoints on ceiling TextureDescription td = (TextureDescription) (textureMesh .textureAt(cX, cZ + 10)); // features. Triangle[] tris = Triangle.quad2Triangles( // CLOCKWISE (else backface culling will eat // it) new double[] { xPos - objectX, xPos + gridSquareSize - objectX, xPos + gridSquareSize - objectX, xPos - objectX }, // x new double[] { hTL - objectY, hTR - objectY, hBR - objectY, hBL - objectY }, new double[] { zPos - objectZ, zPos - objectZ, zPos + gridSquareSize - objectZ, zPos + gridSquareSize - objectZ }, cu, cv, td, RenderMode.STATIC, new Vector3D[] { norm3, norm2, norm1, norm0 }, cX + cZ % 4); m.addTriangle(tris[0]); m.addTriangle(tris[1]); }// end for(cX) }// end for(cZ) // Add to grid //if (m.finalizeModel().get().getTriangleList() != null || m.getTransparentTriangleList() != null) { final TerrainChunk chunkToAdd = new TerrainChunk(tr, m, altitude); final double[] chunkPos = chunkToAdd.getPosition(); chunkPos[0] = objectX; chunkPos[1] = objectY; chunkPos[2] = objectZ; chunkToAdd.notifyPositionChange(); chunkToAdd.setCeiling(true); terrainMirror.add(chunkToAdd); /*} else { System.out.println("Rejected chunk: " + m.getDebugName()); }*/ }// end scope(CEILING) }// end for(gX) return null; }})); }// end for(gZ) for(Future<Void> task:rowTasks) try{task.get();}catch(Exception e){throw new RuntimeException(e);} }// end constructor private class TunnelPoint{ final int x,z; TextureDescription textureToInsert; public TunnelPoint(TDFFile.Tunnel tun, boolean entrance){ try{final String texFile = entrance?tun.getEntranceTerrainTextureFile():tun.getExitTerrainTextureFile(); textureToInsert = tr.getResourceManager().getRAWAsTexture(texFile, tr.getGlobalPaletteVL(),null,false);} catch(Exception e){e.printStackTrace();} DirectionVector v = entrance?tun.getEntrance():tun.getExit(); x = (int)TR.legacy2MapSquare(v.getZ()); z = (int)TR.legacy2MapSquare(v.getX()); } public TextureDescription getTexture(){return textureToInsert;} @Override public boolean equals(Object other){ return other.hashCode()==this.hashCode(); } @Override public int hashCode(){ return (int)(x+z*256); } } /** * @return the gridSquareSize */ public double getGridSquareSize(){ return gridSquareSize; } /** * @return the renderingCubes */ public ArrayList<TerrainChunk> getRenderingCubes(){ return renderingCubes; } }//end TerrainSystem
✔ReferenceLeak in TerrainSystem's anonymous ThreadFactory.
src/main/java/org/jtrfp/trcl/TerrainSystem.java
✔ReferenceLeak in TerrainSystem's anonymous ThreadFactory.
Java
epl-1.0
8dca4a9f00b2e7fd886757babd657ef7a66ca547
0
PDOK/catalog-java,PDOK/catalog-java
package nl.pdok.catalog.gitutil; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GitInteractionsHandler { private static final String GIT_BRANCH_TXT = "gitBranch.txt"; private static final String AUTHORIZATION = "Authorization"; private static final String BASE_GIT_PATH = "http://github.so.kadaster.nl/PDOK/catalogus/archive/"; private static final Logger LOGGER = LoggerFactory.getLogger(GitInteractionsHandler.class); public static boolean isCatalogusPresent(File destinationFolder) { return destinationFolder.exists(); } public static String whichBranchIsPresent(File destinationFolder) { File file = new File(destinationFolder.getPath() + File.separator + GIT_BRANCH_TXT); List<String> lines; try { lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); } catch (IOException e) { return "Unable to read File."; } String output = ""; for (String string : lines) { output += string; } return output; } public static boolean checkout(String branchName, File destinationFolder, String authorization) { if (downloadAndUnpackZipFileFromGit(branchName, destinationFolder, authorization)) { try { for (int i = 1; i <= 5; i++) { if (renameFolders(destinationFolder, branchName)) { writeBranchNameToFile(branchName, destinationFolder); return true; } Thread.sleep(200); } } catch (IOException e) { LOGGER.error("Something went wrong with renaming the Catalogus Folders.", e); } catch (InterruptedException e) { LOGGER.error("InterruptedException on the sleep timer.", e); } } return false; } private static void writeBranchNameToFile(String branchName, File destinationFolder) throws IOException { File file = new File(destinationFolder + File.separator + GIT_BRANCH_TXT); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write(branchName); writer.flush(); writer.close(); } private static boolean downloadAndUnpackZipFileFromGit(String branchName, File destinationFolder, String authorization) { InputStream fileInputStream; try { fileInputStream = retrieveZipFromGit(branchName, authorization); clearCatalogusOldDirectory(destinationFolder.getParentFile()); unpackZipIntoTempFolder(fileInputStream, destinationFolder.getParentFile()); return true; } catch (IOException e) { LOGGER.error("Something went wrong with retrieving and unpacking the zip for " + branchName + " from Git.", e); return false; } } private static InputStream retrieveZipFromGit(String branchName, String authorization) throws IOException { String url = BASE_GIT_PATH + branchName.trim() + ".zip"; URL gitUrl = new URL(url); HttpURLConnection httpConnection = (HttpURLConnection) gitUrl.openConnection(); httpConnection.setRequestProperty(AUTHORIZATION, authorization); return httpConnection.getInputStream(); } private static void clearCatalogusOldDirectory(File parentDirectory) throws IOException { File file = new File(parentDirectory + File.separator + "catalogus_old"); if (file.exists()) { FileUtils.cleanDirectory(file); FileUtils.deleteDirectory(file); } } private static void unpackZipIntoTempFolder(InputStream inputStream, File parentDirectory) throws IOException { byte[] buffer = new byte[1024]; if (!parentDirectory.exists()) { parentDirectory.mkdir(); } ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(parentDirectory + File.separator + fileName); new File(newFile.getParent()).mkdirs(); writeFile(buffer, zis, newFile); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } private static void writeFile(byte[] buffer, ZipInputStream zis, File newFile) throws IOException { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } private static boolean renameFolders(File destinationFolder, String branchName) throws IOException { File tempFolder = new File(destinationFolder.getParentFile() + File.separator + "catalogus-" + branchName); File oldFolder = new File(destinationFolder.getParentFile() + File.separator + "catalogus_old"); try { if (destinationFolder.exists()) { Files.move(destinationFolder.toPath(), oldFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); } } catch (IOException e) { LOGGER.info("Unable to move catalogus to _old.", e); return false; } try { Files.move(tempFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { LOGGER.error("Failed to place new checkout in catalogus! Attempting to return current version.", e); Files.move(oldFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); return false; } return true; } }
src/main/java/nl/pdok/catalog/gitutil/GitInteractionsHandler.java
package nl.pdok.catalog.gitutil; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GitInteractionsHandler { private static final String GIT_BRANCH_TXT = "gitBranch.txt"; private static final String AUTHORIZATION = "Authorization"; private static final String BASE_GIT_PATH = "http://github.so.kadaster.nl/PDOK/catalogus/archive/"; private static final Logger LOGGER = LoggerFactory.getLogger(GitInteractionsHandler.class); public static boolean isCatalogusPresent(File destinationFolder) { return destinationFolder.exists(); } public static String whichBranchIsPresent(File destinationFolder) { File file = new File(destinationFolder.getPath() + File.separator + GIT_BRANCH_TXT); List<String> lines; try { lines = Files.readAllLines(file.toPath()); } catch (IOException e) { return "Unable to read File."; } String output = ""; for (String string : lines) { output += string; } return output; } public static boolean checkout(String branchName, File destinationFolder, String authorization) { if (downloadAndUnpackZipFileFromGit(branchName, destinationFolder, authorization)) { try { for (int i = 1; i <= 5; i++) { if (renameFolders(destinationFolder, branchName)) { writeBranchNameToFile(branchName, destinationFolder); return true; } Thread.sleep(200); } } catch (IOException e) { LOGGER.error("Something went wrong with renaming the Catalogus Folders.", e); } catch (InterruptedException e) { LOGGER.error("InterruptedException on the sleep timer.", e); } } return false; } private static void writeBranchNameToFile(String branchName, File destinationFolder) throws IOException { File file = new File(destinationFolder + File.separator + GIT_BRANCH_TXT); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write(branchName); writer.flush(); writer.close(); } private static boolean downloadAndUnpackZipFileFromGit(String branchName, File destinationFolder, String authorization) { InputStream fileInputStream; try { fileInputStream = retrieveZipFromGit(branchName, authorization); clearCatalogusOldDirectory(destinationFolder.getParentFile()); unpackZipIntoTempFolder(fileInputStream, destinationFolder.getParentFile()); return true; } catch (IOException e) { LOGGER.error("Something went wrong with retrieving and unpacking the zip for " + branchName + " from Git.", e); return false; } } private static InputStream retrieveZipFromGit(String branchName, String authorization) throws IOException { String url = BASE_GIT_PATH + branchName.trim() + ".zip"; URL gitUrl = new URL(url); HttpURLConnection httpConnection = (HttpURLConnection) gitUrl.openConnection(); httpConnection.setRequestProperty(AUTHORIZATION, authorization); return httpConnection.getInputStream(); } private static void clearCatalogusOldDirectory(File parentDirectory) throws IOException { File file = new File(parentDirectory + File.separator + "catalogus_old"); if (file.exists()) { FileUtils.cleanDirectory(file); FileUtils.deleteDirectory(file); } } private static void unpackZipIntoTempFolder(InputStream inputStream, File parentDirectory) throws IOException { byte[] buffer = new byte[1024]; if (!parentDirectory.exists()) { parentDirectory.mkdir(); } ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(parentDirectory + File.separator + fileName); new File(newFile.getParent()).mkdirs(); writeFile(buffer, zis, newFile); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } private static void writeFile(byte[] buffer, ZipInputStream zis, File newFile) throws IOException { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } private static boolean renameFolders(File destinationFolder, String branchName) throws IOException { File tempFolder = new File(destinationFolder.getParentFile() + File.separator + "catalogus-" + branchName); File oldFolder = new File(destinationFolder.getParentFile() + File.separator + "catalogus_old"); try { if (destinationFolder.exists()) { Files.move(destinationFolder.toPath(), oldFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); } } catch (IOException e) { LOGGER.info("Unable to move catalogus to _old.", e); return false; } try { Files.move(tempFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { LOGGER.error("Failed to place new checkout in catalogus! Attempting to return current version.", e); Files.move(oldFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.ATOMIC_MOVE); return false; } return true; } }
pdog-1263: java 7 compatibility
src/main/java/nl/pdok/catalog/gitutil/GitInteractionsHandler.java
pdog-1263: java 7 compatibility
Java
agpl-3.0
ec8a555eae469e5878480903110599632e639897
0
ProtocolSupport/ProtocolSupport,ridalarry/ProtocolSupport
package protocolsupport.api; import java.text.MessageFormat; import java.util.Arrays; import java.util.EnumMap; import org.apache.commons.lang3.Validate; import gnu.trove.map.hash.TIntObjectHashMap; public enum ProtocolVersion { MINECRAFT_FUTURE(-1, new OrderId(ProtocolType.PC, 17)), MINECRAFT_1_11_1(316, new OrderId(ProtocolType.PC, 16), "1.11.2"), MINECRAFT_1_11(315, new OrderId(ProtocolType.PC, 15), "1.11"), MINECRAFT_1_10(210, new OrderId(ProtocolType.PC, 14), "1.10"), MINECRAFT_1_9_4(110, new OrderId(ProtocolType.PC, 13), "1.9.4"), MINECRAFT_1_9_2(109, new OrderId(ProtocolType.PC, 12), "1.9.2"), MINECRAFT_1_9_1(108, new OrderId(ProtocolType.PC, 11), "1.9.1"), MINECRAFT_1_9(107, new OrderId(ProtocolType.PC, 10), "1.9"), MINECRAFT_1_8(47, new OrderId(ProtocolType.PC, 9), "1.8"), MINECRAFT_1_7_10(5, new OrderId(ProtocolType.PC, 8), "1.7.10"), MINECRAFT_1_7_5(4, new OrderId(ProtocolType.PC, 7), "1.7.5"), MINECRAFT_1_6_4(78, new OrderId(ProtocolType.PC, 6), "1.6.4"), MINECRAFT_1_6_2(74, new OrderId(ProtocolType.PC, 5), "1.6.2"), MINECRAFT_1_6_1(73, new OrderId(ProtocolType.PC, 4), "1.6.1"), MINECRAFT_1_5_2(61, new OrderId(ProtocolType.PC, 3), "1.5.2"), MINECRAFT_1_5_1(60, new OrderId(ProtocolType.PC, 2), "1.5.1"), MINECRAFT_1_4_7(51, new OrderId(ProtocolType.PC, 1), "1.4.7"), MINECRAFT_LEGACY(-1, new OrderId(ProtocolType.PC, 0)), UNKNOWN(-1, new OrderId(ProtocolType.UNKNOWN, 0)); private final int id; private final OrderId orderId; private final String name; ProtocolVersion(int id, OrderId orderid) { this(id, orderid, null); } ProtocolVersion(int id, OrderId orderId, String name) { this.id = id; this.orderId = orderId; this.name = name; } /** * Return protocol type of this protocol version * @return {@link ProtocolType} of this protocol version */ public ProtocolType getProtocolType() { return orderId.type; } /** * Returns the network version id of this protocol version * @return network id of this protocol version */ public int getId() { return id; } /** * Returns the user friendly version name * Notice: This name can change, so it shouldn't be used as a key anywhere * @return */ public String getName() { return name; } /** * Returns if this version is supported as game version (i.e.: player can join and play on the server) * @return true if this protocol version is supported */ public boolean isSupported() { return name != null; } /** * Returns if the game version used by this protocol released after the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released after the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isAfter(ProtocolVersion another) { return orderId.compareTo(another.orderId) > 0; } /** * Returns if the game version used by this protocol released after (or is the same) the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released after (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isAfterOrEq(ProtocolVersion another) { return orderId.compareTo(another.orderId) >= 0; } /** * Returns if the game version used by this protocol released before the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released before the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBefore(ProtocolVersion another) { return orderId.compareTo(another.orderId) < 0; } /** * Returns if the game version used by this protocol released before (or is the same) the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released before (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBeforeOrEq(ProtocolVersion another) { return orderId.compareTo(another.orderId) <= 0; } /** * Returns if the game version used by this protocol released in between (or is the same) of other game versions used by others protocol versions * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param one one protocol version * @param another another protocol version * @return true if game version is released before (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBetween(ProtocolVersion one, ProtocolVersion another) { return (isAfterOrEq(one) && isBeforeOrEq(another)) || (isBeforeOrEq(one) && isAfterOrEq(another)); } private static final TIntObjectHashMap<ProtocolVersion> byProtocolId = new TIntObjectHashMap<>(); static { for (ProtocolVersion version : ProtocolVersion.values()) { if (version.id != -1) { byProtocolId.put(version.id, version); } } } /** * Returns protocol version by network game id * @param id network version id * @return Returns protocol version by network game id or UNKNOWN if not found * @deprecated network version ids may be the same for different protocol versions */ @Deprecated public static ProtocolVersion fromId(int id) { ProtocolVersion version = byProtocolId.get(id); return version != null ? version : UNKNOWN; } private static final EnumMap<ProtocolType, ProtocolVersion[]> byOrderId = new EnumMap<>(ProtocolType.class); static { for (ProtocolType type : ProtocolType.values()) { if (type != ProtocolType.UNKNOWN) { byOrderId.put(type, Arrays.stream(ProtocolVersion.values()) .filter(version -> version.getProtocolType() == type) .sorted((o1, o2) -> o1.orderId.compareTo(o2.orderId)) .toArray(size -> new ProtocolVersion[size]) ); } } } /** * Returns all protocol versions that are between specified ones (inclusive) * Throws {@link IllegalArgumentException} if protocol versions types are not the same or one of the types is UNKNOWN * @param one one protocol version * @param another one protocol version * @return all protocol versions that are between specified ones (inclusive) */ public static ProtocolVersion[] getAllBetween(ProtocolVersion one, ProtocolVersion another) { ProtocolType type = one.getProtocolType(); Validate.isTrue(type == another.getProtocolType(), "Can't get versions between different protocol types"); Validate.isTrue(type != ProtocolType.UNKNOWN, "Can't get versions for unknown protocol type"); ProtocolVersion[] versions = byOrderId.get(type); int startId = Math.min(one.orderId.id, another.orderId.id); int endId = Math.max(one.orderId.id, another.orderId.id); ProtocolVersion[] between = new ProtocolVersion[(endId - startId) + 1]; for (int i = startId; i <= endId; i++) { between[i - startId] = versions[i]; } return between; } /** * Returns latest supported protocol version for specified protocol type * Throws {@link IllegalArgumentException} if protocol type has not supported protocol versions * @param type protocol type * @return latest supported protocol version for specified protocol type * @throws IllegalArgumentException */ public static ProtocolVersion getLatest(ProtocolType type) { switch (type) { case PC: { return MINECRAFT_1_11_1; } default: { throw new IllegalArgumentException(MessageFormat.format("No supported versions for protocol type {0}", type)); } } } /** * Returns oldest supported protocol version for specified protocol type * Throws {@link IllegalArgumentException} if protocol type has not supported protocol versions * @param type protocol type * @return oldest supported protocol version for specified protocol type * @throws IllegalArgumentException */ public static ProtocolVersion getOldest(ProtocolType type) { switch (type) { case PC: { return MINECRAFT_1_4_7; } default: { throw new IllegalArgumentException(MessageFormat.format("No supported versions for protocol type {0}", type)); } } } /** * Returns all protocol versions that are after specified one (inclusive) * Throws {@link IllegalArgumentException} if getAllBetween(version, getLatest(version.getType())) throws one * @param version protocol version * @return all protocol versions that are after specified one (inclusive) * @throws IllegalArgumentException * @deprecated non intuitive behavior */ @Deprecated public static ProtocolVersion[] getAllAfter(ProtocolVersion version) { return getAllBetween(version, getLatest(version.getProtocolType())); } /** * Returns all protocol versions that are before specified one (inclusive) * Throws {@link IllegalArgumentException} if getAllBetween(getOldest(version.getType()), version) throws one * @param version protocol version * @return all protocol versions that are before specified one * @throws IllegalArgumentException * @deprecated non intuitive behavior */ @Deprecated public static ProtocolVersion[] getAllBefore(ProtocolVersion version) { return getAllBetween(getOldest(version.getProtocolType()), version); } /** * Returns latest supported protocol version for {@link ProtocolType} PC * @return latest supported protocol version for {@link ProtocolType} PC * @deprecated */ @Deprecated public static ProtocolVersion getLatest() { return getLatest(ProtocolType.PC); } /** * Returns oldest supported protocol version for {@link ProtocolType} PC * @return oldest supported protocol version for {@link ProtocolType} PC */ @Deprecated public static ProtocolVersion getOldest() { return getLatest(ProtocolType.PC); } private static class OrderId implements Comparable<OrderId> { private final ProtocolType type; private final int id; public OrderId(ProtocolType type, int id) { this.type = type; this.id = id; } @Override public int compareTo(OrderId o) { Validate.isTrue(this.type != ProtocolType.UNKNOWN, "Can't compare unknown protocol type"); Validate.isTrue(o.type != ProtocolType.UNKNOWN, "Can't compare with unknown protocol type"); Validate.isTrue(this.type == o.type, "Can't compare order from different types: this - {0}, other - {1}", type, o.type); return Integer.compare(id, o.id); } } }
src/protocolsupport/api/ProtocolVersion.java
package protocolsupport.api; import java.text.MessageFormat; import java.util.Arrays; import java.util.EnumMap; import org.apache.commons.lang3.Validate; import gnu.trove.map.hash.TIntObjectHashMap; public enum ProtocolVersion { MINECRAFT_FUTURE(-1, new OrderId(ProtocolType.PC, 17)), MINECRAFT_1_11_1(316, new OrderId(ProtocolType.PC, 16), "1.11.1"), MINECRAFT_1_11(315, new OrderId(ProtocolType.PC, 15), "1.11"), MINECRAFT_1_10(210, new OrderId(ProtocolType.PC, 14), "1.10"), MINECRAFT_1_9_4(110, new OrderId(ProtocolType.PC, 13), "1.9.4"), MINECRAFT_1_9_2(109, new OrderId(ProtocolType.PC, 12), "1.9.2"), MINECRAFT_1_9_1(108, new OrderId(ProtocolType.PC, 11), "1.9.1"), MINECRAFT_1_9(107, new OrderId(ProtocolType.PC, 10), "1.9"), MINECRAFT_1_8(47, new OrderId(ProtocolType.PC, 9), "1.8"), MINECRAFT_1_7_10(5, new OrderId(ProtocolType.PC, 8), "1.7.10"), MINECRAFT_1_7_5(4, new OrderId(ProtocolType.PC, 7), "1.7.5"), MINECRAFT_1_6_4(78, new OrderId(ProtocolType.PC, 6), "1.6.4"), MINECRAFT_1_6_2(74, new OrderId(ProtocolType.PC, 5), "1.6.2"), MINECRAFT_1_6_1(73, new OrderId(ProtocolType.PC, 4), "1.6.1"), MINECRAFT_1_5_2(61, new OrderId(ProtocolType.PC, 3), "1.5.2"), MINECRAFT_1_5_1(60, new OrderId(ProtocolType.PC, 2), "1.5.1"), MINECRAFT_1_4_7(51, new OrderId(ProtocolType.PC, 1), "1.4.7"), MINECRAFT_LEGACY(-1, new OrderId(ProtocolType.PC, 0)), UNKNOWN(-1, new OrderId(ProtocolType.UNKNOWN, 0)); private final int id; private final OrderId orderId; private final String name; ProtocolVersion(int id, OrderId orderid) { this(id, orderid, null); } ProtocolVersion(int id, OrderId orderId, String name) { this.id = id; this.orderId = orderId; this.name = name; } /** * Return protocol type of this protocol version * @return {@link ProtocolType} of this protocol version */ public ProtocolType getProtocolType() { return orderId.type; } /** * Returns the network version id of this protocol version * @return network id of this protocol version */ public int getId() { return id; } /** * Returns the user friendly version name * Notice: This name can change, so it shouldn't be used as a key anywhere * @return */ public String getName() { return name; } /** * Returns if this version is supported as game version (i.e.: player can join and play on the server) * @return true if this protocol version is supported */ public boolean isSupported() { return name != null; } /** * Returns if the game version used by this protocol released after the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released after the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isAfter(ProtocolVersion another) { return orderId.compareTo(another.orderId) > 0; } /** * Returns if the game version used by this protocol released after (or is the same) the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released after (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isAfterOrEq(ProtocolVersion another) { return orderId.compareTo(another.orderId) >= 0; } /** * Returns if the game version used by this protocol released before the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released before the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBefore(ProtocolVersion another) { return orderId.compareTo(another.orderId) < 0; } /** * Returns if the game version used by this protocol released before (or is the same) the game version used by another protocol version * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param another another protocol version * @return true if game version is released before (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBeforeOrEq(ProtocolVersion another) { return orderId.compareTo(another.orderId) <= 0; } /** * Returns if the game version used by this protocol released in between (or is the same) of other game versions used by others protocol versions * Throws {@link IllegalArgumentException} if protocol versions use different protocol types * @param one one protocol version * @param another another protocol version * @return true if game version is released before (or is the same) the game version used by another protocol version * @throws IllegalArgumentException */ public boolean isBetween(ProtocolVersion one, ProtocolVersion another) { return (isAfterOrEq(one) && isBeforeOrEq(another)) || (isBeforeOrEq(one) && isAfterOrEq(another)); } private static final TIntObjectHashMap<ProtocolVersion> byProtocolId = new TIntObjectHashMap<>(); static { for (ProtocolVersion version : ProtocolVersion.values()) { if (version.id != -1) { byProtocolId.put(version.id, version); } } } /** * Returns protocol version by network game id * @param id network version id * @return Returns protocol version by network game id or UNKNOWN if not found * @deprecated network version ids may be the same for different protocol versions */ @Deprecated public static ProtocolVersion fromId(int id) { ProtocolVersion version = byProtocolId.get(id); return version != null ? version : UNKNOWN; } private static final EnumMap<ProtocolType, ProtocolVersion[]> byOrderId = new EnumMap<>(ProtocolType.class); static { for (ProtocolType type : ProtocolType.values()) { if (type != ProtocolType.UNKNOWN) { byOrderId.put(type, Arrays.stream(ProtocolVersion.values()) .filter(version -> version.getProtocolType() == type) .sorted((o1, o2) -> o1.orderId.compareTo(o2.orderId)) .toArray(size -> new ProtocolVersion[size]) ); } } } /** * Returns all protocol versions that are between specified ones (inclusive) * Throws {@link IllegalArgumentException} if protocol versions types are not the same or one of the types is UNKNOWN * @param one one protocol version * @param another one protocol version * @return all protocol versions that are between specified ones (inclusive) */ public static ProtocolVersion[] getAllBetween(ProtocolVersion one, ProtocolVersion another) { ProtocolType type = one.getProtocolType(); Validate.isTrue(type == another.getProtocolType(), "Can't get versions between different protocol types"); Validate.isTrue(type != ProtocolType.UNKNOWN, "Can't get versions for unknown protocol type"); ProtocolVersion[] versions = byOrderId.get(type); int startId = Math.min(one.orderId.id, another.orderId.id); int endId = Math.max(one.orderId.id, another.orderId.id); ProtocolVersion[] between = new ProtocolVersion[(endId - startId) + 1]; for (int i = startId; i <= endId; i++) { between[i - startId] = versions[i]; } return between; } /** * Returns latest supported protocol version for specified protocol type * Throws {@link IllegalArgumentException} if protocol type has not supported protocol versions * @param type protocol type * @return latest supported protocol version for specified protocol type * @throws IllegalArgumentException */ public static ProtocolVersion getLatest(ProtocolType type) { switch (type) { case PC: { return MINECRAFT_1_11_1; } default: { throw new IllegalArgumentException(MessageFormat.format("No supported versions for protocol type {0}", type)); } } } /** * Returns oldest supported protocol version for specified protocol type * Throws {@link IllegalArgumentException} if protocol type has not supported protocol versions * @param type protocol type * @return oldest supported protocol version for specified protocol type * @throws IllegalArgumentException */ public static ProtocolVersion getOldest(ProtocolType type) { switch (type) { case PC: { return MINECRAFT_1_4_7; } default: { throw new IllegalArgumentException(MessageFormat.format("No supported versions for protocol type {0}", type)); } } } /** * Returns all protocol versions that are after specified one (inclusive) * Throws {@link IllegalArgumentException} if getAllBetween(version, getLatest(version.getType())) throws one * @param version protocol version * @return all protocol versions that are after specified one (inclusive) * @throws IllegalArgumentException * @deprecated non intuitive behavior */ @Deprecated public static ProtocolVersion[] getAllAfter(ProtocolVersion version) { return getAllBetween(version, getLatest(version.getProtocolType())); } /** * Returns all protocol versions that are before specified one (inclusive) * Throws {@link IllegalArgumentException} if getAllBetween(getOldest(version.getType()), version) throws one * @param version protocol version * @return all protocol versions that are before specified one * @throws IllegalArgumentException * @deprecated non intuitive behavior */ @Deprecated public static ProtocolVersion[] getAllBefore(ProtocolVersion version) { return getAllBetween(getOldest(version.getProtocolType()), version); } /** * Returns latest supported protocol version for {@link ProtocolType} PC * @return latest supported protocol version for {@link ProtocolType} PC * @deprecated */ @Deprecated public static ProtocolVersion getLatest() { return getLatest(ProtocolType.PC); } /** * Returns oldest supported protocol version for {@link ProtocolType} PC * @return oldest supported protocol version for {@link ProtocolType} PC */ @Deprecated public static ProtocolVersion getOldest() { return getLatest(ProtocolType.PC); } private static class OrderId implements Comparable<OrderId> { private final ProtocolType type; private final int id; public OrderId(ProtocolType type, int id) { this.type = type; this.id = id; } @Override public int compareTo(OrderId o) { Validate.isTrue(this.type != ProtocolType.UNKNOWN, "Can't compare unknown protocol type"); Validate.isTrue(o.type != ProtocolType.UNKNOWN, "Can't compare with unknown protocol type"); Validate.isTrue(this.type == o.type, "Can't compare order from different types: this - {0}, other - {1}", type, o.type); return Integer.compare(id, o.id); } } }
Change MINECRAFT_1_11 friendly version name from 1.11.1 to 1.11.2
src/protocolsupport/api/ProtocolVersion.java
Change MINECRAFT_1_11 friendly version name from 1.11.1 to 1.11.2
Java
agpl-3.0
a46303da00a019eeafb8dc04dd873cf7531b2e23
0
kuali/kfs-git-training
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.coa.businessobject; import java.util.LinkedHashMap; import java.util.logging.Logger; public class ReportingCode { private static Logger LOG = Logger.getLogger(ReportingCode.class.getName()); private String chartOfAccountsCode; private String organizationCode; private String financialReportingCode; private String financialReportingCodeDescription; private String financialReportingCodeMgrId; private String financialReportsToReportingCode; private boolean active; private Chart chart; private Organization org; private ReportingCode reportingCodes; /** * Creates new object and sets up logging */ public ReportingCode(){ LOG.log(Level.INFO, "An object of class "+getClass().getName()+" has been instantiated"); } /** * @return Returns the chartOfAccountsCode. */ public String getChartOfAccountsCode() { return chartOfAccountsCode; } /** * @param chartOfAccountsCode The chartOfAccountsCode to set. */ public void setChartOfAccountsCode(String chartOfAccountsCode) { this.chartOfAccountsCode = chartOfAccountsCode; } /** * @return Returns the financialReportingCode. */ public String getFinancialReportingCode() { return financialReportingCode; } /** * @param financialReportingCode The financialReportingCode to set. */ public void setFinancialReportingCode(String financialReportingCode) { this.financialReportingCode = financialReportingCode; } /** * @return Returns the financialReportingCodeDescription. */ public String getFinancialReportingCodeDescription() { return financialReportingCodeDescription; } /** * @param financialReportingCodeDescription The financialReportingCodeDescription to set. */ public void setFinancialReportingCodeDescription(String financialReportingCodeDescription) { this.financialReportingCodeDescription = financialReportingCodeDescription; } /** * @return Returns the financialReportingCodeMgrId. */ public String getFinancialReportingCodeMgrId() { return financialReportingCodeMgrId; } /** * @param financialReportingCodeMgrId The financialReportingCodeMgrId to set. */ public void setFinancialReportingCodeMgrId(String financialReportingCodeMgrId) { this.financialReportingCodeMgrId = financialReportingCodeMgrId; } /** * @return Returns the organizationCode. */ public String getOrganizationCode() { return organizationCode; } /** * @param organizationCode The organizationCode to set. */ public void setOrganizationCode(String organizationCode) { this.organizationCode = organizationCode; } /** * @return Returns the financialReportsToReportingCode. */ public String getFinancialReportsToReportingCode() { return financialReportsToReportingCode; } /** * @param financialReportsToReportingCode The financialReportsToReportingCode to set. */ public void setFinancialReportsToReportingCode(String financialReportsToReportingCode) { this.financialReportsToReportingCode = financialReportsToReportingCode; } /** * @return Returns the chart. */ public Chart getChart() { return chart; } /** * @param chart The chart to set. * @deprecated */ public void setChart(Chart chart) { this.chart = chart; } /** * @return Returns the org. */ public Organization getOrg() { return org; } /** * @param org The org to set. * @deprecated */ public void setOrg(Organization org) { this.org = org; } /** * @return Returns the reportingCodes. */ public ReportingCode getReportingCodes() { return reportingCodes; } /** * @param reportingCodes The reportingCodes to set. * @deprecated */ public void setReportingCodes(ReportingCode reportingCodes) { this.reportingCodes = reportingCodes; } protected LinkedHashMap toStringMapper_RICE20_REFACTORME() { LinkedHashMap m = new LinkedHashMap(); m.put("chartOfAccountsCode", this.chartOfAccountsCode); m.put("organizationCode", this.organizationCode); m.put("financialReportingCode", this.financialReportingCode); m.put("financialReportingCodeDescription", this.financialReportingCodeDescription); m.put("financialReportingCodeMgrId", this.financialReportingCodeMgrId); m.put("financialReportsToReportingCode", this.financialReportsToReportingCode); return m; } /** * Gets the active attribute. * @return Returns the active. */ public boolean isActive() { return active; } /** * Sets the active attribute value. * @param active The active to set. */ public void setActive(boolean active) { this.active = active; } }
src/main/java/org/kuali/kfs/coa/businessobject/ReportingCode.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.coa.businessobject; import java.util.LinkedHashMap; import java.util.logging.Logger; public class ReportingCode { private static Logger LOG = Logger.getLogger(ReportingCode.class.getName()); private String chartOfAccountsCode; private String organizationCode; private String financialReportingCode; private String financialReportingCodeDescription; private String financialReportingCodeMgrId; private String financialReportsToReportingCode; private boolean active; private Chart chart; private Organization org; private ReportingCode reportingCodes; /** * @return Returns the chartOfAccountsCode. */ public String getChartOfAccountsCode() { return chartOfAccountsCode; } /** * @param chartOfAccountsCode The chartOfAccountsCode to set. */ public void setChartOfAccountsCode(String chartOfAccountsCode) { this.chartOfAccountsCode = chartOfAccountsCode; } /** * @return Returns the financialReportingCode. */ public String getFinancialReportingCode() { return financialReportingCode; } /** * @param financialReportingCode The financialReportingCode to set. */ public void setFinancialReportingCode(String financialReportingCode) { this.financialReportingCode = financialReportingCode; } /** * @return Returns the financialReportingCodeDescription. */ public String getFinancialReportingCodeDescription() { return financialReportingCodeDescription; } /** * @param financialReportingCodeDescription The financialReportingCodeDescription to set. */ public void setFinancialReportingCodeDescription(String financialReportingCodeDescription) { this.financialReportingCodeDescription = financialReportingCodeDescription; } /** * @return Returns the financialReportingCodeMgrId. */ public String getFinancialReportingCodeMgrId() { return financialReportingCodeMgrId; } /** * @param financialReportingCodeMgrId The financialReportingCodeMgrId to set. */ public void setFinancialReportingCodeMgrId(String financialReportingCodeMgrId) { this.financialReportingCodeMgrId = financialReportingCodeMgrId; } /** * @return Returns the organizationCode. */ public String getOrganizationCode() { return organizationCode; } /** * @param organizationCode The organizationCode to set. */ public void setOrganizationCode(String organizationCode) { this.organizationCode = organizationCode; } /** * @return Returns the financialReportsToReportingCode. */ public String getFinancialReportsToReportingCode() { return financialReportsToReportingCode; } /** * @param financialReportsToReportingCode The financialReportsToReportingCode to set. */ public void setFinancialReportsToReportingCode(String financialReportsToReportingCode) { this.financialReportsToReportingCode = financialReportsToReportingCode; } /** * @return Returns the chart. */ public Chart getChart() { return chart; } /** * @param chart The chart to set. * @deprecated */ public void setChart(Chart chart) { this.chart = chart; } /** * @return Returns the org. */ public Organization getOrg() { return org; } /** * @param org The org to set. * @deprecated */ public void setOrg(Organization org) { this.org = org; } /** * @return Returns the reportingCodes. */ public ReportingCode getReportingCodes() { return reportingCodes; } /** * @param reportingCodes The reportingCodes to set. * @deprecated */ public void setReportingCodes(ReportingCode reportingCodes) { this.reportingCodes = reportingCodes; } protected LinkedHashMap toStringMapper_RICE20_REFACTORME() { LinkedHashMap m = new LinkedHashMap(); m.put("chartOfAccountsCode", this.chartOfAccountsCode); m.put("organizationCode", this.organizationCode); m.put("financialReportingCode", this.financialReportingCode); m.put("financialReportingCodeDescription", this.financialReportingCodeDescription); m.put("financialReportingCodeMgrId", this.financialReportingCodeMgrId); m.put("financialReportsToReportingCode", this.financialReportsToReportingCode); return m; } /** * Gets the active attribute. * @return Returns the active. */ public boolean isActive() { return active; } /** * Sets the active attribute value. * @param active The active to set. */ public void setActive(boolean active) { this.active = active; } }
EXER2 Adding the constructor + logging implementation.
src/main/java/org/kuali/kfs/coa/businessobject/ReportingCode.java
EXER2 Adding the constructor + logging implementation.
Java
lgpl-2.1
2fdb7b43e7bdffbbcb86ab4e09f76dd2517d3329
0
jdoyle65/checkstyle,beckerhd/checkstyle,HubSpot/checkstyle,jochenvdv/checkstyle,naver/checkstyle,jonmbake/checkstyle,MEZk/checkstyle,sabaka/checkstyle,gallandarakhneorg/checkstyle,checkstyle/checkstyle,jasonchaffee/checkstyle,bansalayush/checkstyle,jasonchaffee/checkstyle,philwebb/checkstyle,designreuse/checkstyle,FeodorFitsner/checkstyle,sharang108/checkstyle,checkstyle/checkstyle,ilanKeshet/checkstyle,autermann/checkstyle,rnveach/checkstyle,FeodorFitsner/checkstyle,naver/checkstyle,another-dave/checkstyle,gallandarakhneorg/checkstyle,ivanov-alex/checkstyle,philwebb/checkstyle,designreuse/checkstyle,sirdis/checkstyle,rnveach/checkstyle,AkshitaKukreja30/checkstyle,checkstyle/checkstyle,baratali/checkstyle,sirdis/checkstyle,jochenvdv/checkstyle,WilliamRen/checkstyle,MEZk/checkstyle,jochenvdv/checkstyle,FeodorFitsner/checkstyle,Godin/checkstyle,HubSpot/checkstyle,romani/checkstyle,izishared/checkstyle,Bhavik3/checkstyle,pietern/checkstyle,gallandarakhneorg/checkstyle,StetsiukRoman/checkstyle,jonmbake/checkstyle,sharang108/checkstyle,liscju/checkstyle,vboerchers/checkstyle,zofuthan/checkstyle-1,sabaka/checkstyle,attatrol/checkstyle,attatrol/checkstyle,another-dave/checkstyle,vboerchers/checkstyle,rnveach/checkstyle,naver/checkstyle,izishared/checkstyle,jasonchaffee/checkstyle,philwebb/checkstyle,universsky/checkstyle,rnveach/checkstyle,romani/checkstyle,liscju/checkstyle,baratali/checkstyle,sharang108/checkstyle,AkshitaKukreja30/checkstyle,WilliamRen/checkstyle,Andrew0701/checkstyle,designreuse/checkstyle,ivanov-alex/checkstyle,checkstyle/checkstyle,cs1331/checkstyle,izishared/checkstyle,rmswimkktt/checkstyle,mkordas/checkstyle,StetsiukRoman/checkstyle,cs1331/checkstyle,WilliamRen/checkstyle,romani/checkstyle,zofuthan/checkstyle-1,Bhavik3/checkstyle,ilanKeshet/checkstyle,nikhilgupta23/checkstyle,beckerhd/checkstyle,llocc/checkstyle,sabaka/checkstyle,romani/checkstyle,mkordas/checkstyle,vboerchers/checkstyle,WonderCsabo/checkstyle,bansalayush/checkstyle,universsky/checkstyle,universsky/checkstyle,mkordas/checkstyle,rmswimkktt/checkstyle,ilanKeshet/checkstyle,checkstyle/checkstyle,pietern/checkstyle,bansalayush/checkstyle,rmswimkktt/checkstyle,ivanov-alex/checkstyle,nikhilgupta23/checkstyle,MEZk/checkstyle,HubSpot/checkstyle,sirdis/checkstyle,checkstyle/checkstyle,Andrew0701/checkstyle,Godin/checkstyle,baratali/checkstyle,Godin/checkstyle,liscju/checkstyle,cs1331/checkstyle,nikhilgupta23/checkstyle,beckerhd/checkstyle,WonderCsabo/checkstyle,Bhavik3/checkstyle,zofuthan/checkstyle-1,romani/checkstyle,autermann/checkstyle,WonderCsabo/checkstyle,pbaranchikov/checkstyle,StetsiukRoman/checkstyle,rnveach/checkstyle,jonmbake/checkstyle,another-dave/checkstyle,pietern/checkstyle,llocc/checkstyle,attatrol/checkstyle,romani/checkstyle,AkshitaKukreja30/checkstyle,llocc/checkstyle,pbaranchikov/checkstyle,jdoyle65/checkstyle,rnveach/checkstyle,autermann/checkstyle
package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.Locale; import java.util.Properties; import junit.framework.TestCase; public abstract class BaseCheckTestCase extends TestCase { /** a brief logger that only display info about errors */ protected static class BriefLogger extends DefaultLogger { public BriefLogger(OutputStream out) { super(out, true); } public void auditStarted(AuditEvent evt) {} public void fileFinished(AuditEvent evt) {} public void fileStarted(AuditEvent evt) {} } private final ByteArrayOutputStream mBAOS = new ByteArrayOutputStream(); protected final PrintStream mStream = new PrintStream(mBAOS); protected final Properties mProps = new Properties(); public static DefaultConfiguration createCheckConfig(Class aClazz) { final DefaultConfiguration checkConfig = new DefaultConfiguration(aClazz.getName()); return checkConfig; } protected Checker createChecker(Configuration aCheckConfig) throws Exception { final DefaultConfiguration dc = createCheckerConfig(aCheckConfig); final Checker c = new Checker(); // make sure the tests always run with english error messages // so the tests don't fail in supported locales like german final Locale locale = Locale.ENGLISH; c.setLocaleCountry(locale.getCountry()); c.setLocaleLanguage(locale.getLanguage()); c.configure(dc); c.addListener(new BriefLogger(mStream)); return c; } protected DefaultConfiguration createCheckerConfig(Configuration aConfig) { final DefaultConfiguration dc = new DefaultConfiguration("configuration"); final DefaultConfiguration twConf = createCheckConfig(TreeWalker.class); dc.addChild(twConf); twConf.addChild(aConfig); return dc; } protected static String getPath(String aFilename) throws IOException { final File f = new File(System.getProperty("testinputs.dir"), aFilename); return f.getCanonicalPath(); } protected void verify(Configuration aConfig, String aFileName, String[] aExpected) throws Exception { verify(createChecker(aConfig), aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aFileName, String[] aExpected) throws Exception { verify(aC, aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aProcessedFilename, String aMessageFileName, String[] aExpected) throws Exception { verify(aC, new File[] {new File(aProcessedFilename)}, aMessageFileName, aExpected); } protected void verify(Checker aC, File[] aProcessedFiles, String aMessageFileName, String[] aExpected) throws Exception { mStream.flush(); final int errs = aC.process(aProcessedFiles); // process each of the lines final ByteArrayInputStream bais = new ByteArrayInputStream(mBAOS.toByteArray()); final LineNumberReader lnr = new LineNumberReader(new InputStreamReader(bais)); for (int i = 0; i < aExpected.length; i++) { final String expected = aMessageFileName + ":" + aExpected[i]; final String actual = lnr.readLine(); assertEquals(expected, actual); } assertEquals(aExpected.length, errs); aC.destroy(); } }
src/tests/com/puppycrawl/tools/checkstyle/BaseCheckTestCase.java
package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.Locale; import java.util.Properties; import junit.framework.TestCase; public abstract class BaseCheckTestCase extends TestCase { /** a brief logger that only display info about errors */ protected static class BriefLogger extends DefaultLogger { public BriefLogger(OutputStream out) { super(out, true); } public void auditStarted(AuditEvent evt) {} public void fileFinished(AuditEvent evt) {} public void fileStarted(AuditEvent evt) {} } private final ByteArrayOutputStream mBAOS = new ByteArrayOutputStream(); protected final PrintStream mStream = new PrintStream(mBAOS); protected final Properties mProps = new Properties(); public static DefaultConfiguration createCheckConfig(Class aClazz) { final DefaultConfiguration checkConfig = new DefaultConfiguration(aClazz.getName()); return checkConfig; } protected Checker createChecker(Configuration aCheckConfig) throws Exception { final DefaultConfiguration dc = createCheckerConfig(aCheckConfig); final Checker c = new Checker(); // make sure the tests always run with english error messages // so the tests don't fail in supported locales like german final Locale locale = Locale.ENGLISH; c.setLocaleCountry(locale.getCountry()); c.setLocaleLanguage(locale.getLanguage()); c.configure(dc); c.addListener(new BriefLogger(mStream)); return c; } protected DefaultConfiguration createCheckerConfig(Configuration aConfig) { final DefaultConfiguration dc = new DefaultConfiguration("configuration"); final DefaultConfiguration twConf = createCheckConfig(TreeWalker.class); dc.addChild(twConf); twConf.addChild(aConfig); return dc; } protected static String getPath(String aFilename) throws IOException { final File f = new File(System.getProperty("testinputs.dir"), aFilename); return f.getCanonicalPath(); } protected void verify(Configuration aConfig, String aFileName, String[] aExpected) throws Exception { verify(createChecker(aConfig), aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aFileName, String[] aExpected) throws Exception { verify(aC, aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aProcessedFilename, String aMessageFileName, String[] aExpected) throws Exception { verify(aC, new File[] {new File(aProcessedFilename)}, aMessageFileName, aExpected); } protected void verify(Checker aC, File[] aProcessedFiles, String aMessageFileName, String[] aExpected) throws Exception { mStream.flush(); final int errs = aC.process(aProcessedFiles); // process each of the lines final ByteArrayInputStream bais = new ByteArrayInputStream(mBAOS.toByteArray()); final LineNumberReader lnr = new LineNumberReader(new InputStreamReader(bais)); for (int i = 0; i < aExpected.length; i++) { assertEquals(aMessageFileName + ":" + aExpected[i], lnr.readLine()); } assertEquals(aExpected.length, errs); aC.destroy(); } }
assign expected and actual result to variables, eases debugging
src/tests/com/puppycrawl/tools/checkstyle/BaseCheckTestCase.java
assign expected and actual result to variables, eases debugging
Java
unlicense
3cdebe739596e2ffa54a7987a845bcb48d7c28b5
0
squeek502/HungerInPeace
package squeek.hungerinpeace; import net.minecraft.world.EnumDifficulty; import net.minecraftforge.common.MinecraftForge; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import squeek.applecore.api.hunger.ExhaustionEvent; import squeek.applecore.api.hunger.HealthRegenEvent; import squeek.applecore.api.hunger.StarvationEvent; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Mod(modid = ModInfo.MODID, version = ModInfo.VERSION, dependencies = "required-after:AppleCore") public class HungerInPeace { public static final Logger Log = LogManager.getLogger(ModInfo.MODID); @EventHandler public void preInit(FMLPreInitializationEvent event) { ModConfig.init(event.getSuggestedConfigurationFile()); MinecraftForge.EVENT_BUS.register(this); } @EventHandler public void postInit(FMLPostInitializationEvent event) { FMLInterModComms.sendRuntimeMessage(ModInfo.MODID, "VersionChecker", "addVersionCheck", "http://www.ryanliptak.com/minecraft/versionchecker/squeek502/HungerInPeace"); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onExhausted(ExhaustionEvent.Exhausted event) { if (event.player.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) return; if (event.player.getFoodStats().getSaturationLevel() <= 0) event.deltaHunger = -1; } @SubscribeEvent(priority = EventPriority.LOWEST) public void onPeacefulRegen(HealthRegenEvent.PeacefulRegen event) { if (!ModConfig.DISABLE_HEALTH_REGEN) return; event.setCanceled(true); } @SubscribeEvent(priority = EventPriority.LOWEST) public void onStarve(StarvationEvent.Starve event) { if (event.starveDamage != 0f) return; if (event.player.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) return; if (event.player.getHealth() <= ModConfig.MIN_HEALTH_FROM_STARVATION) return; event.starveDamage = 1f; } }
java/squeek/hungerinpeace/HungerInPeace.java
package squeek.hungerinpeace; import net.minecraft.world.EnumDifficulty; import net.minecraftforge.common.MinecraftForge; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import squeek.applecore.api.hunger.ExhaustionEvent; import squeek.applecore.api.hunger.HealthRegenEvent; import squeek.applecore.api.hunger.StarvationEvent; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @Mod(modid = ModInfo.MODID, version = ModInfo.VERSION, dependencies = "required-after:AppleCore") public class HungerInPeace { public static final Logger Log = LogManager.getLogger(ModInfo.MODID); @EventHandler public void preInit(FMLPreInitializationEvent event) { ModConfig.init(event.getSuggestedConfigurationFile()); MinecraftForge.EVENT_BUS.register(this); } @SubscribeEvent(priority = EventPriority.HIGHEST) public void onExhausted(ExhaustionEvent.Exhausted event) { if (event.player.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) return; if (event.player.getFoodStats().getSaturationLevel() <= 0) event.deltaHunger = -1; } @SubscribeEvent(priority = EventPriority.LOWEST) public void onPeacefulRegen(HealthRegenEvent.PeacefulRegen event) { if (!ModConfig.DISABLE_HEALTH_REGEN) return; event.setCanceled(true); } @SubscribeEvent(priority = EventPriority.LOWEST) public void onStarve(StarvationEvent.Starve event) { if (event.starveDamage != 0f) return; if (event.player.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) return; if (event.player.getHealth() <= ModConfig.MIN_HEALTH_FROM_STARVATION) return; event.starveDamage = 1f; } }
Add Version Checker support
java/squeek/hungerinpeace/HungerInPeace.java
Add Version Checker support
Java
apache-2.0
984861d8d0091c882c6092db1d1f42ad5b084268
0
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
/* * 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.uima.cas.impl; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; import org.apache.uima.UIMAFramework; import org.apache.uima.UIMARuntimeException; import org.apache.uima.UimaSerializable; import org.apache.uima.cas.AbstractCas_ImplBase; import org.apache.uima.cas.ArrayFS; import org.apache.uima.cas.BooleanArrayFS; import org.apache.uima.cas.ByteArrayFS; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.CasOwner; import org.apache.uima.cas.CommonArrayFS; import org.apache.uima.cas.ComponentInfo; import org.apache.uima.cas.ConstraintFactory; import org.apache.uima.cas.DoubleArrayFS; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIndexRepository; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeaturePath; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.FeatureValuePath; import org.apache.uima.cas.FloatArrayFS; import org.apache.uima.cas.IntArrayFS; import org.apache.uima.cas.LongArrayFS; import org.apache.uima.cas.Marker; import org.apache.uima.cas.SerialFormat; import org.apache.uima.cas.ShortArrayFS; import org.apache.uima.cas.SofaFS; import org.apache.uima.cas.SofaID; import org.apache.uima.cas.StringArrayFS; import org.apache.uima.cas.Type; import org.apache.uima.cas.TypeSystem; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.admin.CASFactory; import org.apache.uima.cas.admin.CASMgr; import org.apache.uima.cas.admin.FSIndexComparator; import org.apache.uima.cas.admin.FSIndexRepositoryMgr; import org.apache.uima.cas.admin.TypeSystemMgr; import org.apache.uima.cas.impl.FSsTobeAddedback.FSsTobeAddedbackSingle; import org.apache.uima.cas.impl.SlotKinds.SlotKind; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.cas.text.Language; import org.apache.uima.internal.util.IntVector; import org.apache.uima.internal.util.Misc; import org.apache.uima.internal.util.PositiveIntSet; import org.apache.uima.internal.util.PositiveIntSet_impl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.AnnotationBase; import org.apache.uima.jcas.cas.BooleanArray; import org.apache.uima.jcas.cas.ByteArray; import org.apache.uima.jcas.cas.DoubleArray; import org.apache.uima.jcas.cas.EmptyFSList; import org.apache.uima.jcas.cas.EmptyFloatList; import org.apache.uima.jcas.cas.EmptyIntegerList; import org.apache.uima.jcas.cas.EmptyList; import org.apache.uima.jcas.cas.EmptyStringList; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.FloatArray; import org.apache.uima.jcas.cas.IntegerArray; import org.apache.uima.jcas.cas.LongArray; import org.apache.uima.jcas.cas.ShortArray; import org.apache.uima.jcas.cas.Sofa; import org.apache.uima.jcas.cas.StringArray; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.impl.JCasHashMap; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.util.Level; /** * Implements the CAS interfaces. This class must be public because we need to * be able to create instance of it from outside the package. Use at your own * risk. May change without notice. * */ public class CASImpl extends AbstractCas_ImplBase implements CAS, CASMgr, LowLevelCAS, TypeSystemConstants { public static final boolean IS_USE_V2_IDS = false; // if false, ids increment by 1 private static final boolean trace = false; // debug public static final boolean traceFSs = false; // debug - trace FS creation and update public static final boolean traceCow = false; // debug - trace copy on write actions, index adds / deletes private static final String traceFile = "traceFSs.log.txt"; private static final PrintStream traceOut; static { try { if (traceFSs) { System.out.println("Creating traceFSs file in directory " + System.getProperty("user.dir")); traceOut = traceFSs ? new PrintStream(new BufferedOutputStream(new FileOutputStream(traceFile, false))) : null; } else { traceOut = null; } } catch (Exception e) { throw new RuntimeException(e); } } private static final boolean MEASURE_SETINT = false; // debug static final AtomicInteger casIdProvider = new AtomicInteger(0); // Notes on the implementation // --------------------------- // Floats are handled by casting them to ints when they are stored // in the heap. Conveniently, 0 casts to 0.0f, which is the default // value. public static final int NULL = 0; // Boolean scalar values are stored as ints in the fs heap. // TRUE is 1 and false is 0. public static final int TRUE = 1; public static final int FALSE = 0; public static final int DEFAULT_INITIAL_HEAP_SIZE = 500_000; public static final int DEFAULT_RESET_HEAP_SIZE = 5_000_000; /** * The UIMA framework detects (unless disabled, for high performance) updates to indexed FS which update * key values used as keys in indexes. Normally the framework will protect against index corruption by * temporarily removing the FS from the indexes, then do the update to the feature value, and then addback * the changed FS. * <p> * Users can use the protectIndexes() methods to explicitly control this remove - add back cycle, for instance * to "batch" together several updates to multiple features in a FS. * <p> * Some build processes may want to FAIL if any unprotected updates of this kind occur, instead of having the * framework silently recover them. This is enabled by having the framework throw an exception; this is controlled * by this global JVM property, which, if defined, causes the framework to throw an exception rather than recover. * */ public static final String THROW_EXCEPTION_FS_UPDATES_CORRUPTS = "uima.exception_when_fs_update_corrupts_index"; // public for test case use public static boolean IS_THROW_EXCEPTION_CORRUPT_INDEX = Misc.getNoValueSystemProperty(THROW_EXCEPTION_FS_UPDATES_CORRUPTS); /** * Define this JVM property to enable checking for invalid updates to features which are used as * keys by any index. * <ul> * <li>The following are the same: -Duima.check_invalid_fs_updates and -Duima.check_invalid_fs_updates=true</li> * </ul> */ public static final String REPORT_FS_UPDATES_CORRUPTS = "uima.report_fs_update_corrupts_index"; private static final boolean IS_REPORT_FS_UPDATE_CORRUPTS_INDEX = IS_THROW_EXCEPTION_CORRUPT_INDEX || Misc.getNoValueSystemProperty(REPORT_FS_UPDATES_CORRUPTS); /** * Set this JVM property to false for high performance, (no checking); * insure you don't have the report flag (above) turned on - otherwise it will force this to "true". */ public static final String DISABLE_PROTECT_INDEXES = "uima.disable_auto_protect_indexes"; /** * the protect indexes flag is on by default, but may be turned of via setting the property. * * This is overridden if a report is requested or the exception detection is on. */ private static final boolean IS_DISABLED_PROTECT_INDEXES = Misc.getNoValueSystemProperty(DISABLE_PROTECT_INDEXES) && !IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && !IS_THROW_EXCEPTION_CORRUPT_INDEX; public static final String ALWAYS_HOLD_ONTO_FSS = "uima.enable_id_to_feature_structure_map_for_all_fss"; static final boolean IS_ALWAYS_HOLD_ONTO_FSS = // debug Misc.getNoValueSystemProperty(ALWAYS_HOLD_ONTO_FSS); // private static final int REF_DATA_FOR_ALLOC_SIZE = 1024; // private static final int INT_DATA_FOR_ALLOC_SIZE = 1024; // // this next seemingly non-sensical static block // is to force the classes needed by Eclipse debugging to load // otherwise, you get a com.sun.jdi.ClassNotLoadedException when // the class is used as part of formatting debugging messages static { new DebugNameValuePair(null, null); new DebugFSLogicalStructure(); } // Static classes representing shared instance data // - shared data is computed once for all views /** * Journaling changes for computing delta cas. * Each instance represents one or more changes for one feature structure * A particular Feature Structure may have multiple FsChange instances * but we attempt to minimize this */ public static class FsChange { /** ref to the FS being modified */ final TOP fs; /** * which feature (by offset) is modified */ final BitSet featuresModified; final PositiveIntSet arrayUpdates; FsChange(TOP fs) { this.fs = fs; TypeImpl ti = fs._getTypeImpl(); featuresModified = (ti.highestOffset == -1) ? null : new BitSet(ti.highestOffset + 1); arrayUpdates = (ti.isArray()) ? new PositiveIntSet_impl() : null; } void addFeatData(int v) { featuresModified.set(v); } void addArrayData(int v, int nbrOfConsecutive) { for (int i = 0; i < nbrOfConsecutive; i++) { arrayUpdates.add(v++); } } void addArrayData(PositiveIntSet indexesPlus1) { indexesPlus1.forAllInts(i -> arrayUpdates.add(i - 1)); } @Override public int hashCode() { return 31 + ((fs == null) ? 0 : fs._id); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FsChange)) return false; return ((FsChange)obj).fs._id == fs._id; } } // fields shared among all CASes belong to views of a common base CAS static class SharedViewData { /** * map from FS ids to FSs. */ final private Id2FS id2fs; /** set to > 0 to reuse an id, 0 otherwise */ private int reuseId = 0; // Base CAS for all views final private CASImpl baseCAS; /** * These fields are here, not in TypeSystemImpl, because different CASes may have different indexes but share the same type system * They hold the same data (constant per CAS) but are accessed with different indexes */ private final BitSet featureCodesInIndexKeys = new BitSet(1024); // 128 bytes // private final BitSet featureJiInIndexKeys = new BitSet(1024); // indexed by JCas Feature Index, not feature code. // A map from SofaNumbers which are also view numbers to IndexRepositories. // these numbers are dense, and start with 1. 1 is the initial view. 0 is the base cas ArrayList<FSIndexRepositoryImpl> sofa2indexMap; /** * A map from Sofa numbers to CAS views. * number 0 - not used * number 1 - used for view named "_InitialView" * number 2-n used for other views * * Note: this is not reset with "Cas Reset" because views (really, their associated index repos) * take a lot of setup for the indexes. * However, the maximum view count is reset; so creation of new views "reuses" these pre-setup indexRepos * associated with these views. */ ArrayList<CASImpl> sofaNbr2ViewMap; /** * a set of instantiated sofaNames */ private Set<String> sofaNameSet; // Flag that initial Sofa has been created private boolean initialSofaCreated = false; // Count of Views created in this cas // equals count of sofas except if initial view has no sofa. int viewCount; // The ClassLoader that should be used by the JCas to load the generated // FS cover classes for this CAS. Defaults to the ClassLoader used // to load the CASImpl class. private ClassLoader jcasClassLoader = this.getClass().getClassLoader(); /***************************** * PEAR Support *****************************/ /** * Only support one level of PEAR nesting; for more general approach, make this a deque */ private ClassLoader previousJCasClassLoader = null; /** * Save area for suspending this while we create a base instance */ private ClassLoader suspendPreviousJCasClassLoader; /** * A map from IDs to already created trampoline FSs for the base FS with that id. * These are used when in a Pear and retrieving a FS (via index or deref) and you want the * Pear version for that ID. * There are potentially multiple maps - one per PEAR Classpath */ private JCasHashMap id2tramp = null; /** * a map from IDs of FSs that have a Pear version, to the base (non-Pear) version * used to locate the base version for adding to indexes */ private JCasHashMap id2base = null; private final Map<ClassLoader, JCasHashMap> cl2id2tramp = new IdentityHashMap<>(); /** * The current (active, switches at Pear boundaries) FsGenerators (excluding array-generators) * key = type code * read-only, unsynchronized for this CAS * Cache for setting this kept in TypeSystemImpl, by classloader * - shared among all CASs that use that Type System and class loader * -- in turn, initialized from FSClassRegistry, once per classloader / typesystem combo * * Pear generators are mostly null except for instances where the PEAR has redefined * the JCas cover class */ private FsGenerator3[] generators; /** * When generating a new instance of a FS in a PEAR where there's an alternate JCas class impl, * generate the base version, and make the alternate a trampoline to it. * Note: in future, if it is known that this FS is never used outside of this PEAR, then can * skip generating the double version */ private FsGenerator3[] baseGenerators; // If this CAS can be flushed (reset) or not. // often, the framework disables this before calling users code private boolean flushEnabled = true; // not final because set with reinit deserialization private TypeSystemImpl tsi; private ComponentInfo componentInfo; /** * This tracks the changes for delta cas * May also in the future support Journaling by component, * allowing determination of which component in a flow * created/updated a FeatureStructure (not implmented) * * TrackingMarkers are held on to by things outside of the * Cas, to support switching from one tracking marker to * another (currently not used, but designed to support * Component Journaling). * * We track changes on a granularity of features * and for features which are arrays, which element of the array * (This last to enable efficient delta serializations of * giant arrays of things, where you've only updated a few items) * * The FsChange doesn't store the changed data, only stores the * ref info needed to get to what was changed. */ private MarkerImpl trackingMark; /** * Track modified preexistingFSs * Note this is a map, keyed by the FS, so all changes are merged when added */ private Map<TOP, FsChange> modifiedPreexistingFSs; /** * This list currently only contains at most 1 element. * If Journaling is implemented, it may contain an * element per component being journaled. */ private List<MarkerImpl> trackingMarkList; /** * This stack corresponds to nested protectIndexes contexts. Normally should be very shallow. */ private final ArrayList<FSsTobeAddedback> fssTobeAddedback = new ArrayList<FSsTobeAddedback>(); /** * This version is for single fs use, by binary deserializers and by automatic mode * Only one user at a time is allowed. */ private final FSsTobeAddedbackSingle fsTobeAddedbackSingle = (FSsTobeAddedbackSingle) FSsTobeAddedback.createSingle(); /** * Set to true while this is in use. */ boolean fsTobeAddedbackSingleInUse = false; /** * temporarily set to true by deserialization routines doing their own management of this check */ boolean disableAutoCorruptionCheck = false; // used to generate FSIDs, increments by 1 for each use. First id == 1 /** * The fsId of the last created FS * used to generate FSIDs, increments by 1 for each use. First id == 1 */ private int fsIdGenerator = 0; /** * The version 2 size on the main heap of the last created FS */ private int lastFsV2Size = 1; /** * used to "capture" the fsIdGenerator value for a read-only CAS to be visible in * other threads */ AtomicInteger fsIdLastValue = new AtomicInteger(0); // mostly for debug - counts # times cas is reset private final AtomicInteger casResets = new AtomicInteger(0); // unique ID for a created CAS view, not updated if CAS is reset and reused private final int casId = casIdProvider.incrementAndGet(); // shared singltons, created at type system commit private EmptyFSList emptyFSList; private EmptyFloatList emptyFloatList; private EmptyIntegerList emptyIntegerList; private EmptyStringList emptyStringList; /** * Created at startup time, lives as long as the CAS lives * Serves to reference code for binary cas ser/des that used to live * in this class, but was moved out */ private final BinaryCasSerDes bcsd; /** * Created when doing binary or form4 non-delta (de)serialization, used in subsequent delta ser/deserialization * Created when doing binary or form4 non-delta ser/deserialization, used in subsequent delta (de)serialization * Reset with CasReset or deltaMergesComplete API call */ private CommonSerDesSequential csds; /************************************************* * VERSION 2 LOW_LEVEL_API COMPATIBILITY SUPPORT * *************************************************/ /** * A StringSet used only to support ll_get/setInt api * get adds string to this and returns the int handle * set retrieves the string, given the handle * lazy initialized */ private StringSet llstringSet = null; /** * A LongSet used only to support v2 ll_get/setInt api * get adds long to this and returns the int handle * set retrieves the long, given the handle * lazy initialized */ private LongSet lllongSet = null; // For tracing FS creation and updating, normally disabled private final StringBuilder traceFScreationSb = traceFSs ? new StringBuilder() : null; private final StringBuilder traceCowSb = traceCow ? new StringBuilder() : null; private int traceFSid = 0; private boolean traceFSisCreate; private final IntVector id2addr = traceFSs ? new IntVector() : null; private int nextId2Addr = 1; // only for tracing, to convert id's to v2 addresses final private int initialHeapSize; private SharedViewData(CASImpl baseCAS, int initialHeapSize, TypeSystemImpl tsi) { this.baseCAS = baseCAS; this.tsi = tsi; this.initialHeapSize = initialHeapSize; bcsd = new BinaryCasSerDes(baseCAS); id2fs = new Id2FS(initialHeapSize); if (traceFSs) id2addr.add(0); } void clearCasReset() { // fss fsIdGenerator = 0; id2fs.clear(); // pear caches id2tramp = null; id2base = null; for (JCasHashMap m : cl2id2tramp.values()) { m.clear(); } // index corruption avoidance fssTobeAddedback.clear(); fsTobeAddedbackSingle.clear(); fsTobeAddedbackSingleInUse = false; disableAutoCorruptionCheck = false; // misc flushEnabled = true; componentInfo = null; bcsd.clear(); csds = null; llstringSet = null; traceFSid = 0; if (traceFSs) { traceFScreationSb.setLength(0); id2addr.removeAllElements(); id2addr.add(0); nextId2Addr = 1; } } /** * called by resetNoQuestions and cas complete reinit */ void clearSofaInfo() { sofaNameSet.clear(); initialSofaCreated = false; } /** * Called from CasComplete deserialization (reinit). * * Skips the resetNoQuestions operation of flushing the indexes, * since these will be reinitialized with potentially new definitions. * * Clears additional data related to having the * - type system potentially change * - the features belonging to indexes change * */ void clear() { clearCasReset(); clearTrackingMarks(); // type system + index spec tsi = null; featureCodesInIndexKeys.clear(); // featureJiInIndexKeys.clear(); emptyFloatList = null; // these cleared in case new ts redefines? emptyFSList = null; emptyIntegerList = null; emptyStringList = null; clearSofaInfo(); /** * Clear the existing views, except keep the info for the initial view * so that the cas complete deserialization after setting up the new index repository in the base cas * can "refresh" the existing initial view (if present; if not present, a new one is created). */ if (sofaNbr2ViewMap.size() >= 1) { // have initial view - preserve it CASImpl localInitialView = sofaNbr2ViewMap.get(1); sofaNbr2ViewMap.clear(); Misc.setWithExpand(sofaNbr2ViewMap, 1, localInitialView); viewCount = 1; } else { sofaNbr2ViewMap.clear(); viewCount = 0; } } private void clearTrackingMarks() { // resets all markers that might be held by things outside the Cas // Currently (2009) this list has a max of 1 element // Future impl may have one element per component for component Journaling if (trackingMarkList != null) { for (int i=0; i < trackingMarkList.size(); i++) { trackingMarkList.get(i).isValid = false; } } trackingMark = null; if (null != modifiedPreexistingFSs) { modifiedPreexistingFSs.clear(); } trackingMarkList = null; } void switchClassLoader(ClassLoader newClassLoader) { if (null == newClassLoader) { // is null if no cl set return; } if (newClassLoader != jcasClassLoader) { if (null != previousJCasClassLoader) { /** Multiply nested classloaders not supported. Original base loader: {0}, current nested loader: {1}, trying to switch to loader: {2}.*/ throw new CASRuntimeException(CASRuntimeException.SWITCH_CLASS_LOADER_NESTED, previousJCasClassLoader, jcasClassLoader, newClassLoader); } // System.out.println("Switching to new class loader"); previousJCasClassLoader = jcasClassLoader; jcasClassLoader = newClassLoader; generators = tsi.getGeneratorsForClassLoader(newClassLoader, true); // true - isPear assert null == id2tramp; // is null outside of a pear id2tramp = cl2id2tramp.get(newClassLoader); if (null == id2tramp) { cl2id2tramp.put(newClassLoader, id2tramp = new JCasHashMap(32)); } if (id2base == null) { id2base = new JCasHashMap(32); } } } void restoreClassLoader() { if (null == previousJCasClassLoader) { return; } // System.out.println("Switching back to previous class loader"); jcasClassLoader = previousJCasClassLoader; previousJCasClassLoader = null; generators = baseGenerators; id2tramp = null; } private int getNextFsId(TOP fs) { if (reuseId != 0) { // l.setStrongRef(fs, reuseId); return reuseId; } // l.add(fs); // if (id2fs.size() != (2 + fsIdGenerator.get())) { // System.out.println("debug out of sync id generator and id2fs size"); // } // assert(l.size() == (2 + fsIdGenerator)); final int p = fsIdGenerator; final int r = fsIdGenerator += IS_USE_V2_IDS ? lastFsV2Size : 1; if (r < p) { throw new RuntimeException("UIMA Cas Internal id value overflowed maximum int value"); } if (IS_USE_V2_IDS) { // this computation is partial - misses length of arrays stored on heap // because that info not yet available lastFsV2Size = fs._getTypeImpl().getFsSpaceReq(); } return r; } } /***************************************************************** * Non-shared instance data kept per CAS view incl base CAS *****************************************************************/ // package protected to let other things share this info final SharedViewData svd; // shared view data /** The index repository. Referenced by XmiCasSerializer */ FSIndexRepositoryImpl indexRepository; // private Object[] currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // private Object[] returnRefDataForAlloc; // private int[] currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // private int[] returnIntDataForAlloc; // private int nextRefDataOffsetForAlloc = 0; // private int nextIntDataOffsetForAlloc = 0; /** * The Feature Structure for the sofa FS for this view, or * null * //-1 if the sofa FS is for the initial view, or * // 0 if there is no sofa FS - for instance, in the "base cas" */ private Sofa mySofaRef = null; /** the corresponding JCas object */ JCasImpl jcas = null; /** * Copies of frequently accessed data pulled up for * locality of reference - only an optimization * - each value needs to be reset appropriately * - getters check for null, and if null, do the get. */ private TypeSystemImpl tsi_local; /** * for Pear generation - set this to the base FS * not in SharedViewData to reduce object traversal when * generating FSs */ FeatureStructureImplC pearBaseFs = null; // private StackTraceElement[] addbackSingleTrace = null; // for debug use only, normally commented out // CASImpl(TypeSystemImpl typeSystem) { // this(typeSystem, DEFAULT_INITIAL_HEAP_SIZE); // } // // Reference existing CAS // // For use when creating views of the CAS // CASImpl(CAS cas) { // this.setCAS(cas); // this.useFSCache = false; // initTypeVariables(); // } /* * Configure a new (base view) CASImpl, **not a new view** typeSystem can be * null, in which case a new instance of TypeSystemImpl is set up, but not * committed. If typeSystem is not null, it is committed (locked). ** Note: it * is assumed that the caller of this will always set up the initial view ** * by calling */ public CASImpl(TypeSystemImpl typeSystem, int initialHeapSize ) { super(); TypeSystemImpl ts; final boolean externalTypeSystem = (typeSystem != null); if (externalTypeSystem) { ts = typeSystem; } else { ts = (TypeSystemImpl) CASFactory.createTypeSystem(); // creates also new CASMetadata and // FSClassRegistry instances } this.svd = new SharedViewData(this, initialHeapSize, ts); // this.svd.baseCAS = this; // this.svd.heap = new Heap(initialHeapSize); if (externalTypeSystem) { commitTypeSystem(); } this.svd.sofa2indexMap = new ArrayList<>(); this.svd.sofaNbr2ViewMap = new ArrayList<>(); this.svd.sofaNameSet = new HashSet<String>(); this.svd.initialSofaCreated = false; this.svd.viewCount = 0; this.svd.clearTrackingMarks(); } public CASImpl() { this((TypeSystemImpl) null, DEFAULT_INITIAL_HEAP_SIZE); } // In May 2007, appears to have 1 caller, createCASMgr in Serialization class, // could have out-side the framework callers because it is public. public CASImpl(CASMgrSerializer ser) { this(ser.getTypeSystem(), DEFAULT_INITIAL_HEAP_SIZE); checkInternalCodes(ser); // assert(ts != null); // assert(getTypeSystem() != null); this.indexRepository = ser.getIndexRepository(this); } // Use this when creating a CAS view CASImpl(CASImpl cas, SofaFS aSofa) { // these next fields are final and must be set in the constructor this.svd = cas.svd; this.mySofaRef = (Sofa) aSofa; // get the indexRepository for this Sofa this.indexRepository = (this.mySofaRef == null) ? (FSIndexRepositoryImpl) cas.getSofaIndexRepository(1) : (FSIndexRepositoryImpl) cas.getSofaIndexRepository(aSofa); if (null == this.indexRepository) { // create the indexRepository for this CAS // use the baseIR to create a lightweight IR copy FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) cas.getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this, baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { cas.setSofaIndexRepository(1, this.indexRepository); } else { cas.setSofaIndexRepository(aSofa, this.indexRepository); } } } // Use this when creating a CAS view void refreshView(CAS cas, SofaFS aSofa) { if (aSofa != null) { // save address of SofaFS this.mySofaRef = (Sofa) aSofa; } else { // this is the InitialView this.mySofaRef = null; } // toss the JCas, if it exists this.jcas = null; // create the indexRepository for this Sofa final FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) ((CASImpl) cas).getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this,baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { ((CASImpl) cas).setSofaIndexRepository(1, this.indexRepository); } else { ((CASImpl) cas).setSofaIndexRepository(aSofa, this.indexRepository); } } private void checkInternalCodes(CASMgrSerializer ser) throws CASAdminException { if ((ser.topTypeCode > 0) && (ser.topTypeCode != topTypeCode)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } if (ser.featureOffsets == null) { return; } // if (ser.featureOffsets.length != this.svd.casMetadata.featureOffset.length) { // throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); // } TypeSystemImpl tsi = getTypeSystemImpl(); for (int i = 1; i < ser.featureOffsets.length; i++) { FeatureImpl fi = tsi.getFeatureForCode_checked(i); int adjOffset = fi.isInInt ? 0 : fi.getRangeImpl().nbrOfUsedIntDataSlots; if (ser.featureOffsets[i] != (fi.getOffset() + adjOffset)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } } } // ---------------------------------------- // accessors for data in SharedViewData // ---------------------------------------- void addSofaViewName(String id) { svd.sofaNameSet.add(id); } void setViewCount(int n) { svd.viewCount = n; } void addbackSingle(TOP fs) { if (!svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } void addbackSingleIfWasRemoved(boolean wasRemoved, TOP fs) { if (wasRemoved) { addbackSingle(fs); } svd.fsTobeAddedbackSingleInUse = false; } private FSsTobeAddedback getAddback(int size) { if (svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } return svd.fssTobeAddedback.get(size - 1); } FSsTobeAddedbackSingle getAddbackSingle() { if (svd.fsTobeAddedbackSingleInUse) { // System.out.println(Misc.dumpCallers(addbackSingleTrace, 2, 100)); Misc.internalError(); } // addbackSingleTrace = Thread.currentThread().getStackTrace(); svd.fsTobeAddedbackSingleInUse = true; svd.fsTobeAddedbackSingle.clear(); // safety return svd.fsTobeAddedbackSingle; } void featureCodes_inIndexKeysAdd(int featCode/*, int registryIndex*/) { svd.featureCodesInIndexKeys.set(featCode); // skip adding if no JCas registry entry for this feature // if (registryIndex >= 0) { // svd.featureJiInIndexKeys.set(registryIndex); // } } @Override public void enableReset(boolean flag) { this.svd.flushEnabled = flag; } @Override public TypeSystem getTypeSystem() { return getTypeSystemImpl(); } public TypeSystemImpl getTypeSystemImpl() { if (tsi_local == null) { tsi_local = this.svd.tsi; } return this.tsi_local; } /** * Set the shared svd type system ref, in all views * @param ts */ void installTypeSystemInAllViews(TypeSystemImpl ts) { this.svd.tsi = ts; final List<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (sn2v.size() > 0) { for (CASImpl view : sn2v.subList(1, sn2v.size())) { view.tsi_local = ts; } } this.getBaseCAS().tsi_local = ts; } @Override public ConstraintFactory getConstraintFactory() { return ConstraintFactory.instance(); } /** * Create the appropriate Feature Structure Java instance * - from whatever the generator for this type specifies. * * @param type the type to create * @return a Java object representing the FeatureStructure impl in Java. */ @Override public <T extends FeatureStructure> T createFS(Type type) { final TypeImpl ti = (TypeImpl) type; if (!ti.isCreatableAndNotBuiltinArray()) { throw new CASRuntimeException(CASRuntimeException.NON_CREATABLE_TYPE, type.getName(), "CAS.createFS()"); } return (T) createFSAnnotCheck(ti); } private <T extends FeatureStructureImplC> T createFSAnnotCheck(TypeImpl ti) { if (ti.isAnnotationBaseType()) { // not here, will be checked later in AnnotationBase constructor // if (this.isBaseCas()) { // throw new CASRuntimeException(CASRuntimeException.DISALLOW_CREATE_ANNOTATION_IN_BASE_CAS, ti.getName()); // } getSofaRef(); // materialize this if not present; required for setting the sofa ref // must happen before the annotation is created, for compressed form 6 serialization order // to insure sofa precedes the ref of it } FsGenerator3 g = svd.generators[ti.getCode()]; // get generator or null return (g != null) ? (T) g.createFS(ti, this) // pear case, with no overriding pear - use base : (T) createFsFromGenerator(svd.baseGenerators, ti); // // // // not pear or no special cover class for this // // // TOP fs = createFsFromGenerator(svd.baseGenerators, ti); // // FsGenerator g = svd.generators[ti.getCode()]; // get pear generator or null // return (g != null) // ? (T) pearConvert(fs, g) // : (T) fs; // } // // return (T) createFsFromGenerator(svd.generators, ti); } /** * Called during construction of FS. * For normal FS "new" operators, if in PEAR context, make the base version * @param fs * @param ti * @return true if made a base for a trampoline */ boolean maybeMakeBaseVersionForPear(FeatureStructureImplC fs, TypeImpl ti) { if (!inPearContext()) return false; FsGenerator3 g = svd.generators[ti.getCode()]; // get pear generator or null if (g == null) return false; TOP baseFs; try { suspendPearContext(); svd.reuseId = fs._id; baseFs = createFsFromGenerator(svd.baseGenerators, ti); } finally { restorePearContext(); svd.reuseId = 0; } svd.id2base.put(baseFs); pearBaseFs = baseFs; return true; } private TOP createFsFromGenerator(FsGenerator3[] gs, TypeImpl ti) { // if (ti == null || gs == null || gs[ti.getCode()] == null) { // System.out.println("debug"); // } return gs[ti.getCode()].createFS(ti, this); } // public int ll_createFSAnnotCheck(int typeCode) { // TOP fs = createFSAnnotCheck(getTypeFromCode(typeCode)); // svd.id2fs.put(fs); // required for low level, in order to "hold onto" / prevent GC of FS // return fs._id; // } public TOP createArray(TypeImpl array_type, int arrayLength) { TypeImpl_array tia = (TypeImpl_array) array_type; TypeImpl componentType = tia.getComponentType(); if (componentType.isPrimitive()) { checkArrayPreconditions(arrayLength); switch (componentType.getCode()) { case intTypeCode: return new IntegerArray(array_type, this, arrayLength); case floatTypeCode: return new FloatArray(array_type, this, arrayLength); case booleanTypeCode: return new BooleanArray(array_type, this, arrayLength); case byteTypeCode: return new ByteArray(array_type, this, arrayLength); case shortTypeCode: return new ShortArray(array_type, this, arrayLength); case longTypeCode: return new LongArray(array_type, this, arrayLength); case doubleTypeCode: return new DoubleArray(array_type, this, arrayLength); case stringTypeCode: return new StringArray(array_type, this, arrayLength); // case javaObjectTypeCode: return new JavaObjectArray(array_type, this, arrayLength); default: Misc.internalError(); } // return tia.getGeneratorArray().createFS(type, this, arrayLength); // return (((FsGeneratorArray)getFsGenerator(type.getCode())).createFS(type, this, arrayLength)); } return (TOP) createArrayFS(array_type, arrayLength); } @Override public ArrayFS createArrayFS(int length) { return createArrayFS(getTypeSystemImpl().fsArrayType, length); } private ArrayFS createArrayFS(TypeImpl type, int length) { checkArrayPreconditions(length); return new FSArray(type, this, length); // getTypeSystemImpl().fsArrayType.getGeneratorArray() // (((FsGeneratorArray)getFsGenerator(fsArrayTypeCode)) // .createFS(type, this, length); } @Override public IntArrayFS createIntArrayFS(int length) { checkArrayPreconditions(length); return new IntegerArray(getTypeSystemImpl().intArrayType, this, length); } @Override public FloatArrayFS createFloatArrayFS(int length) { checkArrayPreconditions(length); return new FloatArray(getTypeSystemImpl().floatArrayType, this, length); } @Override public StringArrayFS createStringArrayFS(int length) { checkArrayPreconditions(length); return new StringArray(getTypeSystemImpl().stringArrayType, this, length); } // public JavaObjectArray createJavaObjectArrayFS(int length) { // checkArrayPreconditions(length); // return new JavaObjectArray(getTypeSystemImpl().javaObjectArrayType, this, length); // } // return true if only one sofa and it is the default text sofa public boolean isBackwardCompatibleCas() { // check that there is exactly one sofa if (this.svd.viewCount != 1) { return false; } if (!this.svd.initialSofaCreated) { return false; } Sofa sofa = this.getInitialView().getSofa(); // check for mime type exactly equal to "text" String sofaMime = sofa.getMimeType(); if (!"text".equals(sofaMime)) { return false; } // check that sofaURI and sofaArray are not set String sofaUri = sofa.getSofaURI(); if (sofaUri != null) { return false; } TOP sofaArray = sofa.getSofaArray(); if (sofaArray != null) { return false; } // check that name is NAME_DEFAULT_SOFA String sofaname = sofa.getSofaID(); return NAME_DEFAULT_SOFA.equals(sofaname); } int getViewCount() { return this.svd.viewCount; } FSIndexRepository getSofaIndexRepository(SofaFS aSofa) { return getSofaIndexRepository(aSofa.getSofaRef()); } FSIndexRepositoryImpl getSofaIndexRepository(int aSofaRef) { if (aSofaRef >= this.svd.sofa2indexMap.size()) { return null; } return this.svd.sofa2indexMap.get(aSofaRef); } void setSofaIndexRepository(SofaFS aSofa, FSIndexRepositoryImpl indxRepos) { setSofaIndexRepository(aSofa.getSofaRef(), indxRepos); } void setSofaIndexRepository(int aSofaRef, FSIndexRepositoryImpl indxRepos) { Misc.setWithExpand(this.svd.sofa2indexMap, aSofaRef, indxRepos); } /** * @deprecated */ @Override @Deprecated public SofaFS createSofa(SofaID sofaID, String mimeType) { // extract absolute SofaName string from the ID SofaFS aSofa = createSofa(sofaID.getSofaID(), mimeType); getView(aSofa); // will create the view, needed to make the // resetNoQuestions and other things that // iterate over views work. return aSofa; } Sofa createSofa(String sofaName, String mimeType) { return createSofa(++this.svd.viewCount, sofaName, mimeType); } Sofa createSofa(int sofaNum, String sofaName, String mimeType) { if (this.svd.sofaNameSet.contains(sofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, sofaName); } final boolean viewAlreadyExists = sofaNum == this.svd.viewCount; if (!viewAlreadyExists) { if (sofaNum == 1) { // skip the test for sofaNum == 1 - this can be set "later" if (this.svd.viewCount == 0) { this.svd.viewCount = 1; } // else it is == or higher, so don't reset it down } else { // sofa is not initial sofa - is guaranteed to be set when view created // if (sofaNum != this.svd.viewCount + 1) { // System.out.println("debug"); // } assert (sofaNum == this.svd.viewCount + 1); this.svd.viewCount = sofaNum; } } Sofa sofa = new Sofa( getTypeSystemImpl().sofaType, this.getBaseCAS(), // view for a sofa is the base cas to correspond to where it gets indexed sofaNum, sofaName, mimeType); this.getBaseIndexRepository().addFS(sofa); this.svd.sofaNameSet.add(sofaName); if (!viewAlreadyExists) { getView(sofa); // create the view that goes with this Sofa } return sofa; } Sofa createInitialSofa(String mimeType) { Sofa sofa = createSofa(1, CAS.NAME_DEFAULT_SOFA, mimeType); registerInitialSofa(); this.mySofaRef = sofa; return sofa; } void registerInitialSofa() { this.svd.initialSofaCreated = true; } boolean isInitialSofaCreated() { return this.svd.initialSofaCreated; } /** * @deprecated */ @Override @Deprecated public SofaFS getSofa(SofaID sofaID) { // extract absolute SofaName string from the ID return getSofa(sofaID.getSofaID()); } private SofaFS getSofa(String sofaName) { FSIterator<Sofa> iterator = this.svd.baseCAS.getSofaIterator(); while (iterator.hasNext()) { SofaFS sofa = iterator.next(); if (sofaName.equals(sofa.getSofaID())) { return sofa; } } throw new CASRuntimeException(CASRuntimeException.SOFANAME_NOT_FOUND, sofaName); } SofaFS getSofa(int sofaRef) { SofaFS aSofa = (SofaFS) this.ll_getFSForRef(sofaRef); if (aSofa == null) { CASRuntimeException e = new CASRuntimeException(CASRuntimeException.SOFAREF_NOT_FOUND); throw e; } return aSofa; } public int ll_getSofaNum(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaNum(); } public String ll_getSofaID(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaID(); } public String ll_getSofaDataString(int sofaAddr) { return ((Sofa)getFsFromId_checked(sofaAddr)).getSofaString(); } public CASImpl getBaseCAS() { return this.svd.baseCAS; } @Override public <T extends SofaFS> FSIterator<T> getSofaIterator() { FSIndex<T> sofaIndex = this.svd.baseCAS.indexRepository.<T>getIndex(CAS.SOFA_INDEX_NAME); return sofaIndex.iterator(); } // For internal use only public Sofa getSofaRef() { if (this.mySofaRef == null) { // create the SofaFS for _InitialView ... // ... and reset mySofaRef to point to it this.mySofaRef = this.createInitialSofa(null); } return this.mySofaRef; } // For internal use only public InputStream getSofaDataStream(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; String sd = sofa.getLocalStringData(); if (null != sd) { ByteArrayInputStream bis; try { bis = new ByteArrayInputStream(sd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } return bis; } else if (null != aSofa.getLocalFSData()) { TOP fs = (TOP) sofa.getLocalFSData(); ByteBuffer buf = null; switch(fs._getTypeCode()) { case stringArrayTypeCode: { StringBuilder sb = new StringBuilder(); final String[] theArray = ((StringArray) fs)._getTheArray(); for (int i = 0; i < theArray.length; i++) { if (i != 0) { sb.append('\n'); } sb.append(theArray[i]); } try { return new ByteArrayInputStream(sb.toString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } } case intArrayTypeCode: { final int[] theArray = ((IntegerArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asIntBuffer().put(theArray, 0, theArray.length); break; } case floatArrayTypeCode: { final float[] theArray = ((FloatArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asFloatBuffer().put(theArray, 0, theArray.length); break; } case byteArrayTypeCode: { final byte[] theArray = ((ByteArray) fs)._getTheArray(); buf = ByteBuffer.wrap(theArray); break; } case shortArrayTypeCode: { final short[] theArray = ((ShortArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 2)).asShortBuffer().put(theArray, 0, theArray.length); break; } case longArrayTypeCode: { final long[] theArray = ((LongArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asLongBuffer().put(theArray, 0, theArray.length); break; } case doubleArrayTypeCode: { final double[] theArray = ((DoubleArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asDoubleBuffer().put(theArray, 0, theArray.length); break; } default: Misc.internalError(); } ByteArrayInputStream bis = new ByteArrayInputStream(buf.array()); return bis; } else if (null != aSofa.getSofaURI()) { URL url; try { url = new URL(aSofa.getSofaURI()); return url.openStream(); } catch (IOException exc) { throw new CASRuntimeException(CASRuntimeException.SOFADATASTREAM_ERROR, exc.getMessage()); } } return null; } @Override public<T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons) { return new FilteredIterator<T>(it, cons); } public TypeSystemImpl commitTypeSystem() { TypeSystemImpl ts = getTypeSystemImpl(); // For CAS pools, the type system could have already been committed // Skip the initFSClassReg if so, because it may have been updated to a JCas // version by another CAS processing in the pool // @see org.apache.uima.cas.impl.FSClassRegistry // avoid race: two instances of a CAS from a pool attempting to commit the // ts // at the same time final ClassLoader cl = getJCasClassLoader(); synchronized (ts) { if (!ts.isCommitted()) { TypeSystemImpl tsc = ts.commit(getJCasClassLoader()); if (tsc != ts) { installTypeSystemInAllViews(tsc); ts = tsc; } } } svd.baseGenerators = svd.generators = ts.getGeneratorsForClassLoader(cl, false); // false - not PEAR createIndexRepository(); return ts; } private void createIndexRepository() { if (!this.getTypeSystemMgr().isCommitted()) { throw new CASAdminException(CASAdminException.MUST_COMMIT_TYPE_SYSTEM); } if (this.indexRepository == null) { this.indexRepository = new FSIndexRepositoryImpl(this); } } @Override public FSIndexRepositoryMgr getIndexRepositoryMgr() { // assert(this.cas.getIndexRepository() != null); return this.indexRepository; } /** * @deprecated * @param fs - */ @Deprecated public void commitFS(FeatureStructure fs) { getIndexRepository().addFS(fs); } @Override public FeaturePath createFeaturePath() { return new FeaturePathImpl(); } // Implement the ConstraintFactory interface. /** * @see org.apache.uima.cas.admin.CASMgr#getTypeSystemMgr() */ @Override public TypeSystemMgr getTypeSystemMgr() { return getTypeSystemImpl(); } @Override public void reset() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } if (this == this.svd.baseCAS) { resetNoQuestions(); return; } // called from a CAS view. // clear CAS ... this.svd.baseCAS.resetNoQuestions(); } public void resetNoQuestions() { svd.casResets.incrementAndGet(); svd.clearCasReset(); if (trace) { System.out.println("CAS Reset in thread " + Thread.currentThread().getName() + " for CasId = " + getCasId() + ", new reset count = " + svd.casResets.get()); } int numViews = this.getViewCount(); // Flush indexRepository for all views for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getView(view)); if (tcas != null) { tcas.indexRepository.flush(); // mySofaRef = -1 is a flag in initial view that sofa has not been set. // For the initial view, it is possible to not have a sofa - it is set // "lazily" upon the first need. // all other views always have a sofa set. The sofaRef is set to 0, // but will be set to the actual sofa addr in the cas when the view is // initialized. tcas.mySofaRef = null; // was in v2: (1 == view) ? -1 : 0; } } this.svd.clearTrackingMarks(); // safety : in case this public method is called on other than the base cas this.getBaseCAS().indexRepository.flush(); // for base view, other views flushed above this.svd.clearSofaInfo(); // but keep initial view, and other views // because setting up the index infrastructure is expensive this.svd.viewCount = 1; // initial view svd.traceFSid = 0; if (traceFSs) svd.traceFScreationSb.setLength(0); this.svd.componentInfo = null; // https://issues.apache.org/jira/browse/UIMA-5097 } /** * @deprecated Use {@link #reset reset()}instead. */ @Override @Deprecated public void flush() { reset(); } @Override public FSIndexRepository getIndexRepository() { if (this == this.svd.baseCAS) { // BaseCas has no indexes for users return null; } if (this.indexRepository.isCommitted()) { return this.indexRepository; } return null; } FSIndexRepository getBaseIndexRepository() { if (this.svd.baseCAS.indexRepository.isCommitted()) { return this.svd.baseCAS.indexRepository; } return null; } FSIndexRepositoryImpl getBaseIndexRepositoryImpl() { return this.svd.baseCAS.indexRepository; } void addSofaFsToIndex(SofaFS sofa) { this.svd.baseCAS.getBaseIndexRepository().addFS(sofa); } void registerView(Sofa aSofa) { this.mySofaRef = aSofa; } /** * @see org.apache.uima.cas.CAS#fs2listIterator(FSIterator) */ @Override public <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it) { return new FSListIteratorImpl<T>(it); } /** * @see org.apache.uima.cas.admin.CASMgr#getCAS() */ @Override public CAS getCAS() { if (this.indexRepository.isCommitted()) { return this; } throw new CASAdminException(CASAdminException.MUST_COMMIT_INDEX_REPOSITORY); } // public void setFSClassRegistry(FSClassRegistry fsClassReg) { // this.svd.casMetadata.fsClassRegistry = fsClassReg; // } // JCasGen'd cover classes use this to add their generators to the class // registry // Note that this now (June 2007) a no-op for JCasGen'd generators // Also previously (but not now) used in JCas initialization to copy-down super generators to subtypes // as needed public FSClassRegistry getFSClassRegistry() { return null; // return getTypeSystemImpl().getFSClassRegistry(); } /** * @param fs the Feature Structure being updated * @param fi the Feature of fs being updated, or null if fs is an array * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, FeatureImpl fi, int arrayIndexStart, int nbrOfConsecutive) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); if (fi == null) { Misc.assertUie(arrayIndexStart >= 0); change.addArrayData(arrayIndexStart, nbrOfConsecutive); } else { change.addFeatData(fi.getOffset()); } } /** * @param fs the Feature Structure being updated * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, PositiveIntSet indexesPlus1) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); change.addArrayData(indexesPlus1); } private void logFSUpdate(TOP fs, FeatureImpl fi) { logFSUpdate(fs, fi, -1, -1); // indicate non-array call } /** * This is your link from the low-level API to the high-level API. Use this * method to create a FeatureStructure object from an address. Note that the * reverse is not supported by public APIs (i.e., there is currently no way to * get at the address of a FeatureStructure. Maybe we will need to change * that. * * The "create" in "createFS" is a misnomer - the FS must already be created. * * @param id The id of the feature structure to be created. * @param <T> The Java class associated with this feature structure * @return A FeatureStructure object. */ public <T extends TOP> T createFS(int id) { return getFsFromId_checked(id); } public int getArraySize(CommonArrayFS fs) { return fs.size(); } @Override public int ll_getArraySize(int id) { return getArraySize(getFsFromId_checked(id)); } final void setWithCheckAndJournal(TOP fs, FeatureImpl fi, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, fi.getCode()); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, fi); } final public void setWithCheckAndJournal(TOP fs, int featCode, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, featCode); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, featCode); } // public void setWithCheck(FeatureStructureImplC fs, FeatureImpl feat, Runnable setter) { // boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat); // setter.run(); // if (wasRemoved) { // maybeAddback(fs); // } // } /** * This method called by setters in JCas gen'd classes when * the setter must check for journaling * @param fs - * @param fi - * @param setter - */ public void setWithJournal(FeatureStructureImplC fs, FeatureImpl fi, Runnable setter) { setter.run(); maybeLogUpdate(fs, fi); } public boolean isLoggingNeeded(FeatureStructureImplC fs) { return this.svd.trackingMark != null && !this.svd.trackingMark.isNew(fs._id); } /** * @param fs the Feature Structure being updated * @param feat the feature of fs being updated, or null if fs is a primitive array * @param i the index being updated */ final public void maybeLogArrayUpdate(FeatureStructureImplC fs, FeatureImpl feat, int i) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat, i, 1); } } /** * @param fs the Feature Structure being updated * @param indexesPlus1 - a set of indexes (plus 1) that have been update */ final public void maybeLogArrayUpdates(FeatureStructureImplC fs, PositiveIntSet indexesPlus1) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, indexesPlus1); } } /** * @param fs a primitive array FS * @param startingIndex - * @param length number of consequtive items */ public void maybeLogArrayUpdates(FeatureStructureImplC fs, int startingIndex, int length) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, null, startingIndex, length); } } final public void maybeLogUpdate(FeatureStructureImplC fs, FeatureImpl feat) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat); } } final public void maybeLogUpdate(FeatureStructureImplC fs, int featCode) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP)fs, getFeatFromCode_checked(featCode)); } } final public boolean isLogging() { return this.svd.trackingMark != null; } // /** // * Common setter code for features in Feature Structures // * // * These come in two styles: one with int values, one with Object values // * Object values are FS or Strings or JavaObjects // */ // // /** // * low level setter // * // * @param fs the feature structure // * @param feat the feature to set // * @param value - // */ // // public void setFeatureValue(FeatureStructureImplC fs, FeatureImpl feat, int value) { // fs.setIntValue(feat, value); //// boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); //// fs._intData[feat.getAdjustedOffset()] = value; //// if (wasRemoved) { //// maybeAddback(fs); //// } //// maybeLogUpdate(fs, feat); // } /** * version for longs, uses two slots * Only called from FeatureStructureImplC after determining * there is no local field to use * Is here because of 3 calls to things in this class * @param fsIn the feature structure * @param feat the feature to set * @param v - */ public void setLongValue(FeatureStructureImplC fsIn, FeatureImpl feat, long v) { TOP fs = (TOP) fsIn; if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); fs._setLongValueNcNj(feat, v); if (wasRemoved) { maybeAddback(fs); } } else { fs._setLongValueNcNj(feat, v); } maybeLogUpdate(fs, feat); } void setFeatureValue(int fsRef, int featureCode, TOP value) { getFsFromId_checked(fsRef).setFeatureValue(getFeatFromCode_checked(featureCode), value); } /** * Supports setting slots to "0" for null values * @param fs The feature structure to update * @param feat the feature to update- * @param s the string representation of the value, could be null */ public void setFeatureValueFromString(FeatureStructureImplC fs, FeatureImpl feat, String s) { final TypeImpl range = feat.getRangeImpl(); if (fs instanceof Sofa) { // sofa has special setters Sofa sofa = (Sofa) fs; switch (feat.getCode()) { case sofaMimeFeatCode : sofa.setMimeType(s); break; case sofaStringFeatCode: sofa.setLocalSofaData(s); break; case sofaUriFeatCode: sofa.setRemoteSofaURI(s); break; default: // left empty - ignore trying to set final fields } return; } if (feat.isInInt) { switch (range.getCode()) { case floatTypeCode : fs.setFloatValue(feat, (s == null) ? 0F : Float.parseFloat(s)); break; case booleanTypeCode : fs.setBooleanValue(feat, (s == null) ? false : Boolean.parseBoolean(s)); break; case longTypeCode : fs.setLongValue(feat, (s == null) ? 0L : Long.parseLong(s)); break; case doubleTypeCode : fs.setDoubleValue(feat, (s == null) ? 0D : Double.parseDouble(s)); break; case byteTypeCode : fs.setByteValue(feat, (s == null) ? 0 : Byte.parseByte(s)); break; case shortTypeCode : fs.setShortValue(feat, (s == null) ? 0 : Short.parseShort(s)); break; case intTypeCode : fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); break; default: fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); } } else if (range.isRefType) { if (s == null) { fs.setFeatureValue(feat, null); } else { // Setting a reference value "{0}" from a string is not supported. throw new CASRuntimeException(CASRuntimeException.SET_REF_FROM_STRING_NOT_SUPPORTED, feat.getName()); } } else if (range.isStringOrStringSubtype()) { // includes TypeImplSubString // is String or Substring fs.setStringValue(feat, (s == null) ? null : s); // } else if (range == getTypeSystemImpl().javaObjectType) { // fs.setJavaObjectValue(feat, (s == null) ? null : deserializeJavaObject(s)); } else { Misc.internalError(); } } // private Object deserializeJavaObject(String s) { // throw new UnsupportedOperationException("Deserializing JavaObjects not yet implemented"); // } // // static String serializeJavaObject(Object s) { // throw new UnsupportedOperationException("Serializing JavaObjects not yet implemented"); // } /* * This should be the only place where the encoding of floats and doubles in terms of ints is specified * Someday we may want to preserve NAN things using "raw" versions */ public static final float int2float(int i) { return Float.intBitsToFloat(i); } public static final int float2int(float f) { return Float.floatToIntBits(f); } public static final double long2double(long l) { return Double.longBitsToDouble(l); } public static final long double2long(double d) { return Double.doubleToLongBits(d); } // Type access methods. public boolean isStringType(Type type) { return type instanceof TypeImpl_string; } public boolean isAbstractArrayType(Type type) { return isArrayType(type); } public boolean isArrayType(Type type) { return ((TypeImpl) type).isArray(); } public boolean isPrimitiveArrayType(Type type) { return (type instanceof TypeImpl_array) && ! type.getComponentType().isPrimitive(); } public boolean isIntArrayType(Type type) { return (type == getTypeSystemImpl().intArrayType); } public boolean isFloatArrayType(Type type) { return ((TypeImpl)type).getCode() == floatArrayTypeCode; } public boolean isStringArrayType(Type type) { return ((TypeImpl)type).getCode() == stringArrayTypeCode; } public boolean isBooleanArrayType(Type type) { return ((TypeImpl)type).getCode() == booleanArrayTypeCode; } public boolean isByteArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public boolean isShortArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public boolean isLongArrayType(Type type) { return ((TypeImpl)type).getCode() == longArrayTypeCode; } public boolean isDoubleArrayType(Type type) { return ((TypeImpl)type).getCode() == doubleArrayTypeCode; } public boolean isFSArrayType(Type type) { return ((TypeImpl)type).getCode() == fsArrayTypeCode; } public boolean isIntType(Type type) { return ((TypeImpl)type).getCode() == intTypeCode; } public boolean isFloatType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public boolean isByteType(Type type) { return ((TypeImpl)type).getCode() == byteTypeCode; } public boolean isBooleanType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public boolean isShortType(Type type) { return ((TypeImpl)type).getCode() == shortTypeCode; } public boolean isLongType(Type type) { return ((TypeImpl)type).getCode() == longTypeCode; } public boolean isDoubleType(Type type) { return ((TypeImpl)type).getCode() == doubleTypeCode; } /* * Only called on base CAS */ /** * @see org.apache.uima.cas.admin.CASMgr#initCASIndexes() */ @Override public void initCASIndexes() throws CASException { final TypeSystemImpl ts = getTypeSystemImpl(); if (!ts.isCommitted()) { throw new CASException(CASException.MUST_COMMIT_TYPE_SYSTEM); } FSIndexComparator comp = this.indexRepository.createComparator(); comp.setType(ts.sofaType); comp.addKey(ts.sofaNum, FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.SOFA_INDEX_NAME, FSIndex.BAG_INDEX); comp = this.indexRepository.createComparator(); comp.setType(ts.annotType); comp.addKey(ts.startFeat, FSIndexComparator.STANDARD_COMPARE); comp.addKey(ts.endFeat, FSIndexComparator.REVERSE_STANDARD_COMPARE); comp.addKey(this.indexRepository.getDefaultTypeOrder(), FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.STD_ANNOTATION_INDEX); } // /////////////////////////////////////////////////////////////////////////// // CAS support ... create CAS view of aSofa // For internal use only public CAS getView(int sofaNum) { return getViewFromSofaNbr(sofaNum); } @Override public CAS getCurrentView() { return getView(CAS.NAME_DEFAULT_SOFA); } // /////////////////////////////////////////////////////////////////////////// // JCas support @Override public JCas getJCas() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } public JCasImpl getJCasImpl() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } // /** // * Internal use only // * // * @return corresponding JCas, assuming it exists // */ // public JCas getExistingJCas() { // return this.jcas; // } // // Create JCas view of aSofa @Override public JCas getJCas(SofaFS aSofa) throws CASException { // Create base JCas, if needed this.svd.baseCAS.getJCas(); return getView(aSofa).getJCas(); /* * // If a JCas already exists for this Sofa, return it JCas aJCas = (JCas) * this.svd.baseCAS.sofa2jcasMap.get(Integer.valueOf(aSofa.getSofaRef())); if * (null != aJCas) { return aJCas; } // Get view of aSofa CASImpl view = * (CASImpl) getView(aSofa); // wrap in JCas aJCas = view.getJCas(); * this.sofa2jcasMap.put(Integer.valueOf(aSofa.getSofaRef()), aJCas); return * aJCas; */ } /** * @deprecated */ @Override @Deprecated public JCas getJCas(SofaID aSofaID) throws CASException { SofaFS sofa = getSofa(aSofaID); // sofa guaranteed to be non-null by above method. return getJCas(sofa); } private CASImpl getViewFromSofaNbr(int nbr) { final ArrayList<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (nbr < sn2v.size()) { return sn2v.get(nbr); } return null; } void setViewForSofaNbr(int nbr, CASImpl view) { Misc.setWithExpand(this.svd.sofaNbr2ViewMap, nbr, view); } // For internal platform use only CASImpl getInitialView() { CASImpl couldBeThis = getViewFromSofaNbr(1); if (couldBeThis != null) { return couldBeThis; } // create the initial view, without a Sofa CASImpl aView = new CASImpl(this.svd.baseCAS, (SofaFS) null); setViewForSofaNbr(1, aView); assert (this.svd.viewCount <= 1); this.svd.viewCount = 1; return aView; } @Override public CAS createView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // Can't use name of Initial View if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, aSofaID); } Sofa newSofa = createSofa(absoluteSofaName, null); CAS newView = getView(newSofa); ((CASImpl) newView).registerView(newSofa); return newView; } @Override public CAS getView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // if this resolves to the Initial View, return view(1)... // ... as the Sofa for this view may not exist yet if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { return getInitialView(); } // get Sofa and switch to view SofaFS sofa = getSofa(absoluteSofaName); // sofa guaranteed to be non-null by above method // unless sofa doesn't exist, which will cause a throw. return getView(sofa); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getView(org.apache.uima.cas.SofaFS) * * Callers of this can have created Sofas in the CAS without views: using the * old deprecated createSofa apis (this is being fixed so these will create * the views) via deserialization, which will put the sofaFSs into the CAS * without creating the views, and then call this to create the views. - for * deserialization: there are 2 kinds: 1 is xmi the other is binary. - for * xmi: there is 1.4.x compatible and 2.1 compatible. The older format can * have sofaNbrs in the order 2, 3, 4, 1 (initial sofa), 5, 6, 7 The newer * format has them in order. For deserialized sofas, we insure here that there * are no duplicates. This is not done in the deserializers - they use either * heap dumping (binary) or generic fs creators (xmi). * * Goal is to detect case where check is needed (sofa exists, but view not yet * created). This is done by looking for cases where sofaNbr &gt; curViewCount. * This only works if the sofaNbrs go up by 1 (except for the initial sofa) in * the input sequence of calls. */ @Override public CASImpl getView(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; final int sofaNbr = sofa.getSofaRef(); // final Integer sofaNbrInteger = Integer.valueOf(sofaNbr); CASImpl aView = getViewFromSofaNbr(sofaNbr); if (null == aView) { // This is the deserializer case, or the case where an older API created a // sofa, // which is now creating the associated view // create a new CAS view aView = new CASImpl(this.svd.baseCAS, sofa); setViewForSofaNbr(sofaNbr, aView); verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, sofa); return aView; } // for deserialization - might be reusing a view, and need to tie new Sofa // to old View if (null == aView.mySofaRef) { aView.mySofaRef = sofa; } verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, aSofa); return aView; } // boolean isSofaView(int sofaAddr) { // if (mySofaRef == null) { // // don't create initial sofa // return false; // } // return mySofaRef == sofaAddr; // } /* * for Sofas being added (determined by sofaNbr &gt; curViewCount): verify sofa * name is not already present, and record it for future tests * * Only should do the name test & update in the case of deserialized new sofas * coming in. These will come in, in order. Exception is "_InitialView" which * could come in the middle. If it comes in the middle, no test will be done * for duplicates, and it won't be added to set of known names. This is ok * because the createVIew special cases this test. Users could corrupt an xmi * input, which would make this logic fail. */ private void verifySofaNameUniqueIfDeserializedViewAdded(int sofaNbr, SofaFS aSofa) { final int curViewCount = this.svd.viewCount; if (curViewCount < sofaNbr) { // Only true for deserialized sofas with new views being either created, // or // hooked-up from CASes that were freshly reset, which have multiple // views. // Assume sofa numbers are incrementing by 1 assert (sofaNbr == curViewCount + 1); this.svd.viewCount = sofaNbr; String id = aSofa.getSofaID(); // final Feature idFeat = // getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID); // String id = // ll_getStringValue(((FeatureStructureImpl)aSofa).getAddress(), // ((FeatureImpl) idFeat).getCode()); Misc.assertUie(this.svd.sofaNameSet.contains(id)); // this.svd.sofaNameSet.add(id); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getTypeSystem() */ @Override public LowLevelTypeSystem ll_getTypeSystem() { return getTypeSystemImpl().getLowLevelTypeSystem(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getIndexRepository() */ @Override public LowLevelIndexRepository ll_getIndexRepository() { return this.indexRepository; } /** * * @param fs * @param domType * @param featCode */ private final void checkLowLevelParams(TOP fs, TypeImpl domType, int featCode) { checkFeature(featCode); checkTypeHasFeature(domType, featCode); } /** * Check that the featCode is a feature of the domain type * @param domTypeCode * @param featCode */ private final void checkTypeHasFeature(TypeImpl domainType, int featureCode) { checkTypeHasFeature(domainType, getFeatFromCode_checked(featureCode)); } private final void checkTypeHasFeature(TypeImpl domainType, FeatureImpl feature) { if (!domainType.isAppropriateFeature(feature)) { throw new LowLevelException(LowLevelException.FEAT_DOM_ERROR, Integer.valueOf(domainType.getCode()), domainType.getName(), Integer.valueOf(feature.getCode()), feature.getName()); } } /** * Check the range is appropriate for this type/feature. Throws * LowLevelException if it isn't. * * @param domType * domain type * @param ranType * range type * @param feat * feature */ public final void checkTypingConditions(Type domType, Type ranType, Feature feat) { TypeImpl domainTi = (TypeImpl) domType; FeatureImpl fi = (FeatureImpl) feat; checkTypeHasFeature(domainTi, fi); if (!((TypeImpl) fi.getRange()).subsumes((TypeImpl) ranType)) { throw new LowLevelException(LowLevelException.FEAT_RAN_ERROR, Integer.valueOf(fi.getCode()), feat.getName(), Integer.valueOf(((TypeImpl)ranType).getCode()), ranType.getName()); } } /** * Validate a feature's range is a ref to a feature structure * @param featCode * @throws LowLevelException */ private final void checkFsRan(FeatureImpl fi) throws LowLevelException { if (!fi.getRangeImpl().isRefType) { throw new LowLevelException(LowLevelException.FS_RAN_TYPE_ERROR, Integer.valueOf(fi.getCode()), fi.getName(), fi.getRange().getName()); } } private final void checkFeature(int featureCode) { if (!getTypeSystemImpl().isFeature(featureCode)) { throw new LowLevelException(LowLevelException.INVALID_FEATURE_CODE, Integer.valueOf(featureCode)); } } private TypeImpl getTypeFromCode(int typeCode) { return getTypeSystemImpl().getTypeForCode(typeCode); } private TypeImpl getTypeFromCode_checked(int typeCode) { return getTypeSystemImpl().getTypeForCode_checked(typeCode); } private FeatureImpl getFeatFromCode_checked(int featureCode) { return getTypeSystemImpl().getFeatureForCode_checked(featureCode); } public final <T extends TOP> T getFsFromId_checked(int fsRef) { T r = getFsFromId(fsRef); if (r == null) { if (fsRef == 0) { return null; } LowLevelException e = new LowLevelException(LowLevelException.INVALID_FS_REF, Integer.valueOf(fsRef)); // this form to enable seeing this even if the // throwable is silently handled. // System.err.println("debug " + e); throw e; } return r; } @Override public final boolean ll_isRefType(int typeCode) { return getTypeFromCode(typeCode).isRefType; } @Override public final int ll_getTypeClass(int typeCode) { return TypeSystemImpl.getTypeClass(getTypeFromCode(typeCode)); } // backwards compatibility only @Override public final int ll_createFS(int typeCode) { return ll_createFS(typeCode, true); } @Override public final int ll_createFS(int typeCode, boolean doCheck) { TypeImpl ti = (TypeImpl) getTypeSystemImpl().ll_getTypeForCode(typeCode); if (doCheck) { if (ti == null || !ti.isCreatableAndNotBuiltinArray()) { throw new LowLevelException(LowLevelException.CREATE_FS_OF_TYPE_ERROR, Integer.valueOf(typeCode)); } } TOP fs = (TOP) createFS(ti); if (!fs._isPearTrampoline()) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); // hold on to it if nothing else is } else { svd.id2fs.put(fs); } } return fs._id; } /** * used for ll_setIntValue which changes type code * @param ti - the type of the created FS * @param id - the id to use * @return the FS */ private TOP createFsWithExistingId(TypeImpl ti, int id) { svd.reuseId = id; try { TOP fs = createFS(ti); svd.id2fs.putChange(id, fs); return fs; } finally { svd.reuseId = 0; } } /* /** * @param arrayLength * @return the id of the created array * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_createArray(int, int) */ @Override public int ll_createArray(int typeCode, int arrayLength) { TOP fs = createArray(getTypeFromCode_checked(typeCode), arrayLength); if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); } else { svd.id2fs.put(fs); } return fs._id; } /** * (for backwards compatibility with V2 CASImpl) * Create a temporary (i.e., per document) array FS on the heap. * * @param type * The type code of the array to be created. * @param len * The length of the array to be created. * @return - * @exception ArrayIndexOutOfBoundsException * If <code>type</code> is not a type. */ public int createTempArray(int type, int len) { return ll_createArray(type, len); } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createByteArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().byteArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createBooleanArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().booleanArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createShortArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().shortArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createLongArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().longArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createDoubleArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().doubleArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createArray(int typeCode, int arrayLength, boolean doChecks) { TypeImpl ti = getTypeFromCode_checked(typeCode); if (doChecks) { if (!ti.isArray()) { throw new LowLevelException(LowLevelException.CREATE_ARRAY_OF_TYPE_ERROR, Integer.valueOf(typeCode), ti.getName()); } if (arrayLength < 0) { throw new LowLevelException(LowLevelException.ILLEGAL_ARRAY_LENGTH, Integer.valueOf(arrayLength)); } } TOP fs = createArray(ti, arrayLength); svd.id2fs.put(fs); return fs._id; } public void validateArraySize(int length) { if (length < 0) { /** Array size must be &gt;= 0. */ throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } /** * Safety - any time the low level API to a FS is requested, * hold on to that FS until CAS reset to mimic how v2 works. */ @Override public final int ll_getFSRef(FeatureStructure fs) { if (null == fs) { return NULL; } TOP fst = (TOP) fs; if (fst._isPearTrampoline()) { return fst._id; // no need to hold on to this one - it's in jcas hash maps } // uncond. because this method can be called multiple times svd.id2fs.putUnconditionally(fst); // hold on to it return ((FeatureStructureImplC)fs)._id; } @Override public <T extends TOP> T ll_getFSForRef(int id) { return getFsFromId_checked(id); } /** * Handle some unusual backwards compatibility cases * featureCode = 0 - implies getting the type code * feature range is int - normal * feature range is a fs reference, return the id * feature range is a string: add the string if not already present to the string heap, return the int handle. * @param fsRef - * @param featureCode - * @return - */ @Override public final int ll_getIntValue(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { return fs._getTypeImpl().getCode(); // case where the type is being requested } FeatureImpl fi = getFeatFromCode_checked(featureCode); SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: return fs.getFeatureValue(fi)._id; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: return fs._getIntValueNc(fi); case Slot_StrRef: return getCodeForString(fs._getStringValueNc(fi)); case Slot_LongRef: return getCodeForLong(fs._getLongValueNc(fi)); case Slot_DoubleRef: return getCodeForLong(CASImpl.double2long(fs._getDoubleValueNc(fi))); default: throw new CASRuntimeException( CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); } } // public final int ll_getIntValueFeatOffset(int fsRef, int featureOffset) { // return ll_getFSForRef(fsRef)._intData[featureOffset]; // } @Override public final float ll_getFloatValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFloatValue(getFeatFromCode_checked(featureCode)); } @Override public final String ll_getStringValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getStringValue(getFeatFromCode_checked(featureCode)); } // public final String ll_getStringValueFeatOffset(int fsRef, int featureOffset) { // return (String) getFsFromId_checked(fsRef)._refData[featureOffset]; // } @Override public final int ll_getRefValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } // public final int ll_getRefValueFeatOffset(int fsRef, int featureOffset) { // return ((FeatureStructureImplC)getFsFromId_checked(fsRef)._refData[featureOffset]).id(); // } @Override public final int ll_getIntValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getIntValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getFloatValue(int, int, * boolean) */ @Override public final float ll_getFloatValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getFloatValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getStringValue(int, int, * boolean) */ @Override public final String ll_getStringValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getStringValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getRefValue(int, int, boolean) */ @Override public final int ll_getRefValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } /** * This is the method all normal FS feature "setters" call before doing the set operation * on values where the range could be used as an index key. * <p> * If enabled, it will check if the update may corrupt any index in any view. The check tests * whether the feature is being used as a key in one or more indexes and if the FS is in one or more * corruptable view indexes. * <p> * If true, then: * <ul> * <li>it may remove and remember (for later adding-back) the FS from all corruptable indexes * (bag indexes are not corruptable via updating, so these are skipped). * The addback occurs later either via an explicit call to do so, or the end of a protectIndex block, or. * (if autoIndexProtect is enabled) after the individual feature update is completed.</li> * <li>it may give a WARN level message to the log. This enables users to * implement their own optimized handling of this for "high performance" * applications which do not want the overhead of runtime checking. </li></ul> * <p> * * @param fs - the FS to test if it is in the indexes * @param featCode - the feature being tested * @return true if something may need to be added back */ private boolean checkForInvalidFeatureSetting(TOP fs, int featCode) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = checkForInvalidFeatureSetting2(fs); if (wasRemoved && doCorruptReport()) { featModWhileInIndexReport(fs, featCode); } return wasRemoved; } return false; } /** * version for deserializers, and for set document language, using their own store for toBeAdded * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, int featCode, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, featCode); // } return wasRemoved; } return false; } /** * version for deserializers, using their own store for toBeAdded * and not bothering to check for particular features * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, null); // } return wasRemoved; } return false; } // // version of above, but using jcasFieldRegistryIndex // private boolean checkForInvalidFeatureSettingJFRI(TOP fs, int jcasFieldRegistryIndex) { // if (doInvalidFeatSettingCheck(fs) && // svd.featureJiInIndexKeys.get(jcasFieldRegistryIndex)) { // // boolean wasRemoved = checkForInvalidFeatureSetting2(fs); // //// if (wasRemoved && doCorruptReport()) { //// featModWhileInIndexReport(fs, getFeatFromRegistry(jcasFieldRegistryIndex)); //// } // return wasRemoved; // } // return false; // } private boolean checkForInvalidFeatureSetting2(TOP fs) { final int ssz = svd.fssTobeAddedback.size(); // next method skips if the fsRef is not in the index (cache) boolean wasRemoved = removeFromCorruptableIndexAnyView( fs, (ssz > 0) ? getAddback(ssz) : // validates single not in use getAddbackSingle() // validates single usage at a time ); if (!wasRemoved && svd.fsTobeAddedbackSingleInUse) { svd.fsTobeAddedbackSingleInUse = false; } return wasRemoved; } // public FeatureImpl getFeatFromRegistry(int jcasFieldRegistryIndex) { // return getFSClassRegistry().featuresFromJFRI[jcasFieldRegistryIndex]; // } private boolean doCorruptReport() { return // skip message if wasn't removed // skip message if protected in explicit block IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && svd.fssTobeAddedback.size() == 0; } /** * * @param fs - * @return false if the fs is not in a set or sorted index (bit in fs), or * the auto protect is disabled and we're not in an explicit protect block */ private boolean doInvalidFeatSettingCheck(TOP fs) { if (!fs._inSetSortedIndex()) { return false; } final int ssz = svd.fssTobeAddedback.size(); // skip if protection is disabled, and no explicit protection block if (IS_DISABLED_PROTECT_INDEXES && ssz == 0) { return false; } return true; } private void featModWhileInIndexReport(FeatureStructure fs, int featCode) { featModWhileInIndexReport(fs, getFeatFromCode_checked(featCode)); } private void featModWhileInIndexReport(FeatureStructure fs, FeatureImpl fi) { // prepare a message which includes the feature which is a key, the fs, and // the call stack. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new Throwable().printStackTrace(pw); pw.close(); String msg = String.format( "While FS was in the index, the feature \"%s\"" + ", which is used as a key in one or more indexes, " + "was modified\n FS = \"%s\"\n%s%n", (fi == null)? "for-all-features" : fi.getName(), fs.toString(), sw.toString()); UIMAFramework.getLogger().log(Level.WARNING, msg); if (IS_THROW_EXCEPTION_CORRUPT_INDEX) { throw new UIMARuntimeException(UIMARuntimeException.ILLEGAL_FS_FEAT_UPDATE, new Object[]{}); } } /** * Only called if there was something removed that needs to be added back * * skip the addback (to defer it until later) if: * - running in block mode (you can tell this if svd.fssTobeAddedback.size() &gt; 0) or * if running in block mode, the add back is delayed until the end of the block * * @param fs the fs to add back */ public void maybeAddback(TOP fs) { if (svd.fssTobeAddedback.size() == 0) { assert(svd.fsTobeAddedbackSingleInUse); svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } } boolean removeFromCorruptableIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded) { return removeFromIndexAnyView(fs, toBeAdded, FSIndexRepositoryImpl.SKIP_BAG_INDEXES); } /** * This might be called from low level set int value, if we support switching types, and we want to * remove the old type from all indexes. * @param fs the fs to maybe remove * @param toBeAdded a place to record the removal so we can add it back later * @param isSkipBagIndexes is true usually, we don't need to remove/readd to bag indexes (except for the case * of supporting switching types via low level set int for v2 backwards compatibility) * @return true if was removed from one or more indexes */ boolean removeFromIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded, boolean isSkipBagIndexes) { final TypeImpl ti = ((FeatureStructureImplC)fs)._getTypeImpl(); if (ti.isAnnotationBaseType()) { boolean r = removeAndRecord(fs, (FSIndexRepositoryImpl) fs._casView.getIndexRepository(), toBeAdded, isSkipBagIndexes); fs._resetInSetSortedIndex(); return r; } // not a subtype of AnnotationBase, need to check all views (except base) // sofas indexed in the base view are not corruptable. final Iterator<CAS> viewIterator = getViewIterator(); boolean wasRemoved = false; while (viewIterator.hasNext()) { wasRemoved |= removeAndRecord(fs, (FSIndexRepositoryImpl) viewIterator.next().getIndexRepository(), toBeAdded, isSkipBagIndexes); } fs._resetInSetSortedIndex(); return wasRemoved; } /** * remove a FS from all indexes in this view (except bag indexes, if isSkipBagIndex is true) * @param fs the fs to be removed * @param ir the view * @param toBeAdded the place to record how many times it was in the index, per view * @param isSkipBagIndex set to true for corruptable removes, false for remove in all cases from all indexes * @return true if it was removed, false if it wasn't in any corruptable index. */ private boolean removeAndRecord(TOP fs, FSIndexRepositoryImpl ir, FSsTobeAddedback toBeAdded, boolean isSkipBagIndex) { boolean wasRemoved = ir.removeFS_ret(fs, isSkipBagIndex); if (wasRemoved) { toBeAdded.recordRemove(fs, ir, 1); } return wasRemoved; } /** * Special considerations: * Interface with corruption checking * For backwards compatibility: * handle cases where feature is: * int - normal * 0 - change type code * a ref: treat int as FS "addr" * not an int: handle like v2 where reasonable */ @Override public final void ll_setIntValue(int fsRef, int featureCode, int value) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { switchFsType(fs, value); return; } FeatureImpl fi = getFeatFromCode_checked(featureCode); if (fs._getTypeImpl().isArray()) { throw new UnsupportedOperationException("ll_setIntValue not permitted to set a feature of an array"); } SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: if (fi.getCode() == annotBaseSofaFeatCode) { // setting the sofa ref of an annotationBase // can't change this so just verify it's the same TOP sofa = fs.getFeatureValue(fi); if (sofa._id != value) { throw new UnsupportedOperationException("ll_setIntValue not permitted to change a sofaRef feature"); } return; // if the same, just ignore, already set } TOP ref = fs._casView.getFsFromId_checked(value); fs.setFeatureValue(fi, ref); // does the right feature check, too return; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: fs._setIntValueCJ(fi, value); break; case Slot_StrRef: String s = getStringForCode(value); if (s == null && value != 0) { Misc.internalError(new Exception("ll_setIntValue got null string for non-0 handle: " + value)); } fs._setRefValueNfcCJ(fi, getStringForCode(value)); break; case Slot_LongRef: case Slot_DoubleRef: Long lng = getLongForCode(value); if (lng == null) { Misc.internalError(new Exception("ll_setIntValue got null Long/Double for handle: " + value)); } fs._setLongValueNfcCJ(fi, lng); break; default: CASRuntimeException e = new CASRuntimeException(CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); // System.err.println("debug " + e); throw e; } } private String getStringForCode(int i) { if (null == svd.llstringSet) { return null; } return svd.llstringSet.getStringForCode(i); } private int getCodeForString(String s) { if (null == svd.llstringSet) { svd.llstringSet = new StringSet(); } return svd.llstringSet.getCodeForString(s); // avoids adding duplicates } private Long getLongForCode(int i) { if (null == svd.lllongSet) { return null; } return svd.lllongSet.getLongForCode(i); } private int getCodeForLong(long s) { if (null == svd.lllongSet) { svd.lllongSet = new LongSet(); } return svd.lllongSet.getCodeForLong(s); // avoids adding duplicates } private void switchFsType(TOP fs, int value) { // throw new UnsupportedOperationException(); // case where the type is being changed // if the new type is a sub/super type of the existing type, // some field data may be copied // if not, no data is copied. // // Item is removed from index and re-indexed // to emulate what V2 did, // the indexing didn't change // all the slots were the same // boolean wasRemoved = removeFromIndexAnyView(fs, getAddbackSingle(), FSIndexRepositoryImpl.INCLUDE_BAG_INDEXES); if (!wasRemoved) { svd.fsTobeAddedbackSingleInUse = false; } TypeImpl newType = getTypeFromCode_checked(value); Class<?> newClass = newType.getJavaClass(); if ((fs instanceof UimaSerializable) || UimaSerializable.class.isAssignableFrom(newClass)) { throw new UnsupportedOperationException("can't switch type to/from UimaSerializable"); } // Measurement - record which type gets switched to which other type // count how many times // record which JCas cover class goes with each type // key = old type, new type, old jcas cover class, new jcas cover class // value = count MeasureSwitchType mst = null; if (MEASURE_SETINT) { MeasureSwitchType key = new MeasureSwitchType(fs._getTypeImpl(), newType); synchronized (measureSwitches) { // map access / updating must be synchronized mst = measureSwitches.get(key); if (null == mst) { measureSwitches.put(key, key); mst = key; } mst.count ++; mst.newSubsumesOld = newType.subsumes(fs._getTypeImpl()); mst.oldSubsumesNew = fs._getTypeImpl().subsumes(newType); } } if (newClass == fs._getTypeImpl().getJavaClass() || newType.subsumes(fs._getTypeImpl())) { // switch in place fs._setTypeImpl(newType); return; } // if types don't subsume each other, we // deviate a bit from V2 behavior // and skip copying the feature slots boolean isOkToCopyFeatures = // true || // debug fs._getTypeImpl().subsumes(newType) || newType.subsumes(fs._getTypeImpl()); // throw new CASRuntimeException(CASRuntimeException.ILLEGAL_TYPE_CHANGE, newType.getName(), fs._getTypeImpl().getName()); TOP newFs = createFsWithExistingId(newType, fs._id); // updates id -> fs map // initialize fields: if (isOkToCopyFeatures) { newFs._copyIntAndRefArraysFrom(fs); } // if (wasRemoved) { // addbackSingle(newFs); // } // replace refs in existing FSs with new // will miss any fs's held by user code - no way to fix that without // universal indirection - very inefficient, so just accept for now long st = System.nanoTime(); walkReachablePlusFSsSorted(fsItem -> { if (fsItem._getTypeImpl().hasRefFeature) { if (fsItem instanceof FSArray) { TOP[] a = ((FSArray)fsItem)._getTheArray(); for (int i = 0; i < a.length; i++) { if (fs == a[i]) { a[i] = newFs; } } return; } final int sz = fsItem._getTypeImpl().nbrOfUsedRefDataSlots; for (int i = 0; i < sz; i++) { Object o = fsItem._getRefValueCommon(i); if (o == fs) { fsItem._setRefValueCommon(i, newFs); // fsItem._refData[i] = newFs; } } } }, null, // mark null, // null or predicate for filtering what gets added null); // null or type mapper, skips if not in other ts if (MEASURE_SETINT) { mst.scantime += System.nanoTime() - st; } } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value) { getFsFromId_checked(fsRef).setFloatValue(getFeatFromCode_checked(featureCode), value); } // public final void ll_setFloatValueNoIndexCorruptionCheck(int fsRef, int featureCode, float value) { // setFeatureValueNoIndexCorruptionCheck(fsRef, featureCode, float2int(value)); // } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value) { getFsFromId_checked(fsRef).setStringValue(getFeatFromCode_checked(featureCode), value); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value) { // no index check because refs can't be keys setFeatureValue(fsRef, featureCode, getFsFromId_checked(value)); } @Override public final void ll_setIntValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setIntValue(fsRef, featureCode, value); } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setFloatValue(fsRef, featureCode, value); } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setStringValue(fsRef, featureCode, value); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setCharBufferValue(fsRef, featureCode, buffer, start, length); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length) { ll_setStringValue(fsRef, featureCode, new String(buffer, start, length)); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_copyCharBufferValue(int, int, * char, int) */ @Override public int ll_copyCharBufferValue(int fsRef, int featureCode, char[] buffer, int start) { String str = ll_getStringValue(fsRef, featureCode); if (str == null) { return -1; } final int len = str.length(); final int requestedMax = start + len; // Check that the buffer is long enough to copy the whole string. If it isn't long enough, we // copy up to buffer.length - start characters. final int max = (buffer.length < requestedMax) ? (buffer.length - start) : len; for (int i = 0; i < max; i++) { buffer[start + i] = str.charAt(i); } return len; } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getCharBufferValueSize(int, * int) */ @Override public int ll_getCharBufferValueSize(int fsRef, int featureCode) { String str = ll_getStringValue(fsRef, featureCode); return str.length(); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } ll_setRefValue(fsRef, featureCode, value); } public final int getIntArrayValue(IntegerArray array, int i) { return array.get(i); } public final float getFloatArrayValue(FloatArray array, int i) { return array.get(i); } public final String getStringArrayValue(StringArray array, int i) { return array.get(i); } public final FeatureStructure getRefArrayValue(FSArray array, int i) { return array.get(i); } @Override public final int ll_getIntArrayValue(int fsRef, int position) { return getIntArrayValue(((IntegerArray)getFsFromId_checked(fsRef)), position); } @Override public final float ll_getFloatArrayValue(int fsRef, int position) { return getFloatArrayValue(((FloatArray)getFsFromId_checked(fsRef)), position); } @Override public final String ll_getStringArrayValue(int fsRef, int position) { return getStringArrayValue(((StringArray)getFsFromId_checked(fsRef)), position); } @Override public final int ll_getRefArrayValue(int fsRef, int position) { return ((TOP)getRefArrayValue(((FSArray)getFsFromId_checked(fsRef)), position))._id(); } private void throwAccessTypeError(int fsRef, int typeCode) { throw new LowLevelException(LowLevelException.ACCESS_TYPE_ERROR, Integer.valueOf(fsRef), Integer.valueOf(typeCode), getTypeSystemImpl().ll_getTypeForCode(typeCode).getName(), getTypeSystemImpl().ll_getTypeForCode(ll_getFSRefType(fsRef)).getName()); } public final void checkArrayBounds(int fsRef, int pos) { final int arrayLength = ll_getArraySize(fsRef); if ((pos < 0) || (pos >= arrayLength)) { throw new ArrayIndexOutOfBoundsException(pos); // LowLevelException e = new LowLevelException( // LowLevelException.ARRAY_INDEX_OUT_OF_RANGE); // e.addArgument(Integer.toString(pos)); // throw e; } } public final void checkArrayBounds(int arrayLength, int pos, int length) { if ((pos < 0) || (length < 0) || ((pos + length) > arrayLength)) { throw new LowLevelException(LowLevelException.ARRAY_INDEX_LENGTH_OUT_OF_RANGE, Integer.toString(pos), Integer.toString(length)); } } /** * Check that the fsRef is valid. * Check that the fs is featureCode belongs to the fs * Check that the featureCode is one of the features of the domain type of the fsRef * feat could be primitive, string, ref to another feature * * @param fsRef * @param typeCode * @param featureCode */ private final void checkNonArrayConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); final TypeImpl domainType = (TypeImpl) fs.getType(); // checkTypeAt(domType, fs); // since the type is from the FS, it's always OK checkFeature(featureCode); // checks that the featureCode is in the range of all feature codes TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkTypeHasFeature(domainType, fi); // checks that the feature code is one of the features of the type // checkFsRan(fi); } private final void checkFsRefConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); checkLowLevelParams(fs, fs._getTypeImpl(), featureCode); // checks type has feature TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkFsRan(fi); // next not needed because checkFsRan already validates this // checkFsRef(fsRef + this.svd.casMetadata.featureOffset[featureCode]); } // private final void checkArrayConditions(int fsRef, int typeCode, // int position) { // checkTypeSubsumptionAt(fsRef, typeCode); // // skip this next test because // // a) it's done implicitly in the bounds check and // // b) it fails for arrays stored outside of the main heap (e.g., // byteArrays, etc.) // // checkFsRef(getArrayStartAddress(fsRef) + position); // checkArrayBounds(fsRef, position); // } private final void checkPrimitiveArrayConditions(int fsRef, int typeCode, int position) { if (typeCode != ll_getFSRefType(fsRef)) { throwAccessTypeError(fsRef, typeCode); } checkArrayBounds(fsRef, position); } @Override public final int ll_getIntArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } return ll_getIntArrayValue(fsRef, position); } @Override public float ll_getFloatArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } return ll_getFloatArrayValue(fsRef, position); } @Override public String ll_getStringArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } return ll_getStringArrayValue(fsRef, position); } @Override public int ll_getRefArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } return ll_getRefArrayValue(fsRef, position); } @Override public void ll_setIntArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } ll_setIntArrayValue(fsRef, position, value); } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } ll_setFloatArrayValue(fsRef, position, value); } @Override public void ll_setStringArrayValue(int fsRef, int position, String value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } ll_setStringArrayValue(fsRef, position, value); } @Override public void ll_setRefArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } ll_setRefArrayValue(fsRef, position, value); } /* ************************ * Low Level Array Setters * ************************/ @Override public void ll_setIntArrayValue(int fsRef, int position, int value) { IntegerArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value) { FloatArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setStringArrayValue(int fsRef, int position, String value) { StringArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setRefArrayValue(int fsRef, int position, int value) { FSArray array = getFsFromId_checked(fsRef); array.set(position, getFsFromId_checked(value)); // that set operation does required journaling } /** * @param fsRef an id for a FS * @return the type code for this FS */ @Override public int ll_getFSRefType(int fsRef) { return getFsFromId_checked(fsRef)._getTypeCode(); } @Override public int ll_getFSRefType(int fsRef, boolean doChecks) { // type code is always valid return ll_getFSRefType(fsRef); } @Override public LowLevelCAS getLowLevelCAS() { return this; } @Override public int size() { throw new UIMARuntimeException(UIMARuntimeException.INTERNAL_ERROR); } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#getJCasClassLoader() */ @Override public ClassLoader getJCasClassLoader() { return this.svd.jcasClassLoader; } /* * Called to set the overall jcas class loader to use. * * @see org.apache.uima.cas.admin.CASMgr#setJCasClassLoader(java.lang.ClassLoader) */ @Override public void setJCasClassLoader(ClassLoader classLoader) { this.svd.jcasClassLoader = classLoader; } // Internal use only, public for cross package use // Assumes: The JCasClassLoader for a CAS is set up initially when the CAS is // created // and not switched (other than by this code) once it is set. // Callers of this method always code the "restoreClassLoaderUnlockCAS" in // pairs, // protected as needed with try - finally blocks. // // Special handling is needed for CAS Mulipliers - they can modify a cas up to // the point they no longer "own" it. // So the try / finally approach doesn't fit public void switchClassLoaderLockCas(Object userCode) { switchClassLoaderLockCasCL(userCode.getClass().getClassLoader()); } public void switchClassLoaderLockCasCL(ClassLoader newClassLoader) { // lock out CAS functions to which annotator should not have access enableReset(false); svd.switchClassLoader(newClassLoader); } // // internal use, public for cross-package ref // public boolean usingBaseClassLoader() { // return (this.svd.jcasClassLoader == this.svd.previousJCasClassLoader); // } public void restoreClassLoaderUnlockCas() { // unlock CAS functions enableReset(true); // this might be called without the switch ever being called svd.restoreClassLoader(); } @Override public FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException { return FeatureValuePathImpl.getFeaturePath(featureValuePath); } @Override public void setOwner(CasOwner aCasOwner) { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.setOwner(aCasOwner); } else { super.setOwner(aCasOwner); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.AbstractCas_ImplBase#release() */ @Override public void release() { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.release(); } else { super.release(); } } /* ********************************** * A R R A Y C R E A T I O N ************************************/ @Override public ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ByteArray(this.getJCas(), length); } @Override public BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new BooleanArray(this.getJCas(), length); } @Override public ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ShortArray(this.getJCas(), length); } @Override public LongArrayFS createLongArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new LongArray(this.getJCas(), length); } @Override public DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new DoubleArray(this.getJCas(), length); } @Override public byte ll_getByteValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getByteValue(getFeatFromCode_checked(featureCode)); } @Override public byte ll_getByteValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getByteValue(fsRef, featureCode); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getBooleanValue(getFeatFromCode_checked(featureCode)); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getBooleanValue(fsRef, featureCode); } @Override public short ll_getShortValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getShortValue(getFeatFromCode_checked(featureCode)); } @Override public short ll_getShortValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getShortValue(fsRef, featureCode); } // impossible to implement in v3; change callers // public long ll_getLongValue(int offset) { // return this.getLongHeap().getHeapValue(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getLongValue(getFeatFromCode_checked(featureCode)); } // public long ll_getLongValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getLongValueOffset(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getLongValue(fsRef, featureCode); } @Override public double ll_getDoubleValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getDoubleValue(getFeatFromCode_checked(featureCode)); } // public double ll_getDoubleValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getDoubleValueOffset(offset); // } @Override public double ll_getDoubleValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getDoubleValue(fsRef, featureCode); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value) { getFsFromId_checked(fsRef).setBooleanValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setBooleanValue(fsRef, featureCode, value); } @Override public final void ll_setByteValue(int fsRef, int featureCode, byte value) { getFsFromId_checked(fsRef).setByteValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setByteValue(int fsRef, int featureCode, byte value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setByteValue(fsRef, featureCode, value); } @Override public final void ll_setShortValue(int fsRef, int featureCode, short value) { getFsFromId_checked(fsRef).setShortValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setShortValue(int fsRef, int featureCode, short value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setShortValue(fsRef, featureCode, value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value) { getFsFromId_checked(fsRef).setLongValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setLongValue(fsRef, featureCode, value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value) { getFsFromId_checked(fsRef).setDoubleValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setDoubleValue(fsRef, featureCode, value); } @Override public byte ll_getByteArrayValue(int fsRef, int position) { return ((ByteArray) getFsFromId_checked(fsRef)).get(position); } @Override public byte ll_getByteArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getByteArrayValue(fsRef, position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position) { return ((BooleanArray) getFsFromId_checked(fsRef)).get(position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getBooleanArrayValue(fsRef, position); } @Override public short ll_getShortArrayValue(int fsRef, int position) { return ((ShortArray) getFsFromId_checked(fsRef)).get(position); } @Override public short ll_getShortArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getShortArrayValue(fsRef, position); } @Override public long ll_getLongArrayValue(int fsRef, int position) { return ((LongArray) getFsFromId_checked(fsRef)).get(position); } @Override public long ll_getLongArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getLongArrayValue(fsRef, position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position) { return ((DoubleArray) getFsFromId_checked(fsRef)).get(position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getDoubleArrayValue(fsRef, position); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value) { ((ByteArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value, boolean doTypeChecks) { ll_setByteArrayValue(fsRef, position, value);} @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean b) { ((BooleanArray) getFsFromId_checked(fsRef)).set(position, b); } @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean value, boolean doTypeChecks) { ll_setBooleanArrayValue(fsRef, position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value) { ((ShortArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value, boolean doTypeChecks) { ll_setShortArrayValue(fsRef, position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value) { ((LongArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value, boolean doTypeChecks) { ll_setLongArrayValue(fsRef, position, value); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double d) { ((DoubleArray) getFsFromId_checked(fsRef)).set(position, d); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double value, boolean doTypeChecks) { ll_setDoubleArrayValue(fsRef, position, value); } public boolean isAnnotationType(Type t) { return ((TypeImpl)t).isAnnotationType(); } /** * @param t the type code to test * @return true if that type is subsumed by AnnotationBase type */ public boolean isSubtypeOfAnnotationBaseType(int t) { TypeImpl ti = getTypeFromCode(t); return (ti == null) ? false : ti.isAnnotationBaseType(); } public boolean isBaseCas() { return this == getBaseCAS(); } @Override public Annotation createAnnotation(Type type, int begin, int end) { // duplicates a later check // if (this.isBaseCas()) { // // Can't create annotation on base CAS // throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "createAnnotation(Type, int, int)"); // } Annotation fs = (Annotation) createFS(type); fs.setBegin(begin); fs.setEnd(end); return fs; } public int ll_createAnnotation(int typeCode, int begin, int end) { TOP fs = createAnnotation(getTypeFromCode(typeCode), begin, end); svd.id2fs.put(fs); // to prevent gc from reclaiming return fs._id(); } /** * The generic spec T extends AnnotationFS (rather than AnnotationFS) allows the method * JCasImpl getAnnotationIndex to return Annotation instead of AnnotationFS * @param <T> the Java class associated with the annotation index * @return the annotation index */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex() { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex(getTypeSystemImpl().annotType); } /* (non-Javadoc) * @see org.apache.uima.cas.CAS#getAnnotationIndex(org.apache.uima.cas.Type) */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex((TypeImpl) type); } /** * @see org.apache.uima.cas.CAS#getAnnotationType() */ @Override public Type getAnnotationType() { return getTypeSystemImpl().annotType; } /** * @see org.apache.uima.cas.CAS#getEndFeature() */ @Override public Feature getEndFeature() { return getTypeSystemImpl().endFeat; } /** * @see org.apache.uima.cas.CAS#getBeginFeature() */ @Override public Feature getBeginFeature() { return getTypeSystemImpl().startFeat; } private <T extends AnnotationFS> T createDocumentAnnotation(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); // Remove any existing document annotations. FSIterator<T> it = this.<T>getAnnotationIndex(ts.docType).iterator(); List<T> list = new ArrayList<T>(); while (it.isValid()) { list.add(it.get()); it.moveToNext(); } for (int i = 0; i < list.size(); i++) { getIndexRepository().removeFS(list.get(i)); } return (T) createDocumentAnnotationNoRemove(length); } private <T extends Annotation> T createDocumentAnnotationNoRemove(int length) { T docAnnot = createDocumentAnnotationNoRemoveNoIndex(length); addFsToIndexes(docAnnot); return docAnnot; } public <T extends Annotation> T createDocumentAnnotationNoRemoveNoIndex(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); AnnotationFS docAnnot = createAnnotation(ts.docType, 0, length); docAnnot.setStringValue(ts.langFeat, CAS.DEFAULT_LANGUAGE_NAME); return (T) docAnnot; } public int ll_createDocumentAnnotation(int length) { final int fsRef = ll_createDocumentAnnotationNoIndex(0, length); ll_getIndexRepository().ll_addFS(fsRef); return fsRef; } public int ll_createDocumentAnnotationNoIndex(int begin, int end) { final TypeSystemImpl ts = getTypeSystemImpl(); int fsRef = ll_createAnnotation(ts.docType.getCode(), begin, end); ll_setStringValue(fsRef, ts.langFeat.getCode(), CAS.DEFAULT_LANGUAGE_NAME); return fsRef; } // For the "built-in" instance of Document Annotation, set the // "end" feature to be the length of the sofa string /** * updates the document annotation (only if the sofa's local string data != null) * setting the end feature to be the length of the sofa string, if any. * creates the document annotation if not present * only works if not in the base cas * */ public void updateDocumentAnnotation() { if (!mySofaIsValid() || this == this.svd.baseCAS) { return; } String newDoc = this.mySofaRef.getLocalStringData(); if (null != newDoc) { Annotation docAnnot = getDocumentAnnotationNoCreate(); if (docAnnot != null) { // use a local instance of the add-back memory because this may be called as a side effect of updating a sofa FSsTobeAddedback tobeAddedback = FSsTobeAddedback.createSingle(); boolean wasRemoved = this.checkForInvalidFeatureSetting( docAnnot, getTypeSystemImpl().endFeat.getCode(), tobeAddedback); docAnnot._setIntValueNfc(endFeatAdjOffset, newDoc.length()); if (wasRemoved) { tobeAddedback.addback(docAnnot); } } else { // not in the index (yet) createDocumentAnnotation(newDoc.length()); } } return; } /** * Generic issue: The returned document annotation could be either an instance of * DocumentAnnotation or an instance of Annotation - the Java cover class used for * annotations when JCas is not being used. */ @Override public <T extends AnnotationFS> T getDocumentAnnotation() { T docAnnot = (T) getDocumentAnnotationNoCreate(); if (null == docAnnot) { return (T) createDocumentAnnotationNoRemove(0); } else { return docAnnot; } } public <T extends AnnotationFS> T getDocumentAnnotationNoCreate() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } FSIterator<T> it = this.<T>getAnnotationIndex(getTypeSystemImpl().docType).iterator(); if (it.isValid()) { return it.get(); } return null; } /** * * @return the fs addr of the document annotation found via the index, or 0 if not there */ public int ll_getDocumentAnnotation() { if (this == this.svd.baseCAS) { // base CAS has no document return 0; } FSIterator<FeatureStructure> it = getIndexRepository().getIndex(CAS.STD_ANNOTATION_INDEX, getTypeSystemImpl().docType).iterator(); if (it.isValid()) { return it.get()._id(); } return 0; } @Override public String getDocumentLanguage() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return getDocumentAnnotation().getStringValue(getTypeSystemImpl().langFeat); } @Override public String getDocumentText() { return this.getSofaDataString(); } @Override public String getSofaDataString() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return mySofaIsValid() ? mySofaRef.getLocalStringData() : null; } @Override public FeatureStructure getSofaDataArray() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getLocalFSData() : null; } @Override public String getSofaDataURI() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaURI() : null; } @Override public InputStream getSofaDataStream() { if (this == this.svd.baseCAS) { // base CAS has no Sofa nothin return null; } // return mySofaRef.getSofaDataStream(); // this just goes to the next method return mySofaIsValid() ? this.getSofaDataStream(mySofaRef) : null; } @Override public String getSofaMimeType() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaMime() : null; } @Override public Sofa getSofa() { return mySofaRef; } /** * @return the addr of the sofaFS associated with this view, or 0 */ @Override public int ll_getSofa() { return mySofaIsValid() ? mySofaRef._id() : 0; } @Override public String getViewName() { return (this == getViewFromSofaNbr(1)) ? CAS.NAME_DEFAULT_SOFA : mySofaIsValid() ? mySofaRef.getSofaID() : null; } private boolean mySofaIsValid() { return this.mySofaRef != null; } void setDocTextFromDeserializtion(String text) { if (mySofaIsValid()) { SofaFS sofa = getSofaRef(); // creates sofa if doesn't already exist sofa.setLocalSofaData(text); } } @Override public void setDocumentLanguage(String languageCode) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "setDocumentLanguage(String)"); } Annotation docAnnot = getDocumentAnnotation(); FeatureImpl languageFeature = getTypeSystemImpl().langFeat; languageCode = Language.normalize(languageCode); boolean wasRemoved = this.checkForInvalidFeatureSetting(docAnnot, languageFeature.getCode(), this.getAddbackSingle()); docAnnot.setStringValue(getTypeSystemImpl().langFeat, languageCode); addbackSingleIfWasRemoved(wasRemoved, docAnnot); } private void setSofaThingsMime(Consumer<Sofa> c, String msg) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, msg); } Sofa sofa = getSofaRef(); c.accept(sofa); } @Override public void setDocumentText(String text) { setSofaDataString(text, "text"); } @Override public void setSofaDataString(String text, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setLocalSofaData(text, mime), "setSofaDataString(text, mime)"); } @Override public void setSofaDataArray(FeatureStructure array, String mime) { setSofaThingsMime(sofa -> sofa.setLocalSofaData(array, mime), "setSofaDataArray(FeatureStructure, mime)"); } @Override public void setSofaDataURI(String uri, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setRemoteSofaURI(uri, mime), "setSofaDataURI(String, String)"); } @Override public void setCurrentComponentInfo(ComponentInfo info) { // always store component info in base CAS this.svd.componentInfo = info; } ComponentInfo getCurrentComponentInfo() { return this.svd.componentInfo; } /** * @see org.apache.uima.cas.CAS#addFsToIndexes(FeatureStructure fs) */ @Override public void addFsToIndexes(FeatureStructure fs) { // if (fs instanceof AnnotationBaseFS) { // final CAS sofaView = ((AnnotationBaseFS) fs).getView(); // if (sofaView != this) { // CASRuntimeException e = new CASRuntimeException( // CASRuntimeException.ANNOTATION_IN_WRONG_INDEX, new String[] { fs.toString(), // sofaView.getSofa().getSofaID(), this.getSofa().getSofaID() }); // throw e; // } // } this.indexRepository.addFS(fs); } /** * @see org.apache.uima.cas.CAS#removeFsFromIndexes(FeatureStructure fs) */ @Override public void removeFsFromIndexes(FeatureStructure fs) { this.indexRepository.removeFS(fs); } /** * @param fs the AnnotationBase instance * @return the view associated with this FS where it could be indexed */ public CASImpl getSofaCasView(AnnotationBase fs) { return fs._casView; // Sofa sofa = fs.getSofa(); // // if (null != sofa && sofa != this.getSofa()) { // return (CASImpl) this.getView(sofa.getSofaNum()); // } // // /* Note: sofa == null means annotation created from low-level APIs, without setting sofa feature // * Ignore this for backwards compatibility */ // return this; } @Override public CASImpl ll_getSofaCasView(int id) { return getSofaCasView(getFsFromId_checked(id)); } // public Iterator<CAS> getViewIterator() { // List<CAS> viewList = new ArrayList<CAS>(); // // add initial view if it has no sofa // if (!((CASImpl) getInitialView()).mySofaIsValid()) { // viewList.add(getInitialView()); // } // // add views with Sofas // FSIterator<SofaFS> sofaIter = getSofaIterator(); // while (sofaIter.hasNext()) { // viewList.add(getView(sofaIter.next())); // } // return viewList.iterator(); // } /** * Creates the initial view (without a sofa) if not present * @return the number of views, excluding the base view, including the initial view (even if not initially present or no sofa) */ public int getNumberOfViews() { CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa int nbrSofas = this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); return initialView.mySofaIsValid() ? nbrSofas : 1 + nbrSofas; } public int getNumberOfSofas() { return this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator() */ @Override public <T extends CAS> Iterator<T> getViewIterator() { return new Iterator<T>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { return true; } return sofaIter.hasNext(); } @Override public T next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return (T) initialView; } return (T) getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * excludes initial view if its sofa is not valid * * @return iterator over all views except the base view */ public Iterator<CASImpl> getViewImplIterator() { return new Iterator<CASImpl>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { // set to false once iterator moves off of first value return true; } return sofaIter.hasNext(); } @Override public CASImpl next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return initialView; } return getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * iterate over all views in view order (by view number) * @param processViews */ void forAllViews(Consumer<CASImpl> processViews) { final int numViews = this.getNumberOfViews(); for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) { CASImpl view = (viewNbr == 1) ? getInitialView() : (CASImpl) getView(viewNbr); processViews.accept(view); } // // Iterator<CASImpl> it = getViewImplIterator(); // while (it.hasNext()) { // processViews.accept(it.next()); // } } void forAllSofas(Consumer<Sofa> processSofa) { FSIterator<Sofa> it = getSofaIterator(); while (it.hasNext()) { processSofa.accept(it.nextNvc()); } } /** * Excludes base view's ir, * Includes the initial view's ir only if it has a sofa defined * @param processIr the code to execute */ void forAllIndexRepos(Consumer<FSIndexRepositoryImpl> processIr) { final int numViews = this.getViewCount(); for (int viewNum = 1; viewNum <= numViews; viewNum++) { processIr.accept(this.getSofaIndexRepository(viewNum)); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator(java.lang.String) */ @Override public Iterator<CAS> getViewIterator(String localViewNamePrefix) { // do sofa mapping for current component String absolutePrefix = null; if (getCurrentComponentInfo() != null) { absolutePrefix = getCurrentComponentInfo().mapToSofaID(localViewNamePrefix); } if (absolutePrefix == null) { absolutePrefix = localViewNamePrefix; } // find Sofas with this prefix List<CAS> viewList = new ArrayList<CAS>(); FSIterator<Sofa> sofaIter = getSofaIterator(); while (sofaIter.hasNext()) { SofaFS sofa = sofaIter.next(); String sofaId = sofa.getSofaID(); if (sofaId.startsWith(absolutePrefix)) { if ((sofaId.length() == absolutePrefix.length()) || (sofaId.charAt(absolutePrefix.length()) == '.')) { viewList.add(getView(sofa)); } } } return viewList.iterator(); } /** * protectIndexes * * Within the scope of protectIndexes, * feature updates are checked, and if found to be a key, and the FS is in a corruptable index, * then the FS is removed from the indexes (in all necessary views) (perhaps multiple times * if the FS was added to the indexes multiple times), and this removal is recorded on * an new instance of FSsTobeReindexed appended to fssTobeAddedback. * * Later, when the protectIndexes is closed, the tobe items are added back to the indies. */ @Override public AutoCloseable protectIndexes() { FSsTobeAddedback r = FSsTobeAddedback.createMultiple(this); svd.fssTobeAddedback.add(r); return r; } void dropProtectIndexesLevel () { svd.fssTobeAddedback.remove(svd.fssTobeAddedback.size() -1); } /** * This design is to support normal operations where the * addbacks could be nested * It also handles cases where nested ones were inadvertently left open * Three cases: * 1) the addbacks are the last element in the stack * - remove it from the stack * 2) the addbacks are (no longer) in the list * - leave stack alone * 3) the addbacks are in the list but not at the end * - remove it and all later ones * * If the "withProtectedindexes" approach is used, it guarantees proper * nesting, but the Runnable can't throw checked exceptions. * * You can do your own try-finally blocks (or use the try with resources * form in Java 8 to do a similar thing with no restrictions on what the * body can contain. * * @param addbacks */ void addbackModifiedFSs (FSsTobeAddedback addbacks) { final List<FSsTobeAddedback> listOfAddbackInfos = svd.fssTobeAddedback; if (listOfAddbackInfos.get(listOfAddbackInfos.size() - 1) == addbacks) { listOfAddbackInfos.remove(listOfAddbackInfos.size()); } else { int pos = listOfAddbackInfos.indexOf(addbacks); if (pos >= 0) { for (int i = listOfAddbackInfos.size() - 1; i > pos; i--) { FSsTobeAddedback toAddBack = listOfAddbackInfos.remove(i); toAddBack.addback(); } } } addbacks.addback(); } /** * * @param r an inner block of code to be run with */ @Override public void protectIndexes(Runnable r) { AutoCloseable addbacks = protectIndexes(); try { r.run(); } finally { addbackModifiedFSs((FSsTobeAddedback) addbacks); } } /** * The current implementation only supports 1 marker call per * CAS. Subsequent calls will throw an error. * * The design is intended to support (at some future point) * multiple markers; for this to work, the intent is to * extend the MarkerImpl to keep track of indexes into * these IntVectors specifying where that marker starts/ends. */ @Override public Marker createMarker() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } this.svd.trackingMark = new MarkerImpl(this.getLastUsedFsId() + 1, this); if (this.svd.modifiedPreexistingFSs == null) { this.svd.modifiedPreexistingFSs = new IdentityHashMap<>(); } if (this.svd.modifiedPreexistingFSs.size() > 0) { errorMultipleMarkers(); } if (this.svd.trackingMarkList == null) { this.svd.trackingMarkList = new ArrayList<MarkerImpl>(); } else {errorMultipleMarkers();} this.svd.trackingMarkList.add(this.svd.trackingMark); return this.svd.trackingMark; } private void errorMultipleMarkers() { throw new CASRuntimeException(CASRuntimeException.MULTIPLE_CREATE_MARKER); } // made public https://issues.apache.org/jira/browse/UIMA-2478 public MarkerImpl getCurrentMark() { return this.svd.trackingMark; } /** * * @return an array of FsChange items, one per modified Fs, * sorted in order of fs._id */ FsChange[] getModifiedFSList() { final Map<TOP, FsChange> mods = this.svd.modifiedPreexistingFSs; FsChange[] r = mods.values().toArray(new FsChange[mods.size()]); Arrays.sort(r, 0, mods.size(), (c1, c2) -> Integer.compare(c1.fs._id, c2.fs._id)); return r; } boolean isInModifiedPreexisting(TOP fs) { return this.svd.modifiedPreexistingFSs.containsKey(fs); } @Override public String toString() { String sofa = (mySofaRef == null) ? (isBaseCas() ? "Base CAS" : "_InitialView or no Sofa") : mySofaRef.getSofaID(); // (mySofaRef == 0) ? "no Sofa" : return this.getClass().getSimpleName() + ":" + getCasId() + "[view: " + sofa + "]"; } int getCasResets() { return svd.casResets.get(); } int getCasId() { return svd.casId; } final public int getNextFsId(TOP fs) { return svd.getNextFsId(fs); } public void adjustLastFsV2size(int arrayLength) { svd.lastFsV2Size += 1 + arrayLength; // 1 is for array length value } /** * Test case use * @param fss the FSs to include in the id 2 fs map */ public void setId2FSs(FeatureStructure ... fss) { for (FeatureStructure fs : fss) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } else { svd.id2fs.put((TOP)fs); } } } // Not currently used // public Int2ObjHashMap<TOP> getId2FSs() { // return svd.id2fs.getId2fs(); // } // final private int getNextFsId() { // return ++ svd.fsIdGenerator; // } final public int getLastUsedFsId() { return svd.fsIdGenerator; } /** * Call this to capture the current value of fsIdGenerator and make it * available to other threads. * * Must be called on a thread that has been synchronized with the thread used for creating FSs for this CAS. */ final public void captureLastFsIdForOtherThread() { svd.fsIdLastValue.set(svd.fsIdGenerator); } public <T extends TOP> T getFsFromId(int id) { return (T) this.svd.id2fs.get(id); } // /** // * plus means all reachable, plus maybe others not reachable but not yet gc'd // * @param action - // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action) { // this.svd.id2fs.walkReachablePlusFSsSorted(action); // } // /** // * called for delta serialization - walks just the new items above the line // * @param action - // * @param fromId - the id of the first item to walk from // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action, int fromId) { // this.svd.id2fs.walkReachablePlueFSsSorted(action, fromId); // } /** * find all of the FSs via the indexes plus what's reachable. * sort into order by id, * * Apply the action to those * Return the list of sorted FSs * * @param action_filtered action to perform on each item after filtering * @param mark null or the mark * @param includeFilter null or a filter (exclude items not in other type system) * @param typeMapper null or how to map to other type system, used to skip things missing in other type system * @return sorted list of all found items (ignoring mark) */ public List<TOP> walkReachablePlusFSsSorted( Consumer<TOP> action_filtered, MarkerImpl mark, Predicate<TOP> includeFilter, CasTypeSystemMapper typeMapper) { List<TOP> all = new AllFSs(this, mark, includeFilter, typeMapper).getAllFSsSorted(); List<TOP> filtered = filterAboveMark(all, mark); for (TOP fs : filtered) { action_filtered.accept(fs); } return all; } static List<TOP> filterAboveMark(List<TOP> all, MarkerImpl mark) { if (null == mark) { return all; } int c = Collections.binarySearch(all, TOP._createSearchKey(mark.nextFSId), (fs1, fs2) -> Integer.compare(fs1._id, fs2._id)); if (c < 0) { c = (-c) - 1; } return all.subList(c, all.size()); } // /** // * Get the Java class corresponding to a particular type // * Only valid after type system commit // * // * @param type // * @return // */ // public <T extends FeatureStructure> Class<T> getClass4Type(Type type) { // TypeSystemImpl tsi = getTypeSystemImpl(); // if (!tsi.isCommitted()) { // throw new CASRuntimeException(CASRuntimeException.GET_CLASS_FOR_TYPE_BEFORE_TS_COMMIT); // } // // } public static boolean isSameCAS(CAS c1, CAS c2) { CASImpl ci1 = (CASImpl) c1.getLowLevelCAS(); CASImpl ci2 = (CASImpl) c2.getLowLevelCAS(); return ci1.getBaseCAS() == ci2.getBaseCAS(); } public boolean isInCAS(FeatureStructure fs) { return ((TOP)fs)._casView.getBaseCAS() == this.getBaseCAS(); } // /** // * // * @param typecode - // * @return Object that can be cast to either a 2 or 3 arg createFs functional interface // * FsGenerator or FsGeneratorArray // */ // private Object getFsGenerator(int typecode) { // return getTypeSystemImpl().getGenerator(typecode); // } public final void checkArrayPreconditions(int len) throws CASRuntimeException { // Check array size. if (len < 0) { throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } public EmptyFSList getEmptyFSList() { if (null == svd.emptyFSList) { svd.emptyFSList = new EmptyFSList(getTypeSystemImpl().fsEListType, this); } return svd.emptyFSList; } public EmptyFloatList getEmptyFloatList() { if (null == svd.emptyFloatList) { svd.emptyFloatList = new EmptyFloatList(getTypeSystemImpl().floatEListType, this); } return svd.emptyFloatList; } public EmptyIntegerList getEmptyIntegerList() { if (null == svd.emptyIntegerList) { svd.emptyIntegerList = new EmptyIntegerList(getTypeSystemImpl().intEListType, this); } return svd.emptyIntegerList; } public EmptyStringList getEmptyStringList() { if (null == svd.emptyStringList) { svd.emptyStringList = new EmptyStringList(getTypeSystemImpl().stringEListType, this); } return svd.emptyStringList; } /** * @param rangeCode special codes for serialization use only * @return the empty list (shared) corresponding to the type */ public EmptyList getEmptyList(int rangeCode) { return (rangeCode == CasSerializerSupport.TYPE_CLASS_INTLIST) ? getEmptyIntegerList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_FLOATLIST) ? getEmptyFloatList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_STRINGLIST) ? getEmptyStringList() : getEmptyFSList(); } /** * Get an empty list from the type code of a list * @param rangeCode - * @return - */ public EmptyList getEmptyListFromTypeCode(int rangeCode) { switch (rangeCode) { case fsListTypeCode: case fsEListTypeCode: case fsNeListTypeCode: return getEmptyFSList(); case floatListTypeCode: case floatEListTypeCode: case floatNeListTypeCode: return getEmptyFloatList(); case intListTypeCode: case intEListTypeCode: case intNeListTypeCode: return getEmptyIntegerList(); case stringListTypeCode: case stringEListTypeCode: case stringNeListTypeCode: return getEmptyStringList(); default: throw new IllegalArgumentException(); } } // /** // * Copies a feature, from one fs to another // * FSs may belong to different CASes, but must have the same type system // * Features must have compatible ranges // * The target must not be indexed // * The target must be a "new" (above the "mark") FS // * @param fsSrc source FS // * @param fi Feature to copy // * @param fsTgt target FS // */ // public static void copyFeature(TOP fsSrc, FeatureImpl fi, TOP fsTgt) { // if (!copyFeatureExceptFsRef(fsSrc, fi, fsTgt, fi)) { // if (!fi.isAnnotBaseSofaRef) { // fsTgt._setFeatureValueNcNj(fi, fsSrc._getFeatureValueNc(fi)); // } // } // } /** * Copies a feature from one fs to another * FSs may be in different type systems * Doesn't copy a feature ref, but instead returns false. * This is because feature refs can't cross CASes * @param fsSrc source FS * @param fiSrc feature in source to copy * @param fsTgt target FS * @param fiTgt feature in target to set * @return false if feature is an fsRef */ public static boolean copyFeatureExceptFsRef(TOP fsSrc, FeatureImpl fiSrc, TOP fsTgt, FeatureImpl fiTgt) { switch (fiSrc.getRangeImpl().getCode()) { case booleanTypeCode : fsTgt._setBooleanValueNcNj( fiTgt, fsSrc._getBooleanValueNc( fiSrc)); break; case byteTypeCode : fsTgt._setByteValueNcNj( fiTgt, fsSrc._getByteValueNc( fiSrc)); break; case shortTypeCode : fsTgt._setShortValueNcNj( fiTgt, fsSrc._getShortValueNc( fiSrc)); break; case intTypeCode : fsTgt._setIntValueNcNj( fiTgt, fsSrc._getIntValueNc( fiSrc)); break; case longTypeCode : fsTgt._setLongValueNcNj( fiTgt, fsSrc._getLongValueNc( fiSrc)); break; case floatTypeCode : fsTgt._setFloatValueNcNj( fiTgt, fsSrc._getFloatValueNc( fiSrc)); break; case doubleTypeCode : fsTgt._setDoubleValueNcNj( fiTgt, fsSrc._getDoubleValueNc( fiSrc)); break; case stringTypeCode : fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // case javaObjectTypeCode : fsTgt._setJavaObjectValueNcNj(fiTgt, fsSrc.getJavaObjectValue(fiSrc)); break; // skip setting sofaRef - it's final and can't be set default: if (fiSrc.getRangeImpl().isStringSubtype()) { fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // does substring range check } return false; } // end of switch return true; } public static CommonArrayFS copyArray(TOP srcArray) { CommonArrayFS srcCA = (CommonArrayFS) srcArray; CommonArrayFS copy = (CommonArrayFS) srcArray._casView.createArray(srcArray._getTypeImpl(), srcCA.size()); copy.copyValuesFrom(srcCA); return copy; } public BinaryCasSerDes getBinaryCasSerDes() { return svd.bcsd; } /** * @return the saved CommonSerDesSequential info */ CommonSerDesSequential getCsds() { return svd.csds; } void setCsds(CommonSerDesSequential csds) { svd.csds = csds; } CommonSerDesSequential newCsds() { return svd.csds = new CommonSerDesSequential(this.getBaseCAS()); } /** * A space-freeing optimization for use cases where (multiple) delta CASes are being deserialized into this CAS and merged. */ public void deltaMergesComplete() { svd.csds = null; } /****************************************** * PEAR support * Don't modify the type system because it is in use on multiple threads * * Handling of id2fs for low level APIs: * FSs in id2fs map are the outer non-pear ones * Any gets do pear conversion if needed. * ******************************************/ /** * Convert base FS to Pear equivalent * 3 cases: * 1) no trampoline needed, no conversion, return the original fs * 2) trampoline already exists - return that one * 3) create new trampoline * @param aFs * @return */ static <T extends FeatureStructure> T pearConvert(T aFs) { if (null == aFs) { return null; } final TOP fs = (TOP) aFs; final CASImpl view = fs._casView; final TypeImpl ti = fs._getTypeImpl(); final FsGenerator3 generator = view.svd.generators[ti.getCode()]; if (null == generator) { return aFs; } return (T) view.pearConvert(fs, generator); } /** * Inner method - after determining there is a generator * First see if already have generated the pear version, and if so, * use that. * Otherwise, create the pear version and save in trampoline table * @param fs * @param g * @return */ private TOP pearConvert(TOP fs, FsGenerator3 g) { return svd.id2tramp.putIfAbsent(fs._id, k -> { svd.reuseId = k; // create new FS using base FS's ID pearBaseFs = fs; TOP r; // createFS below is modified because of pearBaseFs non-null to // "share" the int and data arrays try { r = g.createFS(fs._getTypeImpl(), this); } finally { svd.reuseId = 0; pearBaseFs = null; } assert r != null; if (r instanceof UimaSerializable) { throw new UnsupportedOperationException( "Pears with Alternate implementations of JCas classes implementing UimaSerializable not supported."); // ((UimaSerializable) fs)._save_to_cas_data(); // updates in r too // ((UimaSerializable) r)._init_from_cas_data(); } return r; }); } /** * Given a trampoline FS, return the corresponding base Fs * Supports adding Fs (which must be a non-trampoline version) to indexes * @param fs trampoline fs * @return the corresponding base fs */ <T extends TOP> T getBaseFsFromTrampoline(T fs) { TOP r = svd.id2base.get(fs._id); assert r != null; return (T) r; } /* ***************************************** * DEBUGGING and TRACING ******************************************/ public void traceFSCreate(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceFSflush(); } // normally commented-out for matching with v2 // // mark annotations created by subiterator // if (fs._getTypeCode() == TypeSystemConstants.annotTypeCode) { // StackTraceElement[] stktr = Thread.currentThread().getStackTrace(); // if (stktr.length > 7 && stktr[6].getClassName().equals("org.apache.uima.cas.impl.Subiterator")) { // b.append('*'); // } // } svd.id2addr.add(svd.nextId2Addr); svd.nextId2Addr += fs._getTypeImpl().getFsSpaceReq((TOP)fs); traceFSfs(fs); svd.traceFSisCreate = true; if (fs._getTypeImpl().isArray()) { b.append(" l:").append(((CommonArrayFS)fs).size()); } } void traceFSfs(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; svd.traceFSid = fs._id; b.append("c:").append(String.format("%-3d", getCasId())); String viewName = fs._casView.getViewName(); if (null == viewName) { viewName = "base"; } b.append(" v:").append(Misc.elide(viewName, 8)); b.append(" i:").append(String.format("%-5s", geti2addr(fs._id))); b.append(" t:").append(Misc.elide(fs._getTypeImpl().getShortName(), 10)); } void traceIndexMod(boolean isAdd, TOP fs, boolean isAddbackOrSkipBag) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append(isAdd ? (isAddbackOrSkipBag ? "abk_idx " : "add_idx ") : (isAddbackOrSkipBag ? "rmv_auto_idx " : "rmv_norm_idx ")); // b.append(fs.toString()); b.append(fs._getTypeImpl().getShortName()).append(":").append(fs._id); if (fs instanceof Annotation) { Annotation ann = (Annotation) fs; b.append(" begin: ").append(ann.getBegin()); b.append(" end: ").append(ann.getEnd()); b.append(" txt: \"").append(Misc.elide(ann.getCoveredText(), 10)).append("\""); } traceOut.println(b); } void traceCowCopy(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowCopyUse(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy-used:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowReinit(String kind, FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-redo: "); b.append(kind); b.append(" i: ").append(index); b.append(" c: "); b.append(Misc.getCaller()); traceOut.println(b); } /** only used for tracing, enables tracing 2 slots for long/double */ private FeatureImpl prevFi; void traceFSfeat(FeatureStructureImplC fs, FeatureImpl fi, Object v) { //debug FeatureImpl originalFi = fi; StringBuilder b = svd.traceFScreationSb; assert (b.length() > 0); if (fs._id != svd.traceFSid) { traceFSfeatUpdate(fs); } if (fi == null) { // happens on 2nd setInt call from cas copier copyfeatures for Long / Double switch(prevFi.getSlotKind()) { case Slot_DoubleRef: v = fs._getDoubleValueNc(prevFi); break; // correct double and long case Slot_LongRef: v = fs._getLongValueNc(prevFi); break; // correct double and long default: Misc.internalError(); } fi = prevFi; prevFi = null; } else { prevFi = fi; } String fn = fi.getShortName(); // correct calls done by cas copier fast loop if (fi.getSlotKind() == SlotKind.Slot_DoubleRef) { if (v instanceof Integer) { return; // wait till the next part is traced } else if (v instanceof Long) { v = CASImpl.long2double((long)v); } } if (fi.getSlotKind() == SlotKind.Slot_LongRef && (v instanceof Integer)) { return; // output done on the next int call } String fv = getTraceRepOfObj(fi, v); // if (geti2addr(fs._id).equals("79") && // fn.equals("sofa")) { // new Throwable().printStackTrace(traceOut); // } // // debug // if (fn.equals("lemma") && // fv.startsWith("Lemma:") && // debug1cnt < 2) { // debug1cnt ++; // traceOut.println("setting lemma feat:"); // new Throwable().printStackTrace(traceOut); // } // debug // if (fs._getTypeImpl().getShortName().equals("Passage") && // "score".equals(fn) && // debug2cnt < 5) { // debug2cnt++; // traceOut.println("setting score feat in Passage"); // new Throwable().printStackTrace(traceOut); // } // debug int i_v = Math.max(0, 10 - fn.length()); int i_n = Math.max(0, 10 - fv.length()); fn = Misc.elide(fn, 10 + i_n, false); fv = Misc.elide(fv, 10 + i_v, false); // debug // if (!svd.traceFSisCreate && fn.equals("uninf.dWord") && fv.equals("XsgTokens")) { // traceOut.println("debug uninf.dWord:XsgTokens: " + Misc.getCallers(3, 10)); // } b.append(' ').append(Misc.elide(fn + ':' + fv, 21)); // value of a feature: // - "null" or // - if FS: type:id (converted to addr) // - v.toString() } private static int debug2cnt = 0; /** * @param v * @return value of the feature: * "null" or if FS: type:id (converted to addr) or v.toString() * Note: white space in strings converted to "_' characters */ private String getTraceRepOfObj(FeatureImpl fi, Object v) { if (v instanceof TOP) { TOP fs = (TOP) v; return Misc.elide(fs.getType().getShortName(), 5, false) + ':' + geti2addr(fs._id); } if (v == null) return "null"; if (v instanceof String) { String s = Misc.elide((String) v, 50, false); return Misc.replaceWhiteSpace(s, "_"); } if (v instanceof Integer) { int iv = (int) v; switch (fi.getSlotKind()) { case Slot_Boolean: return (iv == 1) ? "true" : "false"; case Slot_Byte: case Slot_Short: case Slot_Int: return Integer.toString(iv); case Slot_Float: return Float.toString(int2float(iv)); } } if (v instanceof Long) { long vl = (long) v; return (fi.getSlotKind() == SlotKind.Slot_DoubleRef) ? Double.toString(long2double(vl)) : Long.toString(vl); } return Misc.replaceWhiteSpace(v.toString(), "_"); } private String geti2addr(int id) { if (id >= svd.id2addr.size()) { return Integer.toString(id) + '!'; } return Integer.toString(svd.id2addr.get(id)); } void traceFSfeatUpdate(FeatureStructureImplC fs) { traceFSflush(); traceFSfs(fs); svd.traceFSisCreate = false; } public StringBuilder traceFSflush() { if (!traceFSs) return null; StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceOut.println((svd.traceFSisCreate ? "cr: " : "up: ") + b); b.setLength(0); svd.traceFSisCreate = false; } return b; } private static class MeasureSwitchType { TypeImpl oldType; TypeImpl newType; String oldJCasClassName; String newJCasClassName; int count = 0; boolean newSubsumesOld; boolean oldSubsumesNew; long scantime = 0; MeasureSwitchType(TypeImpl oldType, TypeImpl newType) { this.oldType = oldType; this.oldJCasClassName = oldType.getJavaClass().getName(); this.newType = newType; this.newJCasClassName = newType.getJavaClass().getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((newJCasClassName == null) ? 0 : newJCasClassName.hashCode()); result = prime * result + ((newType == null) ? 0 : newType.hashCode()); result = prime * result + ((oldJCasClassName == null) ? 0 : oldJCasClassName.hashCode()); result = prime * result + ((oldType == null) ? 0 : oldType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MeasureSwitchType)) { return false; } MeasureSwitchType other = (MeasureSwitchType) obj; if (newJCasClassName == null) { if (other.newJCasClassName != null) { return false; } } else if (!newJCasClassName.equals(other.newJCasClassName)) { return false; } if (newType == null) { if (other.newType != null) { return false; } } else if (!newType.equals(other.newType)) { return false; } if (oldJCasClassName == null) { if (other.oldJCasClassName != null) { return false; } } else if (!oldJCasClassName.equals(other.oldJCasClassName)) { return false; } if (oldType == null) { if (other.oldType != null) { return false; } } else if (!oldType.equals(other.oldType)) { return false; } return true; } } private static final Map<MeasureSwitchType, MeasureSwitchType> measureSwitches = new HashMap<>(); static { if (MEASURE_SETINT) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("debug Switch Types dump, # entries: " + measureSwitches.size()); int s1 = 0, s2 = 0, s3 = 0; for (MeasureSwitchType mst : measureSwitches.keySet()) { s1 = Math.max(s1, mst.oldType.getName().length()); s2 = Math.max(s2, mst.newType.getName().length()); s3 = Math.max(s3, mst.oldJCasClassName.length()); } for (MeasureSwitchType mst : measureSwitches.keySet()) { System.out.format("count: %,6d scantime = %,7d ms, subsumes: %s %s, type: %-" + s1 + "s newType: %-" + s2 + "s, cl: %-" + s3 + "s, newCl: %s%n", mst.count, mst.scantime / 1000000, mst.newSubsumesOld ? "n>o" : " ", mst.oldSubsumesNew ? "o>w" : " ", mst.oldType.getName(), mst.newType.getName(), mst.oldJCasClassName, mst.newJCasClassName); } // if (traceFSs) { // System.err.println("debug closing traceFSs output"); // traceOut.close(); // } }, "Dump SwitchTypes")); } // this is definitely needed if (traceFSs) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("closing traceOut"); traceOut.close(); }, "close trace output")); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#setCAS(org.apache.uima.cas.CAS) * Internal use Never called Kept because it's in the interface. */ @Override @Deprecated public void setCAS(CAS cas) {} /** * @return true if in Pear context, or external context outside AnalysisEngine having a UIMA Extension class loader * e.g., if calling a call-back routine loaded outside the AE. */ boolean inPearContext() { return svd.previousJCasClassLoader != null; } /** * Pear context suspended while creating a base version, when we need to create a new FS * (we need to create both the base and the trampoline version) */ private void suspendPearContext() { svd.suspendPreviousJCasClassLoader = svd.previousJCasClassLoader; svd.previousJCasClassLoader = null; } private void restorePearContext() { svd.previousJCasClassLoader = svd.suspendPreviousJCasClassLoader; } /** * * @return the initial heap size specified or defaulted */ public int getInitialHeapSize() { return this.svd.initialHeapSize; } // backwards compatibility - reinit calls // just the public apis /** * Deserializer for Java-object serialized instance of CASSerializer * Used by Soap * @param ser - The instance to convert back to a CAS */ public void reinit(CASSerializer ser) { svd.bcsd.reinit(ser); } /** * Deserializer for CASCompleteSerializer instances - includes type system and index definitions * Never delta * @param casCompSer - */ public void reinit(CASCompleteSerializer casCompSer) { svd.bcsd.reinit(casCompSer); } /** * --------------------------------------------------------------------- * see Blob Format in CASSerializer * * This reads in and deserializes CAS data from a stream. Byte swapping may be * needed if the blob is from C++ -- C++ blob serialization writes data in * native byte order. * * Supports delta deserialization. For that, the the csds from the serialization event must be used. * * @param istream - * @return - the format of the input stream detected * @throws CASRuntimeException wraps IOException */ public SerialFormat reinit(InputStream istream) throws CASRuntimeException { return svd.bcsd.reinit(istream); } void maybeHoldOntoFS(FeatureStructureImplC fs) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } } public void swapInPearVersion(Object[] a) { if (!inPearContext()) { return; } for (int i = 0; i < a.length; i++) { Object ao = a[i]; if (ao instanceof TOP) { a[i] = pearConvert((TOP) ao); } } } public Collection<?> collectNonPearVersions(Collection<?> c) { if (c.size() == 0 || !inPearContext()) { return c; } ArrayList<Object> items = new ArrayList<>(c.size()); for (Object o : c) { if (o instanceof TOP) { items.add(pearConvert((TOP) o)); } } return items; } public <T> Spliterator<T> makePearAware(Spliterator<T> baseSi) { if (!inPearContext()) { return baseSi; } return new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return baseSi.tryAdvance(item -> action.accept( (item instanceof TOP) ? (T) pearConvert((TOP)item) : item)); } @Override public Spliterator<T> trySplit() { return baseSi.trySplit(); } @Override public long estimateSize() { return baseSi.estimateSize(); } @Override public int characteristics() { return baseSi.characteristics(); } }; } // int allocIntData(int sz) { // // if (sz > INT_DATA_FOR_ALLOC_SIZE / 4) { // returnIntDataForAlloc = new int[sz]; // return 0; // } // // if (sz + nextIntDataOffsetForAlloc > INT_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // nextIntDataOffsetForAlloc = 0; // } // int r = nextIntDataOffsetForAlloc; // nextIntDataOffsetForAlloc += sz; // returnIntDataForAlloc = currentIntDataForAlloc; // return r; // } // // int[] getReturnIntDataForAlloc() { // return returnIntDataForAlloc; // } // // int allocRefData(int sz) { // // if (sz > REF_DATA_FOR_ALLOC_SIZE / 4) { // returnRefDataForAlloc = new Object[sz]; // return 0; // } // // if (sz + nextRefDataOffsetForAlloc > REF_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // nextRefDataOffsetForAlloc = 0; // } // int r = nextRefDataOffsetForAlloc; // nextRefDataOffsetForAlloc += sz; // returnRefDataForAlloc = currentRefDataForAlloc; // return r; // } // // Object[] getReturnRefDataForAlloc() { // return returnRefDataForAlloc; // } }
uimaj-core/src/main/java/org/apache/uima/cas/impl/CASImpl.java
/* * 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.uima.cas.impl; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Spliterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; import org.apache.uima.UIMAFramework; import org.apache.uima.UIMARuntimeException; import org.apache.uima.UimaSerializable; import org.apache.uima.cas.AbstractCas_ImplBase; import org.apache.uima.cas.ArrayFS; import org.apache.uima.cas.BooleanArrayFS; import org.apache.uima.cas.ByteArrayFS; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.cas.CASRuntimeException; import org.apache.uima.cas.CasOwner; import org.apache.uima.cas.CommonArrayFS; import org.apache.uima.cas.ComponentInfo; import org.apache.uima.cas.ConstraintFactory; import org.apache.uima.cas.DoubleArrayFS; import org.apache.uima.cas.FSIndex; import org.apache.uima.cas.FSIndexRepository; import org.apache.uima.cas.FSIterator; import org.apache.uima.cas.FSMatchConstraint; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeaturePath; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.FeatureValuePath; import org.apache.uima.cas.FloatArrayFS; import org.apache.uima.cas.IntArrayFS; import org.apache.uima.cas.LongArrayFS; import org.apache.uima.cas.Marker; import org.apache.uima.cas.SerialFormat; import org.apache.uima.cas.ShortArrayFS; import org.apache.uima.cas.SofaFS; import org.apache.uima.cas.SofaID; import org.apache.uima.cas.StringArrayFS; import org.apache.uima.cas.Type; import org.apache.uima.cas.TypeSystem; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.admin.CASFactory; import org.apache.uima.cas.admin.CASMgr; import org.apache.uima.cas.admin.FSIndexComparator; import org.apache.uima.cas.admin.FSIndexRepositoryMgr; import org.apache.uima.cas.admin.TypeSystemMgr; import org.apache.uima.cas.impl.FSsTobeAddedback.FSsTobeAddedbackSingle; import org.apache.uima.cas.impl.SlotKinds.SlotKind; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.cas.text.Language; import org.apache.uima.internal.util.IntVector; import org.apache.uima.internal.util.Misc; import org.apache.uima.internal.util.PositiveIntSet; import org.apache.uima.internal.util.PositiveIntSet_impl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.AnnotationBase; import org.apache.uima.jcas.cas.BooleanArray; import org.apache.uima.jcas.cas.ByteArray; import org.apache.uima.jcas.cas.DoubleArray; import org.apache.uima.jcas.cas.EmptyFSList; import org.apache.uima.jcas.cas.EmptyFloatList; import org.apache.uima.jcas.cas.EmptyIntegerList; import org.apache.uima.jcas.cas.EmptyList; import org.apache.uima.jcas.cas.EmptyStringList; import org.apache.uima.jcas.cas.FSArray; import org.apache.uima.jcas.cas.FloatArray; import org.apache.uima.jcas.cas.IntegerArray; import org.apache.uima.jcas.cas.LongArray; import org.apache.uima.jcas.cas.ShortArray; import org.apache.uima.jcas.cas.Sofa; import org.apache.uima.jcas.cas.StringArray; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.impl.JCasHashMap; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.util.Level; /** * Implements the CAS interfaces. This class must be public because we need to * be able to create instance of it from outside the package. Use at your own * risk. May change without notice. * */ public class CASImpl extends AbstractCas_ImplBase implements CAS, CASMgr, LowLevelCAS, TypeSystemConstants { public static final boolean IS_USE_V2_IDS = false; // if false, ids increment by 1 private static final boolean trace = false; // debug public static final boolean traceFSs = false; // debug - trace FS creation and update public static final boolean traceCow = false; // debug - trace copy on write actions, index adds / deletes private static final String traceFile = "traceFSs.log.txt"; private static final PrintStream traceOut; static { try { if (traceFSs) { System.out.println("Creating traceFSs file in directory " + System.getProperty("user.dir")); traceOut = traceFSs ? new PrintStream(new BufferedOutputStream(new FileOutputStream(traceFile, false))) : null; } else { traceOut = null; } } catch (Exception e) { throw new RuntimeException(e); } } private static final boolean MEASURE_SETINT = false; // debug static final AtomicInteger casIdProvider = new AtomicInteger(0); // Notes on the implementation // --------------------------- // Floats are handled by casting them to ints when they are stored // in the heap. Conveniently, 0 casts to 0.0f, which is the default // value. public static final int NULL = 0; // Boolean scalar values are stored as ints in the fs heap. // TRUE is 1 and false is 0. public static final int TRUE = 1; public static final int FALSE = 0; public static final int DEFAULT_INITIAL_HEAP_SIZE = 500_000; public static final int DEFAULT_RESET_HEAP_SIZE = 5_000_000; /** * The UIMA framework detects (unless disabled, for high performance) updates to indexed FS which update * key values used as keys in indexes. Normally the framework will protect against index corruption by * temporarily removing the FS from the indexes, then do the update to the feature value, and then addback * the changed FS. * <p> * Users can use the protectIndexes() methods to explicitly control this remove - add back cycle, for instance * to "batch" together several updates to multiple features in a FS. * <p> * Some build processes may want to FAIL if any unprotected updates of this kind occur, instead of having the * framework silently recover them. This is enabled by having the framework throw an exception; this is controlled * by this global JVM property, which, if defined, causes the framework to throw an exception rather than recover. * */ public static final String THROW_EXCEPTION_FS_UPDATES_CORRUPTS = "uima.exception_when_fs_update_corrupts_index"; // public for test case use public static boolean IS_THROW_EXCEPTION_CORRUPT_INDEX = Misc.getNoValueSystemProperty(THROW_EXCEPTION_FS_UPDATES_CORRUPTS); /** * Define this JVM property to enable checking for invalid updates to features which are used as * keys by any index. * <ul> * <li>The following are the same: -Duima.check_invalid_fs_updates and -Duima.check_invalid_fs_updates=true</li> * </ul> */ public static final String REPORT_FS_UPDATES_CORRUPTS = "uima.report_fs_update_corrupts_index"; private static final boolean IS_REPORT_FS_UPDATE_CORRUPTS_INDEX = IS_THROW_EXCEPTION_CORRUPT_INDEX || Misc.getNoValueSystemProperty(REPORT_FS_UPDATES_CORRUPTS); /** * Set this JVM property to false for high performance, (no checking); * insure you don't have the report flag (above) turned on - otherwise it will force this to "true". */ public static final String DISABLE_PROTECT_INDEXES = "uima.disable_auto_protect_indexes"; /** * the protect indexes flag is on by default, but may be turned of via setting the property. * * This is overridden if a report is requested or the exception detection is on. */ private static final boolean IS_DISABLED_PROTECT_INDEXES = Misc.getNoValueSystemProperty(DISABLE_PROTECT_INDEXES) && !IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && !IS_THROW_EXCEPTION_CORRUPT_INDEX; public static final String ALWAYS_HOLD_ONTO_FSS = "uima.enable_id_to_feature_structure_map_for_all_fss"; static final boolean IS_ALWAYS_HOLD_ONTO_FSS = // debug Misc.getNoValueSystemProperty(ALWAYS_HOLD_ONTO_FSS); // private static final int REF_DATA_FOR_ALLOC_SIZE = 1024; // private static final int INT_DATA_FOR_ALLOC_SIZE = 1024; // // this next seemingly non-sensical static block // is to force the classes needed by Eclipse debugging to load // otherwise, you get a com.sun.jdi.ClassNotLoadedException when // the class is used as part of formatting debugging messages static { new DebugNameValuePair(null, null); new DebugFSLogicalStructure(); } // Static classes representing shared instance data // - shared data is computed once for all views /** * Journaling changes for computing delta cas. * Each instance represents one or more changes for one feature structure * A particular Feature Structure may have multiple FsChange instances * but we attempt to minimize this */ public static class FsChange { /** ref to the FS being modified */ final TOP fs; /** * which feature (by offset) is modified */ final BitSet featuresModified; final PositiveIntSet arrayUpdates; FsChange(TOP fs) { this.fs = fs; TypeImpl ti = fs._getTypeImpl(); featuresModified = (ti.highestOffset == -1) ? null : new BitSet(ti.highestOffset + 1); arrayUpdates = (ti.isArray()) ? new PositiveIntSet_impl() : null; } void addFeatData(int v) { featuresModified.set(v); } void addArrayData(int v, int nbrOfConsecutive) { for (int i = 0; i < nbrOfConsecutive; i++) { arrayUpdates.add(v++); } } void addArrayData(PositiveIntSet indexesPlus1) { indexesPlus1.forAllInts(i -> arrayUpdates.add(i - 1)); } @Override public int hashCode() { return 31 + ((fs == null) ? 0 : fs._id); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FsChange)) return false; return ((FsChange)obj).fs._id == fs._id; } } // fields shared among all CASes belong to views of a common base CAS static class SharedViewData { /** * map from FS ids to FSs. */ final private Id2FS id2fs; /** set to > 0 to reuse an id, 0 otherwise */ private int reuseId = 0; // Base CAS for all views final private CASImpl baseCAS; /** * These fields are here, not in TypeSystemImpl, because different CASes may have different indexes but share the same type system * They hold the same data (constant per CAS) but are accessed with different indexes */ private final BitSet featureCodesInIndexKeys = new BitSet(1024); // 128 bytes // private final BitSet featureJiInIndexKeys = new BitSet(1024); // indexed by JCas Feature Index, not feature code. // A map from SofaNumbers which are also view numbers to IndexRepositories. // these numbers are dense, and start with 1. 1 is the initial view. 0 is the base cas ArrayList<FSIndexRepositoryImpl> sofa2indexMap; /** * A map from Sofa numbers to CAS views. * number 0 - not used * number 1 - used for view named "_InitialView" * number 2-n used for other views * * Note: this is not reset with "Cas Reset" because views (really, their associated index repos) * take a lot of setup for the indexes. * However, the maximum view count is reset; so creation of new views "reuses" these pre-setup indexRepos * associated with these views. */ ArrayList<CASImpl> sofaNbr2ViewMap; /** * a set of instantiated sofaNames */ private Set<String> sofaNameSet; // Flag that initial Sofa has been created private boolean initialSofaCreated = false; // Count of Views created in this cas // equals count of sofas except if initial view has no sofa. int viewCount; // The ClassLoader that should be used by the JCas to load the generated // FS cover classes for this CAS. Defaults to the ClassLoader used // to load the CASImpl class. private ClassLoader jcasClassLoader = this.getClass().getClassLoader(); /***************************** * PEAR Support *****************************/ /** * Only support one level of PEAR nesting; for more general approach, make this a deque */ private ClassLoader previousJCasClassLoader = null; /** * Save area for suspending this while we create a base instance */ private ClassLoader suspendPreviousJCasClassLoader; /** * A map from IDs to already created trampoline FSs for the base FS with that id. * These are used when in a Pear and retrieving a FS (via index or deref) and you want the * Pear version for that ID. * There are potentially multiple maps - one per PEAR Classpath */ private JCasHashMap id2tramp = null; /** * a map from IDs of FSs that have a Pear version, to the base (non-Pear) version * used to locate the base version for adding to indexes */ private JCasHashMap id2base = null; private final Map<ClassLoader, JCasHashMap> cl2id2tramp = new IdentityHashMap<>(); /** * The current (active, switches at Pear boundaries) FsGenerators (excluding array-generators) * key = type code * read-only, unsynchronized for this CAS * Cache for setting this kept in TypeSystemImpl, by classloader * - shared among all CASs that use that Type System and class loader * -- in turn, initialized from FSClassRegistry, once per classloader / typesystem combo * * Pear generators are mostly null except for instances where the PEAR has redefined * the JCas cover class */ private FsGenerator3[] generators; /** * When generating a new instance of a FS in a PEAR where there's an alternate JCas class impl, * generate the base version, and make the alternate a trampoline to it. * Note: in future, if it is known that this FS is never used outside of this PEAR, then can * skip generating the double version */ private FsGenerator3[] baseGenerators; // If this CAS can be flushed (reset) or not. // often, the framework disables this before calling users code private boolean flushEnabled = true; // not final because set with reinit deserialization private TypeSystemImpl tsi; private ComponentInfo componentInfo; /** * This tracks the changes for delta cas * May also in the future support Journaling by component, * allowing determination of which component in a flow * created/updated a FeatureStructure (not implmented) * * TrackingMarkers are held on to by things outside of the * Cas, to support switching from one tracking marker to * another (currently not used, but designed to support * Component Journaling). * * We track changes on a granularity of features * and for features which are arrays, which element of the array * (This last to enable efficient delta serializations of * giant arrays of things, where you've only updated a few items) * * The FsChange doesn't store the changed data, only stores the * ref info needed to get to what was changed. */ private MarkerImpl trackingMark; /** * Track modified preexistingFSs * Note this is a map, keyed by the FS, so all changes are merged when added */ private Map<TOP, FsChange> modifiedPreexistingFSs; /** * This list currently only contains at most 1 element. * If Journaling is implemented, it may contain an * element per component being journaled. */ private List<MarkerImpl> trackingMarkList; /** * This stack corresponds to nested protectIndexes contexts. Normally should be very shallow. */ private final ArrayList<FSsTobeAddedback> fssTobeAddedback = new ArrayList<FSsTobeAddedback>(); /** * This version is for single fs use, by binary deserializers and by automatic mode * Only one user at a time is allowed. */ private final FSsTobeAddedbackSingle fsTobeAddedbackSingle = (FSsTobeAddedbackSingle) FSsTobeAddedback.createSingle(); /** * Set to true while this is in use. */ boolean fsTobeAddedbackSingleInUse = false; /** * temporarily set to true by deserialization routines doing their own management of this check */ boolean disableAutoCorruptionCheck = false; // used to generate FSIDs, increments by 1 for each use. First id == 1 /** * The fsId of the last created FS * used to generate FSIDs, increments by 1 for each use. First id == 1 */ private int fsIdGenerator = 0; /** * The version 2 size on the main heap of the last created FS */ private int lastFsV2Size = 1; /** * used to "capture" the fsIdGenerator value for a read-only CAS to be visible in * other threads */ AtomicInteger fsIdLastValue = new AtomicInteger(0); // mostly for debug - counts # times cas is reset private final AtomicInteger casResets = new AtomicInteger(0); // unique ID for a created CAS view, not updated if CAS is reset and reused private final int casId = casIdProvider.incrementAndGet(); // shared singltons, created at type system commit private EmptyFSList emptyFSList; private EmptyFloatList emptyFloatList; private EmptyIntegerList emptyIntegerList; private EmptyStringList emptyStringList; /** * Created at startup time, lives as long as the CAS lives * Serves to reference code for binary cas ser/des that used to live * in this class, but was moved out */ private final BinaryCasSerDes bcsd; /** * Created when doing binary or form4 non-delta (de)serialization, used in subsequent delta ser/deserialization * Created when doing binary or form4 non-delta ser/deserialization, used in subsequent delta (de)serialization * Reset with CasReset or deltaMergesComplete API call */ private CommonSerDesSequential csds; /************************************************* * VERSION 2 LOW_LEVEL_API COMPATIBILITY SUPPORT * *************************************************/ /** * A StringSet used only to support ll_get/setInt api * get adds string to this and returns the int handle * set retrieves the string, given the handle * lazy initialized */ private StringSet llstringSet = null; /** * A LongSet used only to support v2 ll_get/setInt api * get adds long to this and returns the int handle * set retrieves the long, given the handle * lazy initialized */ private LongSet lllongSet = null; // For tracing FS creation and updating, normally disabled private final StringBuilder traceFScreationSb = traceFSs ? new StringBuilder() : null; private final StringBuilder traceCowSb = traceCow ? new StringBuilder() : null; private int traceFSid = 0; private boolean traceFSisCreate; private final IntVector id2addr = traceFSs ? new IntVector() : null; private int nextId2Addr = 1; // only for tracing, to convert id's to v2 addresses final private int initialHeapSize; private SharedViewData(CASImpl baseCAS, int initialHeapSize, TypeSystemImpl tsi) { this.baseCAS = baseCAS; this.tsi = tsi; this.initialHeapSize = initialHeapSize; bcsd = new BinaryCasSerDes(baseCAS); id2fs = new Id2FS(initialHeapSize); if (traceFSs) id2addr.add(0); } void clearCasReset() { // fss fsIdGenerator = 0; id2fs.clear(); // pear caches id2tramp = null; id2base = null; for (JCasHashMap m : cl2id2tramp.values()) { m.clear(); } // index corruption avoidance fssTobeAddedback.clear(); fsTobeAddedbackSingle.clear(); fsTobeAddedbackSingleInUse = false; disableAutoCorruptionCheck = false; // misc flushEnabled = true; componentInfo = null; bcsd.clear(); csds = null; llstringSet = null; traceFSid = 0; if (traceFSs) { traceFScreationSb.setLength(0); id2addr.removeAllElements(); id2addr.add(0); nextId2Addr = 1; } } /** * called by resetNoQuestions and cas complete reinit */ void clearSofaInfo() { sofaNameSet.clear(); initialSofaCreated = false; } /** * Called from CasComplete deserialization (reinit). * * Skips the resetNoQuestions operation of flushing the indexes, * since these will be reinitialized with potentially new definitions. * * Clears additional data related to having the * - type system potentially change * - the features belonging to indexes change * */ void clear() { clearCasReset(); clearTrackingMarks(); // type system + index spec tsi = null; featureCodesInIndexKeys.clear(); // featureJiInIndexKeys.clear(); emptyFloatList = null; // these cleared in case new ts redefines? emptyFSList = null; emptyIntegerList = null; emptyStringList = null; clearSofaInfo(); /** * Clear the existing views, except keep the info for the initial view * so that the cas complete deserialization after setting up the new index repository in the base cas * can "refresh" the existing initial view (if present; if not present, a new one is created). */ if (sofaNbr2ViewMap.size() >= 1) { // have initial view - preserve it CASImpl localInitialView = sofaNbr2ViewMap.get(1); sofaNbr2ViewMap.clear(); Misc.setWithExpand(sofaNbr2ViewMap, 1, localInitialView); viewCount = 1; } else { sofaNbr2ViewMap.clear(); viewCount = 0; } } private void clearTrackingMarks() { // resets all markers that might be held by things outside the Cas // Currently (2009) this list has a max of 1 element // Future impl may have one element per component for component Journaling if (trackingMarkList != null) { for (int i=0; i < trackingMarkList.size(); i++) { trackingMarkList.get(i).isValid = false; } } trackingMark = null; if (null != modifiedPreexistingFSs) { modifiedPreexistingFSs.clear(); } trackingMarkList = null; } void switchClassLoader(ClassLoader newClassLoader) { if (null == newClassLoader) { // is null if no cl set return; } if (newClassLoader != jcasClassLoader) { if (null != previousJCasClassLoader) { /** Multiply nested classloaders not supported. Original base loader: {0}, current nested loader: {1}, trying to switch to loader: {2}.*/ throw new CASRuntimeException(CASRuntimeException.SWITCH_CLASS_LOADER_NESTED, previousJCasClassLoader, jcasClassLoader, newClassLoader); } // System.out.println("Switching to new class loader"); previousJCasClassLoader = jcasClassLoader; jcasClassLoader = newClassLoader; generators = tsi.getGeneratorsForClassLoader(newClassLoader, true); // true - isPear assert null == id2tramp; // is null outside of a pear id2tramp = cl2id2tramp.get(newClassLoader); if (null == id2tramp) { cl2id2tramp.put(newClassLoader, id2tramp = new JCasHashMap(32)); } if (id2base == null) { id2base = new JCasHashMap(32); } } } void restoreClassLoader() { if (null == previousJCasClassLoader) { return; } // System.out.println("Switching back to previous class loader"); jcasClassLoader = previousJCasClassLoader; previousJCasClassLoader = null; generators = baseGenerators; id2tramp = null; } private int getNextFsId(TOP fs) { if (reuseId != 0) { // l.setStrongRef(fs, reuseId); return reuseId; } // l.add(fs); // if (id2fs.size() != (2 + fsIdGenerator.get())) { // System.out.println("debug out of sync id generator and id2fs size"); // } // assert(l.size() == (2 + fsIdGenerator)); final int p = fsIdGenerator; final int r = fsIdGenerator += IS_USE_V2_IDS ? lastFsV2Size : 1; if (r < p) { throw new RuntimeException("UIMA Cas Internal id value overflowed maximum int value"); } if (IS_USE_V2_IDS) { // this computation is partial - misses length of arrays stored on heap // because that info not yet available lastFsV2Size = fs._getTypeImpl().getFsSpaceReq(); } return r; } } /***************************************************************** * Non-shared instance data kept per CAS view incl base CAS *****************************************************************/ // package protected to let other things share this info final SharedViewData svd; // shared view data /** The index repository. Referenced by XmiCasSerializer */ FSIndexRepositoryImpl indexRepository; // private Object[] currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // private Object[] returnRefDataForAlloc; // private int[] currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // private int[] returnIntDataForAlloc; // private int nextRefDataOffsetForAlloc = 0; // private int nextIntDataOffsetForAlloc = 0; /** * The Feature Structure for the sofa FS for this view, or * null * //-1 if the sofa FS is for the initial view, or * // 0 if there is no sofa FS - for instance, in the "base cas" */ private Sofa mySofaRef = null; /** the corresponding JCas object */ JCasImpl jcas = null; /** * Copies of frequently accessed data pulled up for * locality of reference - only an optimization * - each value needs to be reset appropriately * - getters check for null, and if null, do the get. */ private TypeSystemImpl tsi_local; /** * for Pear generation - set this to the base FS * not in SharedViewData to reduce object traversal when * generating FSs */ FeatureStructureImplC pearBaseFs = null; // private StackTraceElement[] addbackSingleTrace = null; // for debug use only, normally commented out // CASImpl(TypeSystemImpl typeSystem) { // this(typeSystem, DEFAULT_INITIAL_HEAP_SIZE); // } // // Reference existing CAS // // For use when creating views of the CAS // CASImpl(CAS cas) { // this.setCAS(cas); // this.useFSCache = false; // initTypeVariables(); // } /* * Configure a new (base view) CASImpl, **not a new view** typeSystem can be * null, in which case a new instance of TypeSystemImpl is set up, but not * committed. If typeSystem is not null, it is committed (locked). ** Note: it * is assumed that the caller of this will always set up the initial view ** * by calling */ public CASImpl(TypeSystemImpl typeSystem, int initialHeapSize ) { super(); TypeSystemImpl ts; final boolean externalTypeSystem = (typeSystem != null); if (externalTypeSystem) { ts = typeSystem; } else { ts = (TypeSystemImpl) CASFactory.createTypeSystem(); // creates also new CASMetadata and // FSClassRegistry instances } this.svd = new SharedViewData(this, initialHeapSize, ts); // this.svd.baseCAS = this; // this.svd.heap = new Heap(initialHeapSize); if (externalTypeSystem) { commitTypeSystem(); } this.svd.sofa2indexMap = new ArrayList<>(); this.svd.sofaNbr2ViewMap = new ArrayList<>(); this.svd.sofaNameSet = new HashSet<String>(); this.svd.initialSofaCreated = false; this.svd.viewCount = 0; this.svd.clearTrackingMarks(); } public CASImpl() { this((TypeSystemImpl) null, DEFAULT_INITIAL_HEAP_SIZE); } // In May 2007, appears to have 1 caller, createCASMgr in Serialization class, // could have out-side the framework callers because it is public. public CASImpl(CASMgrSerializer ser) { this(ser.getTypeSystem(), DEFAULT_INITIAL_HEAP_SIZE); checkInternalCodes(ser); // assert(ts != null); // assert(getTypeSystem() != null); this.indexRepository = ser.getIndexRepository(this); } // Use this when creating a CAS view CASImpl(CASImpl cas, SofaFS aSofa) { // these next fields are final and must be set in the constructor this.svd = cas.svd; this.mySofaRef = (Sofa) aSofa; // get the indexRepository for this Sofa this.indexRepository = (this.mySofaRef == null) ? (FSIndexRepositoryImpl) cas.getSofaIndexRepository(1) : (FSIndexRepositoryImpl) cas.getSofaIndexRepository(aSofa); if (null == this.indexRepository) { // create the indexRepository for this CAS // use the baseIR to create a lightweight IR copy FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) cas.getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this, baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { cas.setSofaIndexRepository(1, this.indexRepository); } else { cas.setSofaIndexRepository(aSofa, this.indexRepository); } } } // Use this when creating a CAS view void refreshView(CAS cas, SofaFS aSofa) { if (aSofa != null) { // save address of SofaFS this.mySofaRef = (Sofa) aSofa; } else { // this is the InitialView this.mySofaRef = null; } // toss the JCas, if it exists this.jcas = null; // create the indexRepository for this Sofa final FSIndexRepositoryImpl baseIndexRepo = (FSIndexRepositoryImpl) ((CASImpl) cas).getBaseIndexRepository(); this.indexRepository = new FSIndexRepositoryImpl(this,baseIndexRepo); // the index creation depends on "indexRepository" already being set baseIndexRepo.name2indexMap.keySet().stream().forEach(key -> this.indexRepository.createIndex(baseIndexRepo, key)); this.indexRepository.commit(); // save new sofa index if (this.mySofaRef == null) { ((CASImpl) cas).setSofaIndexRepository(1, this.indexRepository); } else { ((CASImpl) cas).setSofaIndexRepository(aSofa, this.indexRepository); } } private void checkInternalCodes(CASMgrSerializer ser) throws CASAdminException { if ((ser.topTypeCode > 0) && (ser.topTypeCode != topTypeCode)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } if (ser.featureOffsets == null) { return; } // if (ser.featureOffsets.length != this.svd.casMetadata.featureOffset.length) { // throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); // } TypeSystemImpl tsi = getTypeSystemImpl(); for (int i = 1; i < ser.featureOffsets.length; i++) { FeatureImpl fi = tsi.getFeatureForCode_checked(i); int adjOffset = fi.isInInt ? 0 : fi.getRangeImpl().nbrOfUsedIntDataSlots; if (ser.featureOffsets[i] != (fi.getOffset() + adjOffset)) { throw new CASAdminException(CASAdminException.DESERIALIZATION_ERROR); } } } // ---------------------------------------- // accessors for data in SharedViewData // ---------------------------------------- void addSofaViewName(String id) { svd.sofaNameSet.add(id); } void setViewCount(int n) { svd.viewCount = n; } void addbackSingle(TOP fs) { if (!svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } void addbackSingleIfWasRemoved(boolean wasRemoved, TOP fs) { if (wasRemoved) { addbackSingle(fs); } svd.fsTobeAddedbackSingleInUse = false; } private FSsTobeAddedback getAddback(int size) { if (svd.fsTobeAddedbackSingleInUse) { Misc.internalError(); } return svd.fssTobeAddedback.get(size - 1); } FSsTobeAddedbackSingle getAddbackSingle() { if (svd.fsTobeAddedbackSingleInUse) { // System.out.println(Misc.dumpCallers(addbackSingleTrace, 2, 100)); Misc.internalError(); } // addbackSingleTrace = Thread.currentThread().getStackTrace(); svd.fsTobeAddedbackSingleInUse = true; svd.fsTobeAddedbackSingle.clear(); // safety return svd.fsTobeAddedbackSingle; } void featureCodes_inIndexKeysAdd(int featCode/*, int registryIndex*/) { svd.featureCodesInIndexKeys.set(featCode); // skip adding if no JCas registry entry for this feature // if (registryIndex >= 0) { // svd.featureJiInIndexKeys.set(registryIndex); // } } @Override public void enableReset(boolean flag) { this.svd.flushEnabled = flag; } @Override public TypeSystem getTypeSystem() { return getTypeSystemImpl(); } public TypeSystemImpl getTypeSystemImpl() { if (tsi_local == null) { tsi_local = this.svd.tsi; } return this.tsi_local; } /** * Set the shared svd type system ref, in all views * @param ts */ void installTypeSystemInAllViews(TypeSystemImpl ts) { this.svd.tsi = ts; final List<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (sn2v.size() > 0) { for (CASImpl view : sn2v.subList(1, sn2v.size())) { view.tsi_local = ts; } } this.getBaseCAS().tsi_local = ts; } @Override public ConstraintFactory getConstraintFactory() { return ConstraintFactory.instance(); } /** * Create the appropriate Feature Structure Java instance * - from whatever the generator for this type specifies. * * @param type the type to create * @return a Java object representing the FeatureStructure impl in Java. */ @Override public <T extends FeatureStructure> T createFS(Type type) { final TypeImpl ti = (TypeImpl) type; if (!ti.isCreatableAndNotBuiltinArray()) { throw new CASRuntimeException(CASRuntimeException.NON_CREATABLE_TYPE, type.getName(), "CAS.createFS()"); } return (T) createFSAnnotCheck(ti); } private <T extends FeatureStructureImplC> T createFSAnnotCheck(TypeImpl ti) { if (ti.isAnnotationBaseType()) { // not here, will be checked later in AnnotationBase constructor // if (this.isBaseCas()) { // throw new CASRuntimeException(CASRuntimeException.DISALLOW_CREATE_ANNOTATION_IN_BASE_CAS, ti.getName()); // } getSofaRef(); // materialize this if not present; required for setting the sofa ref // must happen before the annotation is created, for compressed form 6 serialization order // to insure sofa precedes the ref of it } FsGenerator3 g = svd.generators[ti.getCode()]; // get generator or null return (g != null) ? (T) g.createFS(ti, this) // pear case, with no overriding pear - use base : (T) createFsFromGenerator(svd.baseGenerators, ti); // // // // not pear or no special cover class for this // // // TOP fs = createFsFromGenerator(svd.baseGenerators, ti); // // FsGenerator g = svd.generators[ti.getCode()]; // get pear generator or null // return (g != null) // ? (T) pearConvert(fs, g) // : (T) fs; // } // // return (T) createFsFromGenerator(svd.generators, ti); } /** * Called during construction of FS. * For normal FS "new" operators, if in PEAR context, make the base version * @param fs * @param ti * @return true if made a base for a trampoline */ boolean maybeMakeBaseVersionForPear(FeatureStructureImplC fs, TypeImpl ti) { if (!inPearContext()) return false; FsGenerator3 g = svd.generators[ti.getCode()]; // get pear generator or null if (g == null) return false; TOP baseFs; try { suspendPearContext(); svd.reuseId = fs._id; baseFs = createFsFromGenerator(svd.baseGenerators, ti); } finally { restorePearContext(); svd.reuseId = 0; } svd.id2base.put(baseFs); pearBaseFs = baseFs; return true; } private TOP createFsFromGenerator(FsGenerator3[] gs, TypeImpl ti) { // if (ti == null || gs == null || gs[ti.getCode()] == null) { // System.out.println("debug"); // } return gs[ti.getCode()].createFS(ti, this); } // public int ll_createFSAnnotCheck(int typeCode) { // TOP fs = createFSAnnotCheck(getTypeFromCode(typeCode)); // svd.id2fs.put(fs); // required for low level, in order to "hold onto" / prevent GC of FS // return fs._id; // } public TOP createArray(TypeImpl array_type, int arrayLength) { TypeImpl_array tia = (TypeImpl_array) array_type; TypeImpl componentType = tia.getComponentType(); if (componentType.isPrimitive()) { checkArrayPreconditions(arrayLength); switch (componentType.getCode()) { case intTypeCode: return new IntegerArray(array_type, this, arrayLength); case floatTypeCode: return new FloatArray(array_type, this, arrayLength); case booleanTypeCode: return new BooleanArray(array_type, this, arrayLength); case byteTypeCode: return new ByteArray(array_type, this, arrayLength); case shortTypeCode: return new ShortArray(array_type, this, arrayLength); case longTypeCode: return new LongArray(array_type, this, arrayLength); case doubleTypeCode: return new DoubleArray(array_type, this, arrayLength); case stringTypeCode: return new StringArray(array_type, this, arrayLength); // case javaObjectTypeCode: return new JavaObjectArray(array_type, this, arrayLength); default: Misc.internalError(); } // return tia.getGeneratorArray().createFS(type, this, arrayLength); // return (((FsGeneratorArray)getFsGenerator(type.getCode())).createFS(type, this, arrayLength)); } return (TOP) createArrayFS(array_type, arrayLength); } @Override public ArrayFS createArrayFS(int length) { return createArrayFS(getTypeSystemImpl().fsArrayType, length); } private ArrayFS createArrayFS(TypeImpl type, int length) { checkArrayPreconditions(length); return new FSArray(type, this, length); // getTypeSystemImpl().fsArrayType.getGeneratorArray() // (((FsGeneratorArray)getFsGenerator(fsArrayTypeCode)) // .createFS(type, this, length); } @Override public IntArrayFS createIntArrayFS(int length) { checkArrayPreconditions(length); return new IntegerArray(getTypeSystemImpl().intArrayType, this, length); } @Override public FloatArrayFS createFloatArrayFS(int length) { checkArrayPreconditions(length); return new FloatArray(getTypeSystemImpl().floatArrayType, this, length); } @Override public StringArrayFS createStringArrayFS(int length) { checkArrayPreconditions(length); return new StringArray(getTypeSystemImpl().stringArrayType, this, length); } // public JavaObjectArray createJavaObjectArrayFS(int length) { // checkArrayPreconditions(length); // return new JavaObjectArray(getTypeSystemImpl().javaObjectArrayType, this, length); // } // return true if only one sofa and it is the default text sofa public boolean isBackwardCompatibleCas() { // check that there is exactly one sofa if (this.svd.viewCount != 1) { return false; } if (!this.svd.initialSofaCreated) { return false; } Sofa sofa = this.getInitialView().getSofa(); // check for mime type exactly equal to "text" String sofaMime = sofa.getMimeType(); if (!"text".equals(sofaMime)) { return false; } // check that sofaURI and sofaArray are not set String sofaUri = sofa.getSofaURI(); if (sofaUri != null) { return false; } TOP sofaArray = sofa.getSofaArray(); if (sofaArray != null) { return false; } // check that name is NAME_DEFAULT_SOFA String sofaname = sofa.getSofaID(); return NAME_DEFAULT_SOFA.equals(sofaname); } int getViewCount() { return this.svd.viewCount; } FSIndexRepository getSofaIndexRepository(SofaFS aSofa) { return getSofaIndexRepository(aSofa.getSofaRef()); } FSIndexRepositoryImpl getSofaIndexRepository(int aSofaRef) { if (aSofaRef >= this.svd.sofa2indexMap.size()) { return null; } return this.svd.sofa2indexMap.get(aSofaRef); } void setSofaIndexRepository(SofaFS aSofa, FSIndexRepositoryImpl indxRepos) { setSofaIndexRepository(aSofa.getSofaRef(), indxRepos); } void setSofaIndexRepository(int aSofaRef, FSIndexRepositoryImpl indxRepos) { Misc.setWithExpand(this.svd.sofa2indexMap, aSofaRef, indxRepos); } /** * @deprecated */ @Override @Deprecated public SofaFS createSofa(SofaID sofaID, String mimeType) { // extract absolute SofaName string from the ID SofaFS aSofa = createSofa(sofaID.getSofaID(), mimeType); getView(aSofa); // will create the view, needed to make the // resetNoQuestions and other things that // iterate over views work. return aSofa; } Sofa createSofa(String sofaName, String mimeType) { return createSofa(++this.svd.viewCount, sofaName, mimeType); } Sofa createSofa(int sofaNum, String sofaName, String mimeType) { if (this.svd.sofaNameSet.contains(sofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, sofaName); } final boolean viewAlreadyExists = sofaNum == this.svd.viewCount; if (!viewAlreadyExists) { if (sofaNum == 1) { // skip the test for sofaNum == 1 - this can be set "later" if (this.svd.viewCount == 0) { this.svd.viewCount = 1; } // else it is == or higher, so don't reset it down } else { // sofa is not initial sofa - is guaranteed to be set when view created // if (sofaNum != this.svd.viewCount + 1) { // System.out.println("debug"); // } assert (sofaNum == this.svd.viewCount + 1); this.svd.viewCount = sofaNum; } } Sofa sofa = new Sofa( getTypeSystemImpl().sofaType, this.getBaseCAS(), // view for a sofa is the base cas to correspond to where it gets indexed sofaNum, sofaName, mimeType); this.getBaseIndexRepository().addFS(sofa); this.svd.sofaNameSet.add(sofaName); if (!viewAlreadyExists) { getView(sofa); // create the view that goes with this Sofa } return sofa; } Sofa createInitialSofa(String mimeType) { Sofa sofa = createSofa(1, CAS.NAME_DEFAULT_SOFA, mimeType); registerInitialSofa(); this.mySofaRef = sofa; return sofa; } void registerInitialSofa() { this.svd.initialSofaCreated = true; } boolean isInitialSofaCreated() { return this.svd.initialSofaCreated; } /** * @deprecated */ @Override @Deprecated public SofaFS getSofa(SofaID sofaID) { // extract absolute SofaName string from the ID return getSofa(sofaID.getSofaID()); } private SofaFS getSofa(String sofaName) { FSIterator<Sofa> iterator = this.svd.baseCAS.getSofaIterator(); while (iterator.hasNext()) { SofaFS sofa = iterator.next(); if (sofaName.equals(sofa.getSofaID())) { return sofa; } } throw new CASRuntimeException(CASRuntimeException.SOFANAME_NOT_FOUND, sofaName); } SofaFS getSofa(int sofaRef) { SofaFS aSofa = (SofaFS) this.ll_getFSForRef(sofaRef); if (aSofa == null) { CASRuntimeException e = new CASRuntimeException(CASRuntimeException.SOFAREF_NOT_FOUND); throw e; } return aSofa; } public int ll_getSofaNum(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaNum(); } public String ll_getSofaID(int sofaRef) { return ((Sofa)getFsFromId_checked(sofaRef)).getSofaID(); } public String ll_getSofaDataString(int sofaAddr) { return ((Sofa)getFsFromId_checked(sofaAddr)).getSofaString(); } public CASImpl getBaseCAS() { return this.svd.baseCAS; } @Override public <T extends SofaFS> FSIterator<T> getSofaIterator() { FSIndex<T> sofaIndex = this.svd.baseCAS.indexRepository.<T>getIndex(CAS.SOFA_INDEX_NAME); return sofaIndex.iterator(); } // For internal use only public Sofa getSofaRef() { if (this.mySofaRef == null) { // create the SofaFS for _InitialView ... // ... and reset mySofaRef to point to it this.mySofaRef = this.createInitialSofa(null); } return this.mySofaRef; } // For internal use only public InputStream getSofaDataStream(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; String sd = sofa.getLocalStringData(); if (null != sd) { ByteArrayInputStream bis; try { bis = new ByteArrayInputStream(sd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } return bis; } else if (null != aSofa.getLocalFSData()) { TOP fs = (TOP) sofa.getLocalFSData(); ByteBuffer buf = null; switch(fs._getTypeCode()) { case stringArrayTypeCode: { StringBuilder sb = new StringBuilder(); final String[] theArray = ((StringArray) fs)._getTheArray(); for (int i = 0; i < theArray.length; i++) { if (i != 0) { sb.append('\n'); } sb.append(theArray[i]); } try { return new ByteArrayInputStream(sb.toString().getBytes("UTF-8") ); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // never happen } } case intArrayTypeCode: { final int[] theArray = ((IntegerArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asIntBuffer().put(theArray, 0, theArray.length); break; } case floatArrayTypeCode: { final float[] theArray = ((FloatArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 4)).asFloatBuffer().put(theArray, 0, theArray.length); break; } case byteArrayTypeCode: { final byte[] theArray = ((ByteArray) fs)._getTheArray(); buf = ByteBuffer.wrap(theArray); break; } case shortArrayTypeCode: { final short[] theArray = ((ShortArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 2)).asShortBuffer().put(theArray, 0, theArray.length); break; } case longArrayTypeCode: { final long[] theArray = ((LongArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asLongBuffer().put(theArray, 0, theArray.length); break; } case doubleArrayTypeCode: { final double[] theArray = ((DoubleArray) fs)._getTheArray(); (buf = ByteBuffer.allocate(theArray.length * 8)).asDoubleBuffer().put(theArray, 0, theArray.length); break; } default: Misc.internalError(); } ByteArrayInputStream bis = new ByteArrayInputStream(buf.array()); return bis; } else if (null != aSofa.getSofaURI()) { URL url; try { url = new URL(aSofa.getSofaURI()); return url.openStream(); } catch (IOException exc) { throw new CASRuntimeException(CASRuntimeException.SOFADATASTREAM_ERROR, exc.getMessage()); } } return null; } @Override public<T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons) { return new FilteredIterator<T>(it, cons); } public TypeSystemImpl commitTypeSystem() { TypeSystemImpl ts = getTypeSystemImpl(); // For CAS pools, the type system could have already been committed // Skip the initFSClassReg if so, because it may have been updated to a JCas // version by another CAS processing in the pool // @see org.apache.uima.cas.impl.FSClassRegistry // avoid race: two instances of a CAS from a pool attempting to commit the // ts // at the same time final ClassLoader cl = getJCasClassLoader(); synchronized (ts) { if (!ts.isCommitted()) { TypeSystemImpl tsc = ts.commit(getJCasClassLoader()); if (tsc != ts) { installTypeSystemInAllViews(tsc); ts = tsc; } } } svd.baseGenerators = svd.generators = ts.getGeneratorsForClassLoader(cl, false); // false - not PEAR createIndexRepository(); return ts; } private void createIndexRepository() { if (!this.getTypeSystemMgr().isCommitted()) { throw new CASAdminException(CASAdminException.MUST_COMMIT_TYPE_SYSTEM); } if (this.indexRepository == null) { this.indexRepository = new FSIndexRepositoryImpl(this); } } @Override public FSIndexRepositoryMgr getIndexRepositoryMgr() { // assert(this.cas.getIndexRepository() != null); return this.indexRepository; } /** * @deprecated * @param fs - */ @Deprecated public void commitFS(FeatureStructure fs) { getIndexRepository().addFS(fs); } @Override public FeaturePath createFeaturePath() { return new FeaturePathImpl(); } // Implement the ConstraintFactory interface. /** * @see org.apache.uima.cas.admin.CASMgr#getTypeSystemMgr() */ @Override public TypeSystemMgr getTypeSystemMgr() { return getTypeSystemImpl(); } @Override public void reset() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } if (this == this.svd.baseCAS) { resetNoQuestions(); return; } // called from a CAS view. // clear CAS ... this.svd.baseCAS.resetNoQuestions(); } public void resetNoQuestions() { svd.casResets.incrementAndGet(); svd.clearCasReset(); if (trace) { System.out.println("CAS Reset in thread " + Thread.currentThread().getName() + " for CasId = " + getCasId() + ", new reset count = " + svd.casResets.get()); } int numViews = this.getViewCount(); // Flush indexRepository for all views for (int view = 1; view <= numViews; view++) { CASImpl tcas = (CASImpl) ((view == 1) ? getInitialView() : getView(view)); if (tcas != null) { tcas.indexRepository.flush(); // mySofaRef = -1 is a flag in initial view that sofa has not been set. // For the initial view, it is possible to not have a sofa - it is set // "lazily" upon the first need. // all other views always have a sofa set. The sofaRef is set to 0, // but will be set to the actual sofa addr in the cas when the view is // initialized. tcas.mySofaRef = null; // was in v2: (1 == view) ? -1 : 0; } } this.svd.clearTrackingMarks(); // safety : in case this public method is called on other than the base cas this.getBaseCAS().indexRepository.flush(); // for base view, other views flushed above this.svd.clearSofaInfo(); // but keep initial view, and other views // because setting up the index infrastructure is expensive this.svd.viewCount = 1; // initial view svd.traceFSid = 0; if (traceFSs) svd.traceFScreationSb.setLength(0); this.svd.componentInfo = null; // https://issues.apache.org/jira/browse/UIMA-5097 } /** * @deprecated Use {@link #reset reset()}instead. */ @Override @Deprecated public void flush() { reset(); } @Override public FSIndexRepository getIndexRepository() { if (this == this.svd.baseCAS) { // BaseCas has no indexes for users return null; } if (this.indexRepository.isCommitted()) { return this.indexRepository; } return null; } FSIndexRepository getBaseIndexRepository() { if (this.svd.baseCAS.indexRepository.isCommitted()) { return this.svd.baseCAS.indexRepository; } return null; } FSIndexRepositoryImpl getBaseIndexRepositoryImpl() { return this.svd.baseCAS.indexRepository; } void addSofaFsToIndex(SofaFS sofa) { this.svd.baseCAS.getBaseIndexRepository().addFS(sofa); } void registerView(Sofa aSofa) { this.mySofaRef = aSofa; } /** * @see org.apache.uima.cas.CAS#fs2listIterator(FSIterator) */ @Override public <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it) { return new FSListIteratorImpl<T>(it); } /** * @see org.apache.uima.cas.admin.CASMgr#getCAS() */ @Override public CAS getCAS() { if (this.indexRepository.isCommitted()) { return this; } throw new CASAdminException(CASAdminException.MUST_COMMIT_INDEX_REPOSITORY); } // public void setFSClassRegistry(FSClassRegistry fsClassReg) { // this.svd.casMetadata.fsClassRegistry = fsClassReg; // } // JCasGen'd cover classes use this to add their generators to the class // registry // Note that this now (June 2007) a no-op for JCasGen'd generators // Also previously (but not now) used in JCas initialization to copy-down super generators to subtypes // as needed public FSClassRegistry getFSClassRegistry() { return null; // return getTypeSystemImpl().getFSClassRegistry(); } /** * @param fs the Feature Structure being updated * @param fi the Feature of fs being updated, or null if fs is an array * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, FeatureImpl fi, int arrayIndexStart, int nbrOfConsecutive) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); if (fi == null) { Misc.assertUie(arrayIndexStart >= 0); change.addArrayData(arrayIndexStart, nbrOfConsecutive); } else { change.addFeatData(fi.getOffset()); } } /** * @param fs the Feature Structure being updated * @param arrayIndexStart * @param nbrOfConsecutive */ private void logFSUpdate(TOP fs, PositiveIntSet indexesPlus1) { //log the FS final Map<TOP, FsChange> changes = this.svd.modifiedPreexistingFSs; //create or use last FsChange element FsChange change = changes.computeIfAbsent(fs, key -> new FsChange(key)); change.addArrayData(indexesPlus1); } private void logFSUpdate(TOP fs, FeatureImpl fi) { logFSUpdate(fs, fi, -1, -1); // indicate non-array call } /** * This is your link from the low-level API to the high-level API. Use this * method to create a FeatureStructure object from an address. Note that the * reverse is not supported by public APIs (i.e., there is currently no way to * get at the address of a FeatureStructure. Maybe we will need to change * that. * * The "create" in "createFS" is a misnomer - the FS must already be created. * * @param id The id of the feature structure to be created. * @param <T> The Java class associated with this feature structure * @return A FeatureStructure object. */ public <T extends TOP> T createFS(int id) { return getFsFromId_checked(id); } public int getArraySize(CommonArrayFS fs) { return fs.size(); } @Override public int ll_getArraySize(int id) { return getArraySize(getFsFromId_checked(id)); } final void setWithCheckAndJournal(TOP fs, FeatureImpl fi, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, fi.getCode()); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, fi); } final public void setWithCheckAndJournal(TOP fs, int featCode, Runnable setter) { if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, featCode); setter.run(); if (wasRemoved) { maybeAddback(fs); } } else { setter.run(); } maybeLogUpdate(fs, featCode); } // public void setWithCheck(FeatureStructureImplC fs, FeatureImpl feat, Runnable setter) { // boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat); // setter.run(); // if (wasRemoved) { // maybeAddback(fs); // } // } /** * This method called by setters in JCas gen'd classes when * the setter must check for journaling * @param fs - * @param fi - * @param setter - */ public void setWithJournal(FeatureStructureImplC fs, FeatureImpl fi, Runnable setter) { setter.run(); maybeLogUpdate(fs, fi); } public boolean isLoggingNeeded(FeatureStructureImplC fs) { return this.svd.trackingMark != null && !this.svd.trackingMark.isNew(fs._id); } /** * @param fs the Feature Structure being updated * @param feat the feature of fs being updated, or null if fs is a primitive array * @param i the index being updated */ final public void maybeLogArrayUpdate(FeatureStructureImplC fs, FeatureImpl feat, int i) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat, i, 1); } } /** * @param fs the Feature Structure being updated * @param indexesPlus1 - a set of indexes (plus 1) that have been update */ final public void maybeLogArrayUpdates(FeatureStructureImplC fs, PositiveIntSet indexesPlus1) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, indexesPlus1); } } /** * @param fs a primitive array FS * @param startingIndex - * @param length number of consequtive items */ public void maybeLogArrayUpdates(FeatureStructureImplC fs, int startingIndex, int length) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, null, startingIndex, length); } } final public void maybeLogUpdate(FeatureStructureImplC fs, FeatureImpl feat) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP) fs, feat); } } final public void maybeLogUpdate(FeatureStructureImplC fs, int featCode) { if (isLoggingNeeded(fs)) { this.logFSUpdate((TOP)fs, getFeatFromCode_checked(featCode)); } } final public boolean isLogging() { return this.svd.trackingMark != null; } // /** // * Common setter code for features in Feature Structures // * // * These come in two styles: one with int values, one with Object values // * Object values are FS or Strings or JavaObjects // */ // // /** // * low level setter // * // * @param fs the feature structure // * @param feat the feature to set // * @param value - // */ // // public void setFeatureValue(FeatureStructureImplC fs, FeatureImpl feat, int value) { // fs.setIntValue(feat, value); //// boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); //// fs._intData[feat.getAdjustedOffset()] = value; //// if (wasRemoved) { //// maybeAddback(fs); //// } //// maybeLogUpdate(fs, feat); // } /** * version for longs, uses two slots * Only called from FeatureStructureImplC after determining * there is no local field to use * Is here because of 3 calls to things in this class * @param fsIn the feature structure * @param feat the feature to set * @param v - */ public void setLongValue(FeatureStructureImplC fsIn, FeatureImpl feat, long v) { TOP fs = (TOP) fsIn; if (fs._inSetSortedIndex()) { boolean wasRemoved = checkForInvalidFeatureSetting(fs, feat.getCode()); fs._setLongValueNcNj(feat, v); if (wasRemoved) { maybeAddback(fs); } } else { fs._setLongValueNcNj(feat, v); } maybeLogUpdate(fs, feat); } void setFeatureValue(int fsRef, int featureCode, TOP value) { getFsFromId_checked(fsRef).setFeatureValue(getFeatFromCode_checked(featureCode), value); } /** * Supports setting slots to "0" for null values * @param fs The feature structure to update * @param feat the feature to update- * @param s the string representation of the value, could be null */ public void setFeatureValueFromString(FeatureStructureImplC fs, FeatureImpl feat, String s) { final TypeImpl range = feat.getRangeImpl(); if (fs instanceof Sofa) { // sofa has special setters Sofa sofa = (Sofa) fs; switch (feat.getCode()) { case sofaMimeFeatCode : sofa.setMimeType(s); break; case sofaStringFeatCode: sofa.setLocalSofaData(s); break; case sofaUriFeatCode: sofa.setRemoteSofaURI(s); break; default: // left empty - ignore trying to set final fields } return; } if (feat.isInInt) { switch (range.getCode()) { case floatTypeCode : fs.setFloatValue(feat, (s == null) ? 0F : Float.parseFloat(s)); break; case booleanTypeCode : fs.setBooleanValue(feat, (s == null) ? false : Boolean.parseBoolean(s)); break; case longTypeCode : fs.setLongValue(feat, (s == null) ? 0L : Long.parseLong(s)); break; case doubleTypeCode : fs.setDoubleValue(feat, (s == null) ? 0D : Double.parseDouble(s)); break; case byteTypeCode : fs.setByteValue(feat, (s == null) ? 0 : Byte.parseByte(s)); break; case shortTypeCode : fs.setShortValue(feat, (s == null) ? 0 : Short.parseShort(s)); break; case intTypeCode : fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); break; default: fs.setIntValue(feat, (s == null) ? 0 : Integer.parseInt(s)); } } else if (range.isRefType) { if (s == null) { fs.setFeatureValue(feat, null); } else { // Setting a reference value "{0}" from a string is not supported. throw new CASRuntimeException(CASRuntimeException.SET_REF_FROM_STRING_NOT_SUPPORTED, feat.getName()); } } else if (range.isStringOrStringSubtype()) { // includes TypeImplSubString // is String or Substring fs.setStringValue(feat, (s == null) ? null : s); // } else if (range == getTypeSystemImpl().javaObjectType) { // fs.setJavaObjectValue(feat, (s == null) ? null : deserializeJavaObject(s)); } else { Misc.internalError(); } } // private Object deserializeJavaObject(String s) { // throw new UnsupportedOperationException("Deserializing JavaObjects not yet implemented"); // } // // static String serializeJavaObject(Object s) { // throw new UnsupportedOperationException("Serializing JavaObjects not yet implemented"); // } /* * This should be the only place where the encoding of floats and doubles in terms of ints is specified * Someday we may want to preserve NAN things using "raw" versions */ public static final float int2float(int i) { return Float.intBitsToFloat(i); } public static final int float2int(float f) { return Float.floatToIntBits(f); } public static final double long2double(long l) { return Double.longBitsToDouble(l); } public static final long double2long(double d) { return Double.doubleToLongBits(d); } // Type access methods. public boolean isStringType(Type type) { return type instanceof TypeImpl_string; } public boolean isArrayOfFsType(Type type) { return ((TypeImpl) type).isArray(); } public boolean isPrimitiveArrayType(Type type) { return (type instanceof TypeImpl_array) && ! type.getComponentType().isPrimitive(); } public boolean isIntArrayType(Type type) { return (type == getTypeSystemImpl().intArrayType); } public boolean isFloatArrayType(Type type) { return ((TypeImpl)type).getCode() == floatArrayTypeCode; } public boolean isStringArrayType(Type type) { return ((TypeImpl)type).getCode() == stringArrayTypeCode; } public boolean isBooleanArrayType(Type type) { return ((TypeImpl)type).getCode() == booleanArrayTypeCode; } public boolean isByteArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public boolean isShortArrayType(Type type) { return ((TypeImpl)type).getCode() == byteArrayTypeCode; } public boolean isLongArrayType(Type type) { return ((TypeImpl)type).getCode() == longArrayTypeCode; } public boolean isDoubleArrayType(Type type) { return ((TypeImpl)type).getCode() == doubleArrayTypeCode; } public boolean isFSArrayType(Type type) { return ((TypeImpl)type).getCode() == fsArrayTypeCode; } public boolean isIntType(Type type) { return ((TypeImpl)type).getCode() == intTypeCode; } public boolean isFloatType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public boolean isByteType(Type type) { return ((TypeImpl)type).getCode() == byteTypeCode; } public boolean isBooleanType(Type type) { return ((TypeImpl)type).getCode() == floatTypeCode; } public boolean isShortType(Type type) { return ((TypeImpl)type).getCode() == shortTypeCode; } public boolean isLongType(Type type) { return ((TypeImpl)type).getCode() == longTypeCode; } public boolean isDoubleType(Type type) { return ((TypeImpl)type).getCode() == doubleTypeCode; } /* * Only called on base CAS */ /** * @see org.apache.uima.cas.admin.CASMgr#initCASIndexes() */ @Override public void initCASIndexes() throws CASException { final TypeSystemImpl ts = getTypeSystemImpl(); if (!ts.isCommitted()) { throw new CASException(CASException.MUST_COMMIT_TYPE_SYSTEM); } FSIndexComparator comp = this.indexRepository.createComparator(); comp.setType(ts.sofaType); comp.addKey(ts.sofaNum, FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.SOFA_INDEX_NAME, FSIndex.BAG_INDEX); comp = this.indexRepository.createComparator(); comp.setType(ts.annotType); comp.addKey(ts.startFeat, FSIndexComparator.STANDARD_COMPARE); comp.addKey(ts.endFeat, FSIndexComparator.REVERSE_STANDARD_COMPARE); comp.addKey(this.indexRepository.getDefaultTypeOrder(), FSIndexComparator.STANDARD_COMPARE); this.indexRepository.createIndex(comp, CAS.STD_ANNOTATION_INDEX); } // /////////////////////////////////////////////////////////////////////////// // CAS support ... create CAS view of aSofa // For internal use only public CAS getView(int sofaNum) { return getViewFromSofaNbr(sofaNum); } @Override public CAS getCurrentView() { return getView(CAS.NAME_DEFAULT_SOFA); } // /////////////////////////////////////////////////////////////////////////// // JCas support @Override public JCas getJCas() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } public JCasImpl getJCasImpl() { if (this.jcas == null) { this.jcas = JCasImpl.getJCas(this); } return this.jcas; } // /** // * Internal use only // * // * @return corresponding JCas, assuming it exists // */ // public JCas getExistingJCas() { // return this.jcas; // } // // Create JCas view of aSofa @Override public JCas getJCas(SofaFS aSofa) throws CASException { // Create base JCas, if needed this.svd.baseCAS.getJCas(); return getView(aSofa).getJCas(); /* * // If a JCas already exists for this Sofa, return it JCas aJCas = (JCas) * this.svd.baseCAS.sofa2jcasMap.get(Integer.valueOf(aSofa.getSofaRef())); if * (null != aJCas) { return aJCas; } // Get view of aSofa CASImpl view = * (CASImpl) getView(aSofa); // wrap in JCas aJCas = view.getJCas(); * this.sofa2jcasMap.put(Integer.valueOf(aSofa.getSofaRef()), aJCas); return * aJCas; */ } /** * @deprecated */ @Override @Deprecated public JCas getJCas(SofaID aSofaID) throws CASException { SofaFS sofa = getSofa(aSofaID); // sofa guaranteed to be non-null by above method. return getJCas(sofa); } private CASImpl getViewFromSofaNbr(int nbr) { final ArrayList<CASImpl> sn2v = this.svd.sofaNbr2ViewMap; if (nbr < sn2v.size()) { return sn2v.get(nbr); } return null; } void setViewForSofaNbr(int nbr, CASImpl view) { Misc.setWithExpand(this.svd.sofaNbr2ViewMap, nbr, view); } // For internal platform use only CASImpl getInitialView() { CASImpl couldBeThis = getViewFromSofaNbr(1); if (couldBeThis != null) { return couldBeThis; } // create the initial view, without a Sofa CASImpl aView = new CASImpl(this.svd.baseCAS, (SofaFS) null); setViewForSofaNbr(1, aView); assert (this.svd.viewCount <= 1); this.svd.viewCount = 1; return aView; } @Override public CAS createView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // Can't use name of Initial View if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { throw new CASRuntimeException(CASRuntimeException.SOFANAME_ALREADY_EXISTS, aSofaID); } Sofa newSofa = createSofa(absoluteSofaName, null); CAS newView = getView(newSofa); ((CASImpl) newView).registerView(newSofa); return newView; } @Override public CAS getView(String aSofaID) { // do sofa mapping for current component String absoluteSofaName = null; if (getCurrentComponentInfo() != null) { absoluteSofaName = getCurrentComponentInfo().mapToSofaID(aSofaID); } if (absoluteSofaName == null) { absoluteSofaName = aSofaID; } // if this resolves to the Initial View, return view(1)... // ... as the Sofa for this view may not exist yet if (CAS.NAME_DEFAULT_SOFA.equals(absoluteSofaName)) { return getInitialView(); } // get Sofa and switch to view SofaFS sofa = getSofa(absoluteSofaName); // sofa guaranteed to be non-null by above method // unless sofa doesn't exist, which will cause a throw. return getView(sofa); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getView(org.apache.uima.cas.SofaFS) * * Callers of this can have created Sofas in the CAS without views: using the * old deprecated createSofa apis (this is being fixed so these will create * the views) via deserialization, which will put the sofaFSs into the CAS * without creating the views, and then call this to create the views. - for * deserialization: there are 2 kinds: 1 is xmi the other is binary. - for * xmi: there is 1.4.x compatible and 2.1 compatible. The older format can * have sofaNbrs in the order 2, 3, 4, 1 (initial sofa), 5, 6, 7 The newer * format has them in order. For deserialized sofas, we insure here that there * are no duplicates. This is not done in the deserializers - they use either * heap dumping (binary) or generic fs creators (xmi). * * Goal is to detect case where check is needed (sofa exists, but view not yet * created). This is done by looking for cases where sofaNbr &gt; curViewCount. * This only works if the sofaNbrs go up by 1 (except for the initial sofa) in * the input sequence of calls. */ @Override public CASImpl getView(SofaFS aSofa) { Sofa sofa = (Sofa) aSofa; final int sofaNbr = sofa.getSofaRef(); // final Integer sofaNbrInteger = Integer.valueOf(sofaNbr); CASImpl aView = getViewFromSofaNbr(sofaNbr); if (null == aView) { // This is the deserializer case, or the case where an older API created a // sofa, // which is now creating the associated view // create a new CAS view aView = new CASImpl(this.svd.baseCAS, sofa); setViewForSofaNbr(sofaNbr, aView); verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, sofa); return aView; } // for deserialization - might be reusing a view, and need to tie new Sofa // to old View if (null == aView.mySofaRef) { aView.mySofaRef = sofa; } verifySofaNameUniqueIfDeserializedViewAdded(sofaNbr, aSofa); return aView; } // boolean isSofaView(int sofaAddr) { // if (mySofaRef == null) { // // don't create initial sofa // return false; // } // return mySofaRef == sofaAddr; // } /* * for Sofas being added (determined by sofaNbr &gt; curViewCount): verify sofa * name is not already present, and record it for future tests * * Only should do the name test & update in the case of deserialized new sofas * coming in. These will come in, in order. Exception is "_InitialView" which * could come in the middle. If it comes in the middle, no test will be done * for duplicates, and it won't be added to set of known names. This is ok * because the createVIew special cases this test. Users could corrupt an xmi * input, which would make this logic fail. */ private void verifySofaNameUniqueIfDeserializedViewAdded(int sofaNbr, SofaFS aSofa) { final int curViewCount = this.svd.viewCount; if (curViewCount < sofaNbr) { // Only true for deserialized sofas with new views being either created, // or // hooked-up from CASes that were freshly reset, which have multiple // views. // Assume sofa numbers are incrementing by 1 assert (sofaNbr == curViewCount + 1); this.svd.viewCount = sofaNbr; String id = aSofa.getSofaID(); // final Feature idFeat = // getTypeSystem().getFeatureByFullName(CAS.FEATURE_FULL_NAME_SOFAID); // String id = // ll_getStringValue(((FeatureStructureImpl)aSofa).getAddress(), // ((FeatureImpl) idFeat).getCode()); Misc.assertUie(this.svd.sofaNameSet.contains(id)); // this.svd.sofaNameSet.add(id); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getTypeSystem() */ @Override public LowLevelTypeSystem ll_getTypeSystem() { return getTypeSystemImpl().getLowLevelTypeSystem(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getIndexRepository() */ @Override public LowLevelIndexRepository ll_getIndexRepository() { return this.indexRepository; } /** * * @param fs * @param domType * @param featCode */ private final void checkLowLevelParams(TOP fs, TypeImpl domType, int featCode) { checkFeature(featCode); checkTypeHasFeature(domType, featCode); } /** * Check that the featCode is a feature of the domain type * @param domTypeCode * @param featCode */ private final void checkTypeHasFeature(TypeImpl domainType, int featureCode) { checkTypeHasFeature(domainType, getFeatFromCode_checked(featureCode)); } private final void checkTypeHasFeature(TypeImpl domainType, FeatureImpl feature) { if (!domainType.isAppropriateFeature(feature)) { throw new LowLevelException(LowLevelException.FEAT_DOM_ERROR, Integer.valueOf(domainType.getCode()), domainType.getName(), Integer.valueOf(feature.getCode()), feature.getName()); } } /** * Check the range is appropriate for this type/feature. Throws * LowLevelException if it isn't. * * @param domType * domain type * @param ranType * range type * @param feat * feature */ public final void checkTypingConditions(Type domType, Type ranType, Feature feat) { TypeImpl domainTi = (TypeImpl) domType; FeatureImpl fi = (FeatureImpl) feat; checkTypeHasFeature(domainTi, fi); if (!((TypeImpl) fi.getRange()).subsumes((TypeImpl) ranType)) { throw new LowLevelException(LowLevelException.FEAT_RAN_ERROR, Integer.valueOf(fi.getCode()), feat.getName(), Integer.valueOf(((TypeImpl)ranType).getCode()), ranType.getName()); } } /** * Validate a feature's range is a ref to a feature structure * @param featCode * @throws LowLevelException */ private final void checkFsRan(FeatureImpl fi) throws LowLevelException { if (!fi.getRangeImpl().isRefType) { throw new LowLevelException(LowLevelException.FS_RAN_TYPE_ERROR, Integer.valueOf(fi.getCode()), fi.getName(), fi.getRange().getName()); } } private final void checkFeature(int featureCode) { if (!getTypeSystemImpl().isFeature(featureCode)) { throw new LowLevelException(LowLevelException.INVALID_FEATURE_CODE, Integer.valueOf(featureCode)); } } private TypeImpl getTypeFromCode(int typeCode) { return getTypeSystemImpl().getTypeForCode(typeCode); } private TypeImpl getTypeFromCode_checked(int typeCode) { return getTypeSystemImpl().getTypeForCode_checked(typeCode); } private FeatureImpl getFeatFromCode_checked(int featureCode) { return getTypeSystemImpl().getFeatureForCode_checked(featureCode); } public final <T extends TOP> T getFsFromId_checked(int fsRef) { T r = getFsFromId(fsRef); if (r == null) { if (fsRef == 0) { return null; } LowLevelException e = new LowLevelException(LowLevelException.INVALID_FS_REF, Integer.valueOf(fsRef)); // this form to enable seeing this even if the // throwable is silently handled. // System.err.println("debug " + e); throw e; } return r; } @Override public final boolean ll_isRefType(int typeCode) { return getTypeFromCode(typeCode).isRefType; } @Override public final int ll_getTypeClass(int typeCode) { return TypeSystemImpl.getTypeClass(getTypeFromCode(typeCode)); } // backwards compatibility only @Override public final int ll_createFS(int typeCode) { return ll_createFS(typeCode, true); } @Override public final int ll_createFS(int typeCode, boolean doCheck) { TypeImpl ti = (TypeImpl) getTypeSystemImpl().ll_getTypeForCode(typeCode); if (doCheck) { if (ti == null || !ti.isCreatableAndNotBuiltinArray()) { throw new LowLevelException(LowLevelException.CREATE_FS_OF_TYPE_ERROR, Integer.valueOf(typeCode)); } } TOP fs = (TOP) createFS(ti); if (!fs._isPearTrampoline()) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); // hold on to it if nothing else is } else { svd.id2fs.put(fs); } } return fs._id; } /** * used for ll_setIntValue which changes type code * @param ti - the type of the created FS * @param id - the id to use * @return the FS */ private TOP createFsWithExistingId(TypeImpl ti, int id) { svd.reuseId = id; try { TOP fs = createFS(ti); svd.id2fs.putChange(id, fs); return fs; } finally { svd.reuseId = 0; } } /* /** * @param arrayLength * @return the id of the created array * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_createArray(int, int) */ @Override public int ll_createArray(int typeCode, int arrayLength) { TOP fs = createArray(getTypeFromCode_checked(typeCode), arrayLength); if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally(fs); } else { svd.id2fs.put(fs); } return fs._id; } /** * (for backwards compatibility with V2 CASImpl) * Create a temporary (i.e., per document) array FS on the heap. * * @param type * The type code of the array to be created. * @param len * The length of the array to be created. * @return - * @exception ArrayIndexOutOfBoundsException * If <code>type</code> is not a type. */ public int createTempArray(int type, int len) { return ll_createArray(type, len); } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createByteArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().byteArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createBooleanArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().booleanArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createShortArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().shortArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createLongArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().longArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createDoubleArray(int arrayLength) { TOP fs = createArray(getTypeSystemImpl().doubleArrayType, arrayLength); svd.id2fs.put(fs); return fs._id; } /** * @param arrayLength - * @return the id of the created array */ @Override public int ll_createArray(int typeCode, int arrayLength, boolean doChecks) { TypeImpl ti = getTypeFromCode_checked(typeCode); if (doChecks) { if (!ti.isArray()) { throw new LowLevelException(LowLevelException.CREATE_ARRAY_OF_TYPE_ERROR, Integer.valueOf(typeCode), ti.getName()); } if (arrayLength < 0) { throw new LowLevelException(LowLevelException.ILLEGAL_ARRAY_LENGTH, Integer.valueOf(arrayLength)); } } TOP fs = createArray(ti, arrayLength); svd.id2fs.put(fs); return fs._id; } public void validateArraySize(int length) { if (length < 0) { /** Array size must be &gt;= 0. */ throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } /** * Safety - any time the low level API to a FS is requested, * hold on to that FS until CAS reset to mimic how v2 works. */ @Override public final int ll_getFSRef(FeatureStructure fs) { if (null == fs) { return NULL; } TOP fst = (TOP) fs; if (fst._isPearTrampoline()) { return fst._id; // no need to hold on to this one - it's in jcas hash maps } // uncond. because this method can be called multiple times svd.id2fs.putUnconditionally(fst); // hold on to it return ((FeatureStructureImplC)fs)._id; } @Override public <T extends TOP> T ll_getFSForRef(int id) { return getFsFromId_checked(id); } /** * Handle some unusual backwards compatibility cases * featureCode = 0 - implies getting the type code * feature range is int - normal * feature range is a fs reference, return the id * feature range is a string: add the string if not already present to the string heap, return the int handle. * @param fsRef - * @param featureCode - * @return - */ @Override public final int ll_getIntValue(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { return fs._getTypeImpl().getCode(); // case where the type is being requested } FeatureImpl fi = getFeatFromCode_checked(featureCode); SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: return fs.getFeatureValue(fi)._id; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: return fs._getIntValueNc(fi); case Slot_StrRef: return getCodeForString(fs._getStringValueNc(fi)); case Slot_LongRef: return getCodeForLong(fs._getLongValueNc(fi)); case Slot_DoubleRef: return getCodeForLong(CASImpl.double2long(fs._getDoubleValueNc(fi))); default: throw new CASRuntimeException( CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); } } // public final int ll_getIntValueFeatOffset(int fsRef, int featureOffset) { // return ll_getFSForRef(fsRef)._intData[featureOffset]; // } @Override public final float ll_getFloatValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFloatValue(getFeatFromCode_checked(featureCode)); } @Override public final String ll_getStringValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getStringValue(getFeatFromCode_checked(featureCode)); } // public final String ll_getStringValueFeatOffset(int fsRef, int featureOffset) { // return (String) getFsFromId_checked(fsRef)._refData[featureOffset]; // } @Override public final int ll_getRefValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } // public final int ll_getRefValueFeatOffset(int fsRef, int featureOffset) { // return ((FeatureStructureImplC)getFsFromId_checked(fsRef)._refData[featureOffset]).id(); // } @Override public final int ll_getIntValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getIntValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getFloatValue(int, int, * boolean) */ @Override public final float ll_getFloatValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getFloatValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getStringValue(int, int, * boolean) */ @Override public final String ll_getStringValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getStringValue(fsRef, featureCode); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getRefValue(int, int, boolean) */ @Override public final int ll_getRefValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } return getFsFromId_checked(fsRef).getFeatureValue(getFeatFromCode_checked(featureCode))._id(); } /** * This is the method all normal FS feature "setters" call before doing the set operation * on values where the range could be used as an index key. * <p> * If enabled, it will check if the update may corrupt any index in any view. The check tests * whether the feature is being used as a key in one or more indexes and if the FS is in one or more * corruptable view indexes. * <p> * If true, then: * <ul> * <li>it may remove and remember (for later adding-back) the FS from all corruptable indexes * (bag indexes are not corruptable via updating, so these are skipped). * The addback occurs later either via an explicit call to do so, or the end of a protectIndex block, or. * (if autoIndexProtect is enabled) after the individual feature update is completed.</li> * <li>it may give a WARN level message to the log. This enables users to * implement their own optimized handling of this for "high performance" * applications which do not want the overhead of runtime checking. </li></ul> * <p> * * @param fs - the FS to test if it is in the indexes * @param featCode - the feature being tested * @return true if something may need to be added back */ private boolean checkForInvalidFeatureSetting(TOP fs, int featCode) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = checkForInvalidFeatureSetting2(fs); if (wasRemoved && doCorruptReport()) { featModWhileInIndexReport(fs, featCode); } return wasRemoved; } return false; } /** * version for deserializers, and for set document language, using their own store for toBeAdded * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, int featCode, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { if (!svd.featureCodesInIndexKeys.get(featCode)) { // skip if no index uses this feature return false; } boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, featCode); // } return wasRemoved; } return false; } /** * version for deserializers, using their own store for toBeAdded * and not bothering to check for particular features * Doesn't report updating of corruptable slots. * @param fs - * @param featCode - * @param toBeAdded - * @return - */ boolean checkForInvalidFeatureSetting(TOP fs, FSsTobeAddedback toBeAdded) { if (doInvalidFeatSettingCheck(fs)) { boolean wasRemoved = removeFromCorruptableIndexAnyView(fs, toBeAdded); // if (wasRemoved && doCorruptReport()) { // featModWhileInIndexReport(fs, null); // } return wasRemoved; } return false; } // // version of above, but using jcasFieldRegistryIndex // private boolean checkForInvalidFeatureSettingJFRI(TOP fs, int jcasFieldRegistryIndex) { // if (doInvalidFeatSettingCheck(fs) && // svd.featureJiInIndexKeys.get(jcasFieldRegistryIndex)) { // // boolean wasRemoved = checkForInvalidFeatureSetting2(fs); // //// if (wasRemoved && doCorruptReport()) { //// featModWhileInIndexReport(fs, getFeatFromRegistry(jcasFieldRegistryIndex)); //// } // return wasRemoved; // } // return false; // } private boolean checkForInvalidFeatureSetting2(TOP fs) { final int ssz = svd.fssTobeAddedback.size(); // next method skips if the fsRef is not in the index (cache) boolean wasRemoved = removeFromCorruptableIndexAnyView( fs, (ssz > 0) ? getAddback(ssz) : // validates single not in use getAddbackSingle() // validates single usage at a time ); if (!wasRemoved && svd.fsTobeAddedbackSingleInUse) { svd.fsTobeAddedbackSingleInUse = false; } return wasRemoved; } // public FeatureImpl getFeatFromRegistry(int jcasFieldRegistryIndex) { // return getFSClassRegistry().featuresFromJFRI[jcasFieldRegistryIndex]; // } private boolean doCorruptReport() { return // skip message if wasn't removed // skip message if protected in explicit block IS_REPORT_FS_UPDATE_CORRUPTS_INDEX && svd.fssTobeAddedback.size() == 0; } /** * * @param fs - * @return false if the fs is not in a set or sorted index (bit in fs), or * the auto protect is disabled and we're not in an explicit protect block */ private boolean doInvalidFeatSettingCheck(TOP fs) { if (!fs._inSetSortedIndex()) { return false; } final int ssz = svd.fssTobeAddedback.size(); // skip if protection is disabled, and no explicit protection block if (IS_DISABLED_PROTECT_INDEXES && ssz == 0) { return false; } return true; } private void featModWhileInIndexReport(FeatureStructure fs, int featCode) { featModWhileInIndexReport(fs, getFeatFromCode_checked(featCode)); } private void featModWhileInIndexReport(FeatureStructure fs, FeatureImpl fi) { // prepare a message which includes the feature which is a key, the fs, and // the call stack. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new Throwable().printStackTrace(pw); pw.close(); String msg = String.format( "While FS was in the index, the feature \"%s\"" + ", which is used as a key in one or more indexes, " + "was modified\n FS = \"%s\"\n%s%n", (fi == null)? "for-all-features" : fi.getName(), fs.toString(), sw.toString()); UIMAFramework.getLogger().log(Level.WARNING, msg); if (IS_THROW_EXCEPTION_CORRUPT_INDEX) { throw new UIMARuntimeException(UIMARuntimeException.ILLEGAL_FS_FEAT_UPDATE, new Object[]{}); } } /** * Only called if there was something removed that needs to be added back * * skip the addback (to defer it until later) if: * - running in block mode (you can tell this if svd.fssTobeAddedback.size() &gt; 0) or * if running in block mode, the add back is delayed until the end of the block * * @param fs the fs to add back */ public void maybeAddback(TOP fs) { if (svd.fssTobeAddedback.size() == 0) { assert(svd.fsTobeAddedbackSingleInUse); svd.fsTobeAddedbackSingle.addback(fs); svd.fsTobeAddedbackSingleInUse = false; } } boolean removeFromCorruptableIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded) { return removeFromIndexAnyView(fs, toBeAdded, FSIndexRepositoryImpl.SKIP_BAG_INDEXES); } /** * This might be called from low level set int value, if we support switching types, and we want to * remove the old type from all indexes. * @param fs the fs to maybe remove * @param toBeAdded a place to record the removal so we can add it back later * @param isSkipBagIndexes is true usually, we don't need to remove/readd to bag indexes (except for the case * of supporting switching types via low level set int for v2 backwards compatibility) * @return true if was removed from one or more indexes */ boolean removeFromIndexAnyView(final TOP fs, FSsTobeAddedback toBeAdded, boolean isSkipBagIndexes) { final TypeImpl ti = ((FeatureStructureImplC)fs)._getTypeImpl(); if (ti.isAnnotationBaseType()) { boolean r = removeAndRecord(fs, (FSIndexRepositoryImpl) fs._casView.getIndexRepository(), toBeAdded, isSkipBagIndexes); fs._resetInSetSortedIndex(); return r; } // not a subtype of AnnotationBase, need to check all views (except base) // sofas indexed in the base view are not corruptable. final Iterator<CAS> viewIterator = getViewIterator(); boolean wasRemoved = false; while (viewIterator.hasNext()) { wasRemoved |= removeAndRecord(fs, (FSIndexRepositoryImpl) viewIterator.next().getIndexRepository(), toBeAdded, isSkipBagIndexes); } fs._resetInSetSortedIndex(); return wasRemoved; } /** * remove a FS from all indexes in this view (except bag indexes, if isSkipBagIndex is true) * @param fs the fs to be removed * @param ir the view * @param toBeAdded the place to record how many times it was in the index, per view * @param isSkipBagIndex set to true for corruptable removes, false for remove in all cases from all indexes * @return true if it was removed, false if it wasn't in any corruptable index. */ private boolean removeAndRecord(TOP fs, FSIndexRepositoryImpl ir, FSsTobeAddedback toBeAdded, boolean isSkipBagIndex) { boolean wasRemoved = ir.removeFS_ret(fs, isSkipBagIndex); if (wasRemoved) { toBeAdded.recordRemove(fs, ir, 1); } return wasRemoved; } /** * Special considerations: * Interface with corruption checking * For backwards compatibility: * handle cases where feature is: * int - normal * 0 - change type code * a ref: treat int as FS "addr" * not an int: handle like v2 where reasonable */ @Override public final void ll_setIntValue(int fsRef, int featureCode, int value) { TOP fs = getFsFromId_checked(fsRef); if (featureCode == 0) { switchFsType(fs, value); return; } FeatureImpl fi = getFeatFromCode_checked(featureCode); if (fs._getTypeImpl().isArray()) { throw new UnsupportedOperationException("ll_setIntValue not permitted to set a feature of an array"); } SlotKind kind = fi.getSlotKind(); switch(kind) { case Slot_HeapRef: if (fi.getCode() == annotBaseSofaFeatCode) { // setting the sofa ref of an annotationBase // can't change this so just verify it's the same TOP sofa = fs.getFeatureValue(fi); if (sofa._id != value) { throw new UnsupportedOperationException("ll_setIntValue not permitted to change a sofaRef feature"); } return; // if the same, just ignore, already set } TOP ref = fs._casView.getFsFromId_checked(value); fs.setFeatureValue(fi, ref); // does the right feature check, too return; case Slot_Boolean: case Slot_Byte: case Slot_Short: case Slot_Int: case Slot_Float: fs._setIntValueCJ(fi, value); break; case Slot_StrRef: String s = getStringForCode(value); if (s == null && value != 0) { Misc.internalError(new Exception("ll_setIntValue got null string for non-0 handle: " + value)); } fs._setRefValueNfcCJ(fi, getStringForCode(value)); break; case Slot_LongRef: case Slot_DoubleRef: Long lng = getLongForCode(value); if (lng == null) { Misc.internalError(new Exception("ll_setIntValue got null Long/Double for handle: " + value)); } fs._setLongValueNfcCJ(fi, lng); break; default: CASRuntimeException e = new CASRuntimeException(CASRuntimeException.INAPPROP_RANGE, fi.getName(), "int", fi.getRange().getName()); // System.err.println("debug " + e); throw e; } } private String getStringForCode(int i) { if (null == svd.llstringSet) { return null; } return svd.llstringSet.getStringForCode(i); } private int getCodeForString(String s) { if (null == svd.llstringSet) { svd.llstringSet = new StringSet(); } return svd.llstringSet.getCodeForString(s); // avoids adding duplicates } private Long getLongForCode(int i) { if (null == svd.lllongSet) { return null; } return svd.lllongSet.getLongForCode(i); } private int getCodeForLong(long s) { if (null == svd.lllongSet) { svd.lllongSet = new LongSet(); } return svd.lllongSet.getCodeForLong(s); // avoids adding duplicates } private void switchFsType(TOP fs, int value) { // throw new UnsupportedOperationException(); // case where the type is being changed // if the new type is a sub/super type of the existing type, // some field data may be copied // if not, no data is copied. // // Item is removed from index and re-indexed // to emulate what V2 did, // the indexing didn't change // all the slots were the same // boolean wasRemoved = removeFromIndexAnyView(fs, getAddbackSingle(), FSIndexRepositoryImpl.INCLUDE_BAG_INDEXES); if (!wasRemoved) { svd.fsTobeAddedbackSingleInUse = false; } TypeImpl newType = getTypeFromCode_checked(value); Class<?> newClass = newType.getJavaClass(); if ((fs instanceof UimaSerializable) || UimaSerializable.class.isAssignableFrom(newClass)) { throw new UnsupportedOperationException("can't switch type to/from UimaSerializable"); } // Measurement - record which type gets switched to which other type // count how many times // record which JCas cover class goes with each type // key = old type, new type, old jcas cover class, new jcas cover class // value = count MeasureSwitchType mst = null; if (MEASURE_SETINT) { MeasureSwitchType key = new MeasureSwitchType(fs._getTypeImpl(), newType); synchronized (measureSwitches) { // map access / updating must be synchronized mst = measureSwitches.get(key); if (null == mst) { measureSwitches.put(key, key); mst = key; } mst.count ++; mst.newSubsumesOld = newType.subsumes(fs._getTypeImpl()); mst.oldSubsumesNew = fs._getTypeImpl().subsumes(newType); } } if (newClass == fs._getTypeImpl().getJavaClass() || newType.subsumes(fs._getTypeImpl())) { // switch in place fs._setTypeImpl(newType); return; } // if types don't subsume each other, we // deviate a bit from V2 behavior // and skip copying the feature slots boolean isOkToCopyFeatures = // true || // debug fs._getTypeImpl().subsumes(newType) || newType.subsumes(fs._getTypeImpl()); // throw new CASRuntimeException(CASRuntimeException.ILLEGAL_TYPE_CHANGE, newType.getName(), fs._getTypeImpl().getName()); TOP newFs = createFsWithExistingId(newType, fs._id); // updates id -> fs map // initialize fields: if (isOkToCopyFeatures) { newFs._copyIntAndRefArraysFrom(fs); } // if (wasRemoved) { // addbackSingle(newFs); // } // replace refs in existing FSs with new // will miss any fs's held by user code - no way to fix that without // universal indirection - very inefficient, so just accept for now long st = System.nanoTime(); walkReachablePlusFSsSorted(fsItem -> { if (fsItem._getTypeImpl().hasRefFeature) { if (fsItem instanceof FSArray) { TOP[] a = ((FSArray)fsItem)._getTheArray(); for (int i = 0; i < a.length; i++) { if (fs == a[i]) { a[i] = newFs; } } return; } final int sz = fsItem._getTypeImpl().nbrOfUsedRefDataSlots; for (int i = 0; i < sz; i++) { Object o = fsItem._getRefValueCommon(i); if (o == fs) { fsItem._setRefValueCommon(i, newFs); // fsItem._refData[i] = newFs; } } } }, null, // mark null, // null or predicate for filtering what gets added null); // null or type mapper, skips if not in other ts if (MEASURE_SETINT) { mst.scantime += System.nanoTime() - st; } } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value) { getFsFromId_checked(fsRef).setFloatValue(getFeatFromCode_checked(featureCode), value); } // public final void ll_setFloatValueNoIndexCorruptionCheck(int fsRef, int featureCode, float value) { // setFeatureValueNoIndexCorruptionCheck(fsRef, featureCode, float2int(value)); // } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value) { getFsFromId_checked(fsRef).setStringValue(getFeatFromCode_checked(featureCode), value); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value) { // no index check because refs can't be keys setFeatureValue(fsRef, featureCode, getFsFromId_checked(value)); } @Override public final void ll_setIntValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setIntValue(fsRef, featureCode, value); } @Override public final void ll_setFloatValue(int fsRef, int featureCode, float value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setFloatValue(fsRef, featureCode, value); } @Override public final void ll_setStringValue(int fsRef, int featureCode, String value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setStringValue(fsRef, featureCode, value); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setCharBufferValue(fsRef, featureCode, buffer, start, length); } @Override public final void ll_setCharBufferValue(int fsRef, int featureCode, char[] buffer, int start, int length) { ll_setStringValue(fsRef, featureCode, new String(buffer, start, length)); } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_copyCharBufferValue(int, int, * char, int) */ @Override public int ll_copyCharBufferValue(int fsRef, int featureCode, char[] buffer, int start) { String str = ll_getStringValue(fsRef, featureCode); if (str == null) { return -1; } final int len = str.length(); final int requestedMax = start + len; // Check that the buffer is long enough to copy the whole string. If it isn't long enough, we // copy up to buffer.length - start characters. final int max = (buffer.length < requestedMax) ? (buffer.length - start) : len; for (int i = 0; i < max; i++) { buffer[start + i] = str.charAt(i); } return len; } /* * (non-Javadoc) * * @see org.apache.uima.cas.impl.LowLevelCAS#ll_getCharBufferValueSize(int, * int) */ @Override public int ll_getCharBufferValueSize(int fsRef, int featureCode) { String str = ll_getStringValue(fsRef, featureCode); return str.length(); } @Override public final void ll_setRefValue(int fsRef, int featureCode, int value, boolean doTypeChecks) { if (doTypeChecks) { checkFsRefConditions(fsRef, featureCode); } ll_setRefValue(fsRef, featureCode, value); } public final int getIntArrayValue(IntegerArray array, int i) { return array.get(i); } public final float getFloatArrayValue(FloatArray array, int i) { return array.get(i); } public final String getStringArrayValue(StringArray array, int i) { return array.get(i); } public final FeatureStructure getRefArrayValue(FSArray array, int i) { return array.get(i); } @Override public final int ll_getIntArrayValue(int fsRef, int position) { return getIntArrayValue(((IntegerArray)getFsFromId_checked(fsRef)), position); } @Override public final float ll_getFloatArrayValue(int fsRef, int position) { return getFloatArrayValue(((FloatArray)getFsFromId_checked(fsRef)), position); } @Override public final String ll_getStringArrayValue(int fsRef, int position) { return getStringArrayValue(((StringArray)getFsFromId_checked(fsRef)), position); } @Override public final int ll_getRefArrayValue(int fsRef, int position) { return ((TOP)getRefArrayValue(((FSArray)getFsFromId_checked(fsRef)), position))._id(); } private void throwAccessTypeError(int fsRef, int typeCode) { throw new LowLevelException(LowLevelException.ACCESS_TYPE_ERROR, Integer.valueOf(fsRef), Integer.valueOf(typeCode), getTypeSystemImpl().ll_getTypeForCode(typeCode).getName(), getTypeSystemImpl().ll_getTypeForCode(ll_getFSRefType(fsRef)).getName()); } public final void checkArrayBounds(int fsRef, int pos) { final int arrayLength = ll_getArraySize(fsRef); if ((pos < 0) || (pos >= arrayLength)) { throw new ArrayIndexOutOfBoundsException(pos); // LowLevelException e = new LowLevelException( // LowLevelException.ARRAY_INDEX_OUT_OF_RANGE); // e.addArgument(Integer.toString(pos)); // throw e; } } public final void checkArrayBounds(int arrayLength, int pos, int length) { if ((pos < 0) || (length < 0) || ((pos + length) > arrayLength)) { throw new LowLevelException(LowLevelException.ARRAY_INDEX_LENGTH_OUT_OF_RANGE, Integer.toString(pos), Integer.toString(length)); } } /** * Check that the fsRef is valid. * Check that the fs is featureCode belongs to the fs * Check that the featureCode is one of the features of the domain type of the fsRef * feat could be primitive, string, ref to another feature * * @param fsRef * @param typeCode * @param featureCode */ private final void checkNonArrayConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); final TypeImpl domainType = (TypeImpl) fs.getType(); // checkTypeAt(domType, fs); // since the type is from the FS, it's always OK checkFeature(featureCode); // checks that the featureCode is in the range of all feature codes TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkTypeHasFeature(domainType, fi); // checks that the feature code is one of the features of the type // checkFsRan(fi); } private final void checkFsRefConditions(int fsRef, int featureCode) { TOP fs = getFsFromId_checked(fsRef); checkLowLevelParams(fs, fs._getTypeImpl(), featureCode); // checks type has feature TypeSystemImpl tsi = getTypeSystemImpl(); FeatureImpl fi = tsi.getFeatureForCode_checked(featureCode); checkFsRan(fi); // next not needed because checkFsRan already validates this // checkFsRef(fsRef + this.svd.casMetadata.featureOffset[featureCode]); } // private final void checkArrayConditions(int fsRef, int typeCode, // int position) { // checkTypeSubsumptionAt(fsRef, typeCode); // // skip this next test because // // a) it's done implicitly in the bounds check and // // b) it fails for arrays stored outside of the main heap (e.g., // byteArrays, etc.) // // checkFsRef(getArrayStartAddress(fsRef) + position); // checkArrayBounds(fsRef, position); // } private final void checkPrimitiveArrayConditions(int fsRef, int typeCode, int position) { if (typeCode != ll_getFSRefType(fsRef)) { throwAccessTypeError(fsRef, typeCode); } checkArrayBounds(fsRef, position); } @Override public final int ll_getIntArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } return ll_getIntArrayValue(fsRef, position); } @Override public float ll_getFloatArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } return ll_getFloatArrayValue(fsRef, position); } @Override public String ll_getStringArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } return ll_getStringArrayValue(fsRef, position); } @Override public int ll_getRefArrayValue(int fsRef, int position, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } return ll_getRefArrayValue(fsRef, position); } @Override public void ll_setIntArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, intArrayTypeCode, position); } ll_setIntArrayValue(fsRef, position, value); } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, floatArrayTypeCode, position); } ll_setFloatArrayValue(fsRef, position, value); } @Override public void ll_setStringArrayValue(int fsRef, int position, String value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, stringArrayTypeCode, position); } ll_setStringArrayValue(fsRef, position, value); } @Override public void ll_setRefArrayValue(int fsRef, int position, int value, boolean doTypeChecks) { if (doTypeChecks) { checkPrimitiveArrayConditions(fsRef, fsArrayTypeCode, position); } ll_setRefArrayValue(fsRef, position, value); } /* ************************ * Low Level Array Setters * ************************/ @Override public void ll_setIntArrayValue(int fsRef, int position, int value) { IntegerArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setFloatArrayValue(int fsRef, int position, float value) { FloatArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setStringArrayValue(int fsRef, int position, String value) { StringArray array = getFsFromId_checked(fsRef); array.set(position, value); // that set operation does required journaling } @Override public void ll_setRefArrayValue(int fsRef, int position, int value) { FSArray array = getFsFromId_checked(fsRef); array.set(position, getFsFromId_checked(value)); // that set operation does required journaling } /** * @param fsRef an id for a FS * @return the type code for this FS */ @Override public int ll_getFSRefType(int fsRef) { return getFsFromId_checked(fsRef)._getTypeCode(); } @Override public int ll_getFSRefType(int fsRef, boolean doChecks) { // type code is always valid return ll_getFSRefType(fsRef); } @Override public LowLevelCAS getLowLevelCAS() { return this; } @Override public int size() { throw new UIMARuntimeException(UIMARuntimeException.INTERNAL_ERROR); } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#getJCasClassLoader() */ @Override public ClassLoader getJCasClassLoader() { return this.svd.jcasClassLoader; } /* * Called to set the overall jcas class loader to use. * * @see org.apache.uima.cas.admin.CASMgr#setJCasClassLoader(java.lang.ClassLoader) */ @Override public void setJCasClassLoader(ClassLoader classLoader) { this.svd.jcasClassLoader = classLoader; } // Internal use only, public for cross package use // Assumes: The JCasClassLoader for a CAS is set up initially when the CAS is // created // and not switched (other than by this code) once it is set. // Callers of this method always code the "restoreClassLoaderUnlockCAS" in // pairs, // protected as needed with try - finally blocks. // // Special handling is needed for CAS Mulipliers - they can modify a cas up to // the point they no longer "own" it. // So the try / finally approach doesn't fit public void switchClassLoaderLockCas(Object userCode) { switchClassLoaderLockCasCL(userCode.getClass().getClassLoader()); } public void switchClassLoaderLockCasCL(ClassLoader newClassLoader) { // lock out CAS functions to which annotator should not have access enableReset(false); svd.switchClassLoader(newClassLoader); } // // internal use, public for cross-package ref // public boolean usingBaseClassLoader() { // return (this.svd.jcasClassLoader == this.svd.previousJCasClassLoader); // } public void restoreClassLoaderUnlockCas() { // unlock CAS functions enableReset(true); // this might be called without the switch ever being called svd.restoreClassLoader(); } @Override public FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException { return FeatureValuePathImpl.getFeaturePath(featureValuePath); } @Override public void setOwner(CasOwner aCasOwner) { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.setOwner(aCasOwner); } else { super.setOwner(aCasOwner); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.AbstractCas_ImplBase#release() */ @Override public void release() { CASImpl baseCas = getBaseCAS(); if (baseCas != this) { baseCas.release(); } else { super.release(); } } /* ********************************** * A R R A Y C R E A T I O N ************************************/ @Override public ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ByteArray(this.getJCas(), length); } @Override public BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new BooleanArray(this.getJCas(), length); } @Override public ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new ShortArray(this.getJCas(), length); } @Override public LongArrayFS createLongArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new LongArray(this.getJCas(), length); } @Override public DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException { checkArrayPreconditions(length); return new DoubleArray(this.getJCas(), length); } @Override public byte ll_getByteValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getByteValue(getFeatFromCode_checked(featureCode)); } @Override public byte ll_getByteValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getByteValue(fsRef, featureCode); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getBooleanValue(getFeatFromCode_checked(featureCode)); } @Override public boolean ll_getBooleanValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getBooleanValue(fsRef, featureCode); } @Override public short ll_getShortValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getShortValue(getFeatFromCode_checked(featureCode)); } @Override public short ll_getShortValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getShortValue(fsRef, featureCode); } // impossible to implement in v3; change callers // public long ll_getLongValue(int offset) { // return this.getLongHeap().getHeapValue(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getLongValue(getFeatFromCode_checked(featureCode)); } // public long ll_getLongValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getLongValueOffset(offset); // } @Override public long ll_getLongValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getLongValue(fsRef, featureCode); } @Override public double ll_getDoubleValue(int fsRef, int featureCode) { return getFsFromId_checked(fsRef).getDoubleValue(getFeatFromCode_checked(featureCode)); } // public double ll_getDoubleValueFeatOffset(int fsRef, int offset) { // TOP fs = getFsFromId_checked(fsRef); // return fs.getDoubleValueOffset(offset); // } @Override public double ll_getDoubleValue(int fsRef, int featureCode, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } return ll_getDoubleValue(fsRef, featureCode); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value) { getFsFromId_checked(fsRef).setBooleanValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setBooleanValue(int fsRef, int featureCode, boolean value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setBooleanValue(fsRef, featureCode, value); } @Override public final void ll_setByteValue(int fsRef, int featureCode, byte value) { getFsFromId_checked(fsRef).setByteValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setByteValue(int fsRef, int featureCode, byte value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setByteValue(fsRef, featureCode, value); } @Override public final void ll_setShortValue(int fsRef, int featureCode, short value) { getFsFromId_checked(fsRef).setShortValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setShortValue(int fsRef, int featureCode, short value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setShortValue(fsRef, featureCode, value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value) { getFsFromId_checked(fsRef).setLongValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setLongValue(int fsRef, int featureCode, long value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setLongValue(fsRef, featureCode, value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value) { getFsFromId_checked(fsRef).setDoubleValue(getFeatFromCode_checked(featureCode), value); } @Override public void ll_setDoubleValue(int fsRef, int featureCode, double value, boolean doTypeChecks) { if (doTypeChecks) { checkNonArrayConditions(fsRef, featureCode); } ll_setDoubleValue(fsRef, featureCode, value); } @Override public byte ll_getByteArrayValue(int fsRef, int position) { return ((ByteArray) getFsFromId_checked(fsRef)).get(position); } @Override public byte ll_getByteArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getByteArrayValue(fsRef, position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position) { return ((BooleanArray) getFsFromId_checked(fsRef)).get(position); } @Override public boolean ll_getBooleanArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getBooleanArrayValue(fsRef, position); } @Override public short ll_getShortArrayValue(int fsRef, int position) { return ((ShortArray) getFsFromId_checked(fsRef)).get(position); } @Override public short ll_getShortArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getShortArrayValue(fsRef, position); } @Override public long ll_getLongArrayValue(int fsRef, int position) { return ((LongArray) getFsFromId_checked(fsRef)).get(position); } @Override public long ll_getLongArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getLongArrayValue(fsRef, position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position) { return ((DoubleArray) getFsFromId_checked(fsRef)).get(position); } @Override public double ll_getDoubleArrayValue(int fsRef, int position, boolean doTypeChecks) { return ll_getDoubleArrayValue(fsRef, position); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value) { ((ByteArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setByteArrayValue(int fsRef, int position, byte value, boolean doTypeChecks) { ll_setByteArrayValue(fsRef, position, value);} @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean b) { ((BooleanArray) getFsFromId_checked(fsRef)).set(position, b); } @Override public void ll_setBooleanArrayValue(int fsRef, int position, boolean value, boolean doTypeChecks) { ll_setBooleanArrayValue(fsRef, position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value) { ((ShortArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setShortArrayValue(int fsRef, int position, short value, boolean doTypeChecks) { ll_setShortArrayValue(fsRef, position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value) { ((LongArray) getFsFromId_checked(fsRef)).set(position, value); } @Override public void ll_setLongArrayValue(int fsRef, int position, long value, boolean doTypeChecks) { ll_setLongArrayValue(fsRef, position, value); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double d) { ((DoubleArray) getFsFromId_checked(fsRef)).set(position, d); } @Override public void ll_setDoubleArrayValue(int fsRef, int position, double value, boolean doTypeChecks) { ll_setDoubleArrayValue(fsRef, position, value); } public boolean isAnnotationType(Type t) { return ((TypeImpl)t).isAnnotationType(); } /** * @param t the type code to test * @return true if that type is subsumed by AnnotationBase type */ public boolean isSubtypeOfAnnotationBaseType(int t) { TypeImpl ti = getTypeFromCode(t); return (ti == null) ? false : ti.isAnnotationBaseType(); } public boolean isBaseCas() { return this == getBaseCAS(); } @Override public Annotation createAnnotation(Type type, int begin, int end) { // duplicates a later check // if (this.isBaseCas()) { // // Can't create annotation on base CAS // throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "createAnnotation(Type, int, int)"); // } Annotation fs = (Annotation) createFS(type); fs.setBegin(begin); fs.setEnd(end); return fs; } public int ll_createAnnotation(int typeCode, int begin, int end) { TOP fs = createAnnotation(getTypeFromCode(typeCode), begin, end); svd.id2fs.put(fs); // to prevent gc from reclaiming return fs._id(); } /** * The generic spec T extends AnnotationFS (rather than AnnotationFS) allows the method * JCasImpl getAnnotationIndex to return Annotation instead of AnnotationFS * @param <T> the Java class associated with the annotation index * @return the annotation index */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex() { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex(getTypeSystemImpl().annotType); } /* (non-Javadoc) * @see org.apache.uima.cas.CAS#getAnnotationIndex(org.apache.uima.cas.Type) */ @Override public <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException { return (AnnotationIndex<T>) indexRepository.getAnnotationIndex((TypeImpl) type); } /** * @see org.apache.uima.cas.CAS#getAnnotationType() */ @Override public Type getAnnotationType() { return getTypeSystemImpl().annotType; } /** * @see org.apache.uima.cas.CAS#getEndFeature() */ @Override public Feature getEndFeature() { return getTypeSystemImpl().endFeat; } /** * @see org.apache.uima.cas.CAS#getBeginFeature() */ @Override public Feature getBeginFeature() { return getTypeSystemImpl().startFeat; } private <T extends AnnotationFS> T createDocumentAnnotation(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); // Remove any existing document annotations. FSIterator<T> it = this.<T>getAnnotationIndex(ts.docType).iterator(); List<T> list = new ArrayList<T>(); while (it.isValid()) { list.add(it.get()); it.moveToNext(); } for (int i = 0; i < list.size(); i++) { getIndexRepository().removeFS(list.get(i)); } return (T) createDocumentAnnotationNoRemove(length); } private <T extends Annotation> T createDocumentAnnotationNoRemove(int length) { T docAnnot = createDocumentAnnotationNoRemoveNoIndex(length); addFsToIndexes(docAnnot); return docAnnot; } public <T extends Annotation> T createDocumentAnnotationNoRemoveNoIndex(int length) { final TypeSystemImpl ts = getTypeSystemImpl(); AnnotationFS docAnnot = createAnnotation(ts.docType, 0, length); docAnnot.setStringValue(ts.langFeat, CAS.DEFAULT_LANGUAGE_NAME); return (T) docAnnot; } public int ll_createDocumentAnnotation(int length) { final int fsRef = ll_createDocumentAnnotationNoIndex(0, length); ll_getIndexRepository().ll_addFS(fsRef); return fsRef; } public int ll_createDocumentAnnotationNoIndex(int begin, int end) { final TypeSystemImpl ts = getTypeSystemImpl(); int fsRef = ll_createAnnotation(ts.docType.getCode(), begin, end); ll_setStringValue(fsRef, ts.langFeat.getCode(), CAS.DEFAULT_LANGUAGE_NAME); return fsRef; } // For the "built-in" instance of Document Annotation, set the // "end" feature to be the length of the sofa string /** * updates the document annotation (only if the sofa's local string data != null) * setting the end feature to be the length of the sofa string, if any. * creates the document annotation if not present * only works if not in the base cas * */ public void updateDocumentAnnotation() { if (!mySofaIsValid() || this == this.svd.baseCAS) { return; } String newDoc = this.mySofaRef.getLocalStringData(); if (null != newDoc) { Annotation docAnnot = getDocumentAnnotationNoCreate(); if (docAnnot != null) { // use a local instance of the add-back memory because this may be called as a side effect of updating a sofa FSsTobeAddedback tobeAddedback = FSsTobeAddedback.createSingle(); boolean wasRemoved = this.checkForInvalidFeatureSetting( docAnnot, getTypeSystemImpl().endFeat.getCode(), tobeAddedback); docAnnot._setIntValueNfc(endFeatAdjOffset, newDoc.length()); if (wasRemoved) { tobeAddedback.addback(docAnnot); } } else { // not in the index (yet) createDocumentAnnotation(newDoc.length()); } } return; } /** * Generic issue: The returned document annotation could be either an instance of * DocumentAnnotation or an instance of Annotation - the Java cover class used for * annotations when JCas is not being used. */ @Override public <T extends AnnotationFS> T getDocumentAnnotation() { T docAnnot = (T) getDocumentAnnotationNoCreate(); if (null == docAnnot) { return (T) createDocumentAnnotationNoRemove(0); } else { return docAnnot; } } public <T extends AnnotationFS> T getDocumentAnnotationNoCreate() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } FSIterator<T> it = this.<T>getAnnotationIndex(getTypeSystemImpl().docType).iterator(); if (it.isValid()) { return it.get(); } return null; } /** * * @return the fs addr of the document annotation found via the index, or 0 if not there */ public int ll_getDocumentAnnotation() { if (this == this.svd.baseCAS) { // base CAS has no document return 0; } FSIterator<FeatureStructure> it = getIndexRepository().getIndex(CAS.STD_ANNOTATION_INDEX, getTypeSystemImpl().docType).iterator(); if (it.isValid()) { return it.get()._id(); } return 0; } @Override public String getDocumentLanguage() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return getDocumentAnnotation().getStringValue(getTypeSystemImpl().langFeat); } @Override public String getDocumentText() { return this.getSofaDataString(); } @Override public String getSofaDataString() { if (this == this.svd.baseCAS) { // base CAS has no document return null; } return mySofaIsValid() ? mySofaRef.getLocalStringData() : null; } @Override public FeatureStructure getSofaDataArray() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getLocalFSData() : null; } @Override public String getSofaDataURI() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaURI() : null; } @Override public InputStream getSofaDataStream() { if (this == this.svd.baseCAS) { // base CAS has no Sofa nothin return null; } // return mySofaRef.getSofaDataStream(); // this just goes to the next method return mySofaIsValid() ? this.getSofaDataStream(mySofaRef) : null; } @Override public String getSofaMimeType() { if (this == this.svd.baseCAS) { // base CAS has no Sofa return null; } return mySofaIsValid() ? mySofaRef.getSofaMime() : null; } @Override public Sofa getSofa() { return mySofaRef; } /** * @return the addr of the sofaFS associated with this view, or 0 */ @Override public int ll_getSofa() { return mySofaIsValid() ? mySofaRef._id() : 0; } @Override public String getViewName() { return (this == getViewFromSofaNbr(1)) ? CAS.NAME_DEFAULT_SOFA : mySofaIsValid() ? mySofaRef.getSofaID() : null; } private boolean mySofaIsValid() { return this.mySofaRef != null; } void setDocTextFromDeserializtion(String text) { if (mySofaIsValid()) { SofaFS sofa = getSofaRef(); // creates sofa if doesn't already exist sofa.setLocalSofaData(text); } } @Override public void setDocumentLanguage(String languageCode) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, "setDocumentLanguage(String)"); } Annotation docAnnot = getDocumentAnnotation(); FeatureImpl languageFeature = getTypeSystemImpl().langFeat; languageCode = Language.normalize(languageCode); boolean wasRemoved = this.checkForInvalidFeatureSetting(docAnnot, languageFeature.getCode(), this.getAddbackSingle()); docAnnot.setStringValue(getTypeSystemImpl().langFeat, languageCode); addbackSingleIfWasRemoved(wasRemoved, docAnnot); } private void setSofaThingsMime(Consumer<Sofa> c, String msg) { if (this == this.svd.baseCAS) { throw new CASRuntimeException(CASRuntimeException.INVALID_BASE_CAS_METHOD, msg); } Sofa sofa = getSofaRef(); c.accept(sofa); } @Override public void setDocumentText(String text) { setSofaDataString(text, "text"); } @Override public void setSofaDataString(String text, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setLocalSofaData(text, mime), "setSofaDataString(text, mime)"); } @Override public void setSofaDataArray(FeatureStructure array, String mime) { setSofaThingsMime(sofa -> sofa.setLocalSofaData(array, mime), "setSofaDataArray(FeatureStructure, mime)"); } @Override public void setSofaDataURI(String uri, String mime) throws CASRuntimeException { setSofaThingsMime(sofa -> sofa.setRemoteSofaURI(uri, mime), "setSofaDataURI(String, String)"); } @Override public void setCurrentComponentInfo(ComponentInfo info) { // always store component info in base CAS this.svd.componentInfo = info; } ComponentInfo getCurrentComponentInfo() { return this.svd.componentInfo; } /** * @see org.apache.uima.cas.CAS#addFsToIndexes(FeatureStructure fs) */ @Override public void addFsToIndexes(FeatureStructure fs) { // if (fs instanceof AnnotationBaseFS) { // final CAS sofaView = ((AnnotationBaseFS) fs).getView(); // if (sofaView != this) { // CASRuntimeException e = new CASRuntimeException( // CASRuntimeException.ANNOTATION_IN_WRONG_INDEX, new String[] { fs.toString(), // sofaView.getSofa().getSofaID(), this.getSofa().getSofaID() }); // throw e; // } // } this.indexRepository.addFS(fs); } /** * @see org.apache.uima.cas.CAS#removeFsFromIndexes(FeatureStructure fs) */ @Override public void removeFsFromIndexes(FeatureStructure fs) { this.indexRepository.removeFS(fs); } /** * @param fs the AnnotationBase instance * @return the view associated with this FS where it could be indexed */ public CASImpl getSofaCasView(AnnotationBase fs) { return fs._casView; // Sofa sofa = fs.getSofa(); // // if (null != sofa && sofa != this.getSofa()) { // return (CASImpl) this.getView(sofa.getSofaNum()); // } // // /* Note: sofa == null means annotation created from low-level APIs, without setting sofa feature // * Ignore this for backwards compatibility */ // return this; } @Override public CASImpl ll_getSofaCasView(int id) { return getSofaCasView(getFsFromId_checked(id)); } // public Iterator<CAS> getViewIterator() { // List<CAS> viewList = new ArrayList<CAS>(); // // add initial view if it has no sofa // if (!((CASImpl) getInitialView()).mySofaIsValid()) { // viewList.add(getInitialView()); // } // // add views with Sofas // FSIterator<SofaFS> sofaIter = getSofaIterator(); // while (sofaIter.hasNext()) { // viewList.add(getView(sofaIter.next())); // } // return viewList.iterator(); // } /** * Creates the initial view (without a sofa) if not present * @return the number of views, excluding the base view, including the initial view (even if not initially present or no sofa) */ public int getNumberOfViews() { CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa int nbrSofas = this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); return initialView.mySofaIsValid() ? nbrSofas : 1 + nbrSofas; } public int getNumberOfSofas() { return this.svd.baseCAS.indexRepository.getIndex(CAS.SOFA_INDEX_NAME).size(); } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator() */ @Override public <T extends CAS> Iterator<T> getViewIterator() { return new Iterator<T>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { return true; } return sofaIter.hasNext(); } @Override public T next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return (T) initialView; } return (T) getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * excludes initial view if its sofa is not valid * * @return iterator over all views except the base view */ public Iterator<CASImpl> getViewImplIterator() { return new Iterator<CASImpl>() { final CASImpl initialView = getInitialView(); // creates one if not existing, w/o sofa boolean isInitialView_but_noSofa = !initialView.mySofaIsValid(); // true if has no Sofa in initial view // but is reset to false once iterator moves // off of initial view. // if initial view has a sofa, we just use the // sofa iterator instead. final FSIterator<Sofa> sofaIter = getSofaIterator(); @Override public boolean hasNext() { if (isInitialView_but_noSofa) { // set to false once iterator moves off of first value return true; } return sofaIter.hasNext(); } @Override public CASImpl next() { if (isInitialView_but_noSofa) { isInitialView_but_noSofa = false; // no incr of sofa iterator because it was missing initial view return initialView; } return getView(sofaIter.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * iterate over all views in view order (by view number) * @param processViews */ void forAllViews(Consumer<CASImpl> processViews) { final int numViews = this.getNumberOfViews(); for (int viewNbr = 1; viewNbr <= numViews; viewNbr++) { CASImpl view = (viewNbr == 1) ? getInitialView() : (CASImpl) getView(viewNbr); processViews.accept(view); } // // Iterator<CASImpl> it = getViewImplIterator(); // while (it.hasNext()) { // processViews.accept(it.next()); // } } void forAllSofas(Consumer<Sofa> processSofa) { FSIterator<Sofa> it = getSofaIterator(); while (it.hasNext()) { processSofa.accept(it.nextNvc()); } } /** * Excludes base view's ir, * Includes the initial view's ir only if it has a sofa defined * @param processIr the code to execute */ void forAllIndexRepos(Consumer<FSIndexRepositoryImpl> processIr) { final int numViews = this.getViewCount(); for (int viewNum = 1; viewNum <= numViews; viewNum++) { processIr.accept(this.getSofaIndexRepository(viewNum)); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.CAS#getViewIterator(java.lang.String) */ @Override public Iterator<CAS> getViewIterator(String localViewNamePrefix) { // do sofa mapping for current component String absolutePrefix = null; if (getCurrentComponentInfo() != null) { absolutePrefix = getCurrentComponentInfo().mapToSofaID(localViewNamePrefix); } if (absolutePrefix == null) { absolutePrefix = localViewNamePrefix; } // find Sofas with this prefix List<CAS> viewList = new ArrayList<CAS>(); FSIterator<Sofa> sofaIter = getSofaIterator(); while (sofaIter.hasNext()) { SofaFS sofa = sofaIter.next(); String sofaId = sofa.getSofaID(); if (sofaId.startsWith(absolutePrefix)) { if ((sofaId.length() == absolutePrefix.length()) || (sofaId.charAt(absolutePrefix.length()) == '.')) { viewList.add(getView(sofa)); } } } return viewList.iterator(); } /** * protectIndexes * * Within the scope of protectIndexes, * feature updates are checked, and if found to be a key, and the FS is in a corruptable index, * then the FS is removed from the indexes (in all necessary views) (perhaps multiple times * if the FS was added to the indexes multiple times), and this removal is recorded on * an new instance of FSsTobeReindexed appended to fssTobeAddedback. * * Later, when the protectIndexes is closed, the tobe items are added back to the indies. */ @Override public AutoCloseable protectIndexes() { FSsTobeAddedback r = FSsTobeAddedback.createMultiple(this); svd.fssTobeAddedback.add(r); return r; } void dropProtectIndexesLevel () { svd.fssTobeAddedback.remove(svd.fssTobeAddedback.size() -1); } /** * This design is to support normal operations where the * addbacks could be nested * It also handles cases where nested ones were inadvertently left open * Three cases: * 1) the addbacks are the last element in the stack * - remove it from the stack * 2) the addbacks are (no longer) in the list * - leave stack alone * 3) the addbacks are in the list but not at the end * - remove it and all later ones * * If the "withProtectedindexes" approach is used, it guarantees proper * nesting, but the Runnable can't throw checked exceptions. * * You can do your own try-finally blocks (or use the try with resources * form in Java 8 to do a similar thing with no restrictions on what the * body can contain. * * @param addbacks */ void addbackModifiedFSs (FSsTobeAddedback addbacks) { final List<FSsTobeAddedback> listOfAddbackInfos = svd.fssTobeAddedback; if (listOfAddbackInfos.get(listOfAddbackInfos.size() - 1) == addbacks) { listOfAddbackInfos.remove(listOfAddbackInfos.size()); } else { int pos = listOfAddbackInfos.indexOf(addbacks); if (pos >= 0) { for (int i = listOfAddbackInfos.size() - 1; i > pos; i--) { FSsTobeAddedback toAddBack = listOfAddbackInfos.remove(i); toAddBack.addback(); } } } addbacks.addback(); } /** * * @param r an inner block of code to be run with */ @Override public void protectIndexes(Runnable r) { AutoCloseable addbacks = protectIndexes(); try { r.run(); } finally { addbackModifiedFSs((FSsTobeAddedback) addbacks); } } /** * The current implementation only supports 1 marker call per * CAS. Subsequent calls will throw an error. * * The design is intended to support (at some future point) * multiple markers; for this to work, the intent is to * extend the MarkerImpl to keep track of indexes into * these IntVectors specifying where that marker starts/ends. */ @Override public Marker createMarker() { if (!this.svd.flushEnabled) { throw new CASAdminException(CASAdminException.FLUSH_DISABLED); } this.svd.trackingMark = new MarkerImpl(this.getLastUsedFsId() + 1, this); if (this.svd.modifiedPreexistingFSs == null) { this.svd.modifiedPreexistingFSs = new IdentityHashMap<>(); } if (this.svd.modifiedPreexistingFSs.size() > 0) { errorMultipleMarkers(); } if (this.svd.trackingMarkList == null) { this.svd.trackingMarkList = new ArrayList<MarkerImpl>(); } else {errorMultipleMarkers();} this.svd.trackingMarkList.add(this.svd.trackingMark); return this.svd.trackingMark; } private void errorMultipleMarkers() { throw new CASRuntimeException(CASRuntimeException.MULTIPLE_CREATE_MARKER); } // made public https://issues.apache.org/jira/browse/UIMA-2478 public MarkerImpl getCurrentMark() { return this.svd.trackingMark; } /** * * @return an array of FsChange items, one per modified Fs, * sorted in order of fs._id */ FsChange[] getModifiedFSList() { final Map<TOP, FsChange> mods = this.svd.modifiedPreexistingFSs; FsChange[] r = mods.values().toArray(new FsChange[mods.size()]); Arrays.sort(r, 0, mods.size(), (c1, c2) -> Integer.compare(c1.fs._id, c2.fs._id)); return r; } boolean isInModifiedPreexisting(TOP fs) { return this.svd.modifiedPreexistingFSs.containsKey(fs); } @Override public String toString() { String sofa = (mySofaRef == null) ? (isBaseCas() ? "Base CAS" : "_InitialView or no Sofa") : mySofaRef.getSofaID(); // (mySofaRef == 0) ? "no Sofa" : return this.getClass().getSimpleName() + ":" + getCasId() + "[view: " + sofa + "]"; } int getCasResets() { return svd.casResets.get(); } int getCasId() { return svd.casId; } final public int getNextFsId(TOP fs) { return svd.getNextFsId(fs); } public void adjustLastFsV2size(int arrayLength) { svd.lastFsV2Size += 1 + arrayLength; // 1 is for array length value } /** * Test case use * @param fss the FSs to include in the id 2 fs map */ public void setId2FSs(FeatureStructure ... fss) { for (FeatureStructure fs : fss) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } else { svd.id2fs.put((TOP)fs); } } } // Not currently used // public Int2ObjHashMap<TOP> getId2FSs() { // return svd.id2fs.getId2fs(); // } // final private int getNextFsId() { // return ++ svd.fsIdGenerator; // } final public int getLastUsedFsId() { return svd.fsIdGenerator; } /** * Call this to capture the current value of fsIdGenerator and make it * available to other threads. * * Must be called on a thread that has been synchronized with the thread used for creating FSs for this CAS. */ final public void captureLastFsIdForOtherThread() { svd.fsIdLastValue.set(svd.fsIdGenerator); } public <T extends TOP> T getFsFromId(int id) { return (T) this.svd.id2fs.get(id); } // /** // * plus means all reachable, plus maybe others not reachable but not yet gc'd // * @param action - // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action) { // this.svd.id2fs.walkReachablePlusFSsSorted(action); // } // /** // * called for delta serialization - walks just the new items above the line // * @param action - // * @param fromId - the id of the first item to walk from // */ // public void walkReachablePlusFSsSorted(Consumer<TOP> action, int fromId) { // this.svd.id2fs.walkReachablePlueFSsSorted(action, fromId); // } /** * find all of the FSs via the indexes plus what's reachable. * sort into order by id, * * Apply the action to those * Return the list of sorted FSs * * @param action_filtered action to perform on each item after filtering * @param mark null or the mark * @param includeFilter null or a filter (exclude items not in other type system) * @param typeMapper null or how to map to other type system, used to skip things missing in other type system * @return sorted list of all found items (ignoring mark) */ public List<TOP> walkReachablePlusFSsSorted( Consumer<TOP> action_filtered, MarkerImpl mark, Predicate<TOP> includeFilter, CasTypeSystemMapper typeMapper) { List<TOP> all = new AllFSs(this, mark, includeFilter, typeMapper).getAllFSsSorted(); List<TOP> filtered = filterAboveMark(all, mark); for (TOP fs : filtered) { action_filtered.accept(fs); } return all; } static List<TOP> filterAboveMark(List<TOP> all, MarkerImpl mark) { if (null == mark) { return all; } int c = Collections.binarySearch(all, TOP._createSearchKey(mark.nextFSId), (fs1, fs2) -> Integer.compare(fs1._id, fs2._id)); if (c < 0) { c = (-c) - 1; } return all.subList(c, all.size()); } // /** // * Get the Java class corresponding to a particular type // * Only valid after type system commit // * // * @param type // * @return // */ // public <T extends FeatureStructure> Class<T> getClass4Type(Type type) { // TypeSystemImpl tsi = getTypeSystemImpl(); // if (!tsi.isCommitted()) { // throw new CASRuntimeException(CASRuntimeException.GET_CLASS_FOR_TYPE_BEFORE_TS_COMMIT); // } // // } public static boolean isSameCAS(CAS c1, CAS c2) { CASImpl ci1 = (CASImpl) c1.getLowLevelCAS(); CASImpl ci2 = (CASImpl) c2.getLowLevelCAS(); return ci1.getBaseCAS() == ci2.getBaseCAS(); } public boolean isInCAS(FeatureStructure fs) { return ((TOP)fs)._casView.getBaseCAS() == this.getBaseCAS(); } // /** // * // * @param typecode - // * @return Object that can be cast to either a 2 or 3 arg createFs functional interface // * FsGenerator or FsGeneratorArray // */ // private Object getFsGenerator(int typecode) { // return getTypeSystemImpl().getGenerator(typecode); // } public final void checkArrayPreconditions(int len) throws CASRuntimeException { // Check array size. if (len < 0) { throw new CASRuntimeException(CASRuntimeException.ILLEGAL_ARRAY_SIZE); } } public EmptyFSList getEmptyFSList() { if (null == svd.emptyFSList) { svd.emptyFSList = new EmptyFSList(getTypeSystemImpl().fsEListType, this); } return svd.emptyFSList; } public EmptyFloatList getEmptyFloatList() { if (null == svd.emptyFloatList) { svd.emptyFloatList = new EmptyFloatList(getTypeSystemImpl().floatEListType, this); } return svd.emptyFloatList; } public EmptyIntegerList getEmptyIntegerList() { if (null == svd.emptyIntegerList) { svd.emptyIntegerList = new EmptyIntegerList(getTypeSystemImpl().intEListType, this); } return svd.emptyIntegerList; } public EmptyStringList getEmptyStringList() { if (null == svd.emptyStringList) { svd.emptyStringList = new EmptyStringList(getTypeSystemImpl().stringEListType, this); } return svd.emptyStringList; } /** * @param rangeCode special codes for serialization use only * @return the empty list (shared) corresponding to the type */ public EmptyList getEmptyList(int rangeCode) { return (rangeCode == CasSerializerSupport.TYPE_CLASS_INTLIST) ? getEmptyIntegerList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_FLOATLIST) ? getEmptyFloatList() : (rangeCode == CasSerializerSupport.TYPE_CLASS_STRINGLIST) ? getEmptyStringList() : getEmptyFSList(); } /** * Get an empty list from the type code of a list * @param rangeCode - * @return - */ public EmptyList getEmptyListFromTypeCode(int rangeCode) { switch (rangeCode) { case fsListTypeCode: case fsEListTypeCode: case fsNeListTypeCode: return getEmptyFSList(); case floatListTypeCode: case floatEListTypeCode: case floatNeListTypeCode: return getEmptyFloatList(); case intListTypeCode: case intEListTypeCode: case intNeListTypeCode: return getEmptyIntegerList(); case stringListTypeCode: case stringEListTypeCode: case stringNeListTypeCode: return getEmptyStringList(); default: throw new IllegalArgumentException(); } } // /** // * Copies a feature, from one fs to another // * FSs may belong to different CASes, but must have the same type system // * Features must have compatible ranges // * The target must not be indexed // * The target must be a "new" (above the "mark") FS // * @param fsSrc source FS // * @param fi Feature to copy // * @param fsTgt target FS // */ // public static void copyFeature(TOP fsSrc, FeatureImpl fi, TOP fsTgt) { // if (!copyFeatureExceptFsRef(fsSrc, fi, fsTgt, fi)) { // if (!fi.isAnnotBaseSofaRef) { // fsTgt._setFeatureValueNcNj(fi, fsSrc._getFeatureValueNc(fi)); // } // } // } /** * Copies a feature from one fs to another * FSs may be in different type systems * Doesn't copy a feature ref, but instead returns false. * This is because feature refs can't cross CASes * @param fsSrc source FS * @param fiSrc feature in source to copy * @param fsTgt target FS * @param fiTgt feature in target to set * @return false if feature is an fsRef */ public static boolean copyFeatureExceptFsRef(TOP fsSrc, FeatureImpl fiSrc, TOP fsTgt, FeatureImpl fiTgt) { switch (fiSrc.getRangeImpl().getCode()) { case booleanTypeCode : fsTgt._setBooleanValueNcNj( fiTgt, fsSrc._getBooleanValueNc( fiSrc)); break; case byteTypeCode : fsTgt._setByteValueNcNj( fiTgt, fsSrc._getByteValueNc( fiSrc)); break; case shortTypeCode : fsTgt._setShortValueNcNj( fiTgt, fsSrc._getShortValueNc( fiSrc)); break; case intTypeCode : fsTgt._setIntValueNcNj( fiTgt, fsSrc._getIntValueNc( fiSrc)); break; case longTypeCode : fsTgt._setLongValueNcNj( fiTgt, fsSrc._getLongValueNc( fiSrc)); break; case floatTypeCode : fsTgt._setFloatValueNcNj( fiTgt, fsSrc._getFloatValueNc( fiSrc)); break; case doubleTypeCode : fsTgt._setDoubleValueNcNj( fiTgt, fsSrc._getDoubleValueNc( fiSrc)); break; case stringTypeCode : fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // case javaObjectTypeCode : fsTgt._setJavaObjectValueNcNj(fiTgt, fsSrc.getJavaObjectValue(fiSrc)); break; // skip setting sofaRef - it's final and can't be set default: if (fiSrc.getRangeImpl().isStringSubtype()) { fsTgt._setStringValueNcNj( fiTgt, fsSrc._getStringValueNc( fiSrc)); break; // does substring range check } return false; } // end of switch return true; } public static CommonArrayFS copyArray(TOP srcArray) { CommonArrayFS srcCA = (CommonArrayFS) srcArray; CommonArrayFS copy = (CommonArrayFS) srcArray._casView.createArray(srcArray._getTypeImpl(), srcCA.size()); copy.copyValuesFrom(srcCA); return copy; } public BinaryCasSerDes getBinaryCasSerDes() { return svd.bcsd; } /** * @return the saved CommonSerDesSequential info */ CommonSerDesSequential getCsds() { return svd.csds; } void setCsds(CommonSerDesSequential csds) { svd.csds = csds; } CommonSerDesSequential newCsds() { return svd.csds = new CommonSerDesSequential(this.getBaseCAS()); } /** * A space-freeing optimization for use cases where (multiple) delta CASes are being deserialized into this CAS and merged. */ public void deltaMergesComplete() { svd.csds = null; } /****************************************** * PEAR support * Don't modify the type system because it is in use on multiple threads * * Handling of id2fs for low level APIs: * FSs in id2fs map are the outer non-pear ones * Any gets do pear conversion if needed. * ******************************************/ /** * Convert base FS to Pear equivalent * 3 cases: * 1) no trampoline needed, no conversion, return the original fs * 2) trampoline already exists - return that one * 3) create new trampoline * @param aFs * @return */ static <T extends FeatureStructure> T pearConvert(T aFs) { if (null == aFs) { return null; } final TOP fs = (TOP) aFs; final CASImpl view = fs._casView; final TypeImpl ti = fs._getTypeImpl(); final FsGenerator3 generator = view.svd.generators[ti.getCode()]; if (null == generator) { return aFs; } return (T) view.pearConvert(fs, generator); } /** * Inner method - after determining there is a generator * First see if already have generated the pear version, and if so, * use that. * Otherwise, create the pear version and save in trampoline table * @param fs * @param g * @return */ private TOP pearConvert(TOP fs, FsGenerator3 g) { return svd.id2tramp.putIfAbsent(fs._id, k -> { svd.reuseId = k; // create new FS using base FS's ID pearBaseFs = fs; TOP r; // createFS below is modified because of pearBaseFs non-null to // "share" the int and data arrays try { r = g.createFS(fs._getTypeImpl(), this); } finally { svd.reuseId = 0; pearBaseFs = null; } assert r != null; if (r instanceof UimaSerializable) { throw new UnsupportedOperationException( "Pears with Alternate implementations of JCas classes implementing UimaSerializable not supported."); // ((UimaSerializable) fs)._save_to_cas_data(); // updates in r too // ((UimaSerializable) r)._init_from_cas_data(); } return r; }); } /** * Given a trampoline FS, return the corresponding base Fs * Supports adding Fs (which must be a non-trampoline version) to indexes * @param fs trampoline fs * @return the corresponding base fs */ <T extends TOP> T getBaseFsFromTrampoline(T fs) { TOP r = svd.id2base.get(fs._id); assert r != null; return (T) r; } /* ***************************************** * DEBUGGING and TRACING ******************************************/ public void traceFSCreate(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceFSflush(); } // normally commented-out for matching with v2 // // mark annotations created by subiterator // if (fs._getTypeCode() == TypeSystemConstants.annotTypeCode) { // StackTraceElement[] stktr = Thread.currentThread().getStackTrace(); // if (stktr.length > 7 && stktr[6].getClassName().equals("org.apache.uima.cas.impl.Subiterator")) { // b.append('*'); // } // } svd.id2addr.add(svd.nextId2Addr); svd.nextId2Addr += fs._getTypeImpl().getFsSpaceReq((TOP)fs); traceFSfs(fs); svd.traceFSisCreate = true; if (fs._getTypeImpl().isArray()) { b.append(" l:").append(((CommonArrayFS)fs).size()); } } void traceFSfs(FeatureStructureImplC fs) { StringBuilder b = svd.traceFScreationSb; svd.traceFSid = fs._id; b.append("c:").append(String.format("%-3d", getCasId())); String viewName = fs._casView.getViewName(); if (null == viewName) { viewName = "base"; } b.append(" v:").append(Misc.elide(viewName, 8)); b.append(" i:").append(String.format("%-5s", geti2addr(fs._id))); b.append(" t:").append(Misc.elide(fs._getTypeImpl().getShortName(), 10)); } void traceIndexMod(boolean isAdd, TOP fs, boolean isAddbackOrSkipBag) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append(isAdd ? (isAddbackOrSkipBag ? "abk_idx " : "add_idx ") : (isAddbackOrSkipBag ? "rmv_auto_idx " : "rmv_norm_idx ")); // b.append(fs.toString()); b.append(fs._getTypeImpl().getShortName()).append(":").append(fs._id); if (fs instanceof Annotation) { Annotation ann = (Annotation) fs; b.append(" begin: ").append(ann.getBegin()); b.append(" end: ").append(ann.getEnd()); b.append(" txt: \"").append(Misc.elide(ann.getCoveredText(), 10)).append("\""); } traceOut.println(b); } void traceCowCopy(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowCopyUse(FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-copy-used:"); b.append(" i: ").append(index); traceOut.println(b); } void traceCowReinit(String kind, FsIndex_singletype<?> index) { StringBuilder b = svd.traceCowSb; b.setLength(0); b.append("cow-redo: "); b.append(kind); b.append(" i: ").append(index); b.append(" c: "); b.append(Misc.getCaller()); traceOut.println(b); } /** only used for tracing, enables tracing 2 slots for long/double */ private FeatureImpl prevFi; void traceFSfeat(FeatureStructureImplC fs, FeatureImpl fi, Object v) { //debug FeatureImpl originalFi = fi; StringBuilder b = svd.traceFScreationSb; assert (b.length() > 0); if (fs._id != svd.traceFSid) { traceFSfeatUpdate(fs); } if (fi == null) { // happens on 2nd setInt call from cas copier copyfeatures for Long / Double switch(prevFi.getSlotKind()) { case Slot_DoubleRef: v = fs._getDoubleValueNc(prevFi); break; // correct double and long case Slot_LongRef: v = fs._getLongValueNc(prevFi); break; // correct double and long default: Misc.internalError(); } fi = prevFi; prevFi = null; } else { prevFi = fi; } String fn = fi.getShortName(); // correct calls done by cas copier fast loop if (fi.getSlotKind() == SlotKind.Slot_DoubleRef) { if (v instanceof Integer) { return; // wait till the next part is traced } else if (v instanceof Long) { v = CASImpl.long2double((long)v); } } if (fi.getSlotKind() == SlotKind.Slot_LongRef && (v instanceof Integer)) { return; // output done on the next int call } String fv = getTraceRepOfObj(fi, v); // if (geti2addr(fs._id).equals("79") && // fn.equals("sofa")) { // new Throwable().printStackTrace(traceOut); // } // // debug // if (fn.equals("lemma") && // fv.startsWith("Lemma:") && // debug1cnt < 2) { // debug1cnt ++; // traceOut.println("setting lemma feat:"); // new Throwable().printStackTrace(traceOut); // } // debug // if (fs._getTypeImpl().getShortName().equals("Passage") && // "score".equals(fn) && // debug2cnt < 5) { // debug2cnt++; // traceOut.println("setting score feat in Passage"); // new Throwable().printStackTrace(traceOut); // } // debug int i_v = Math.max(0, 10 - fn.length()); int i_n = Math.max(0, 10 - fv.length()); fn = Misc.elide(fn, 10 + i_n, false); fv = Misc.elide(fv, 10 + i_v, false); // debug // if (!svd.traceFSisCreate && fn.equals("uninf.dWord") && fv.equals("XsgTokens")) { // traceOut.println("debug uninf.dWord:XsgTokens: " + Misc.getCallers(3, 10)); // } b.append(' ').append(Misc.elide(fn + ':' + fv, 21)); // value of a feature: // - "null" or // - if FS: type:id (converted to addr) // - v.toString() } private static int debug2cnt = 0; /** * @param v * @return value of the feature: * "null" or if FS: type:id (converted to addr) or v.toString() * Note: white space in strings converted to "_' characters */ private String getTraceRepOfObj(FeatureImpl fi, Object v) { if (v instanceof TOP) { TOP fs = (TOP) v; return Misc.elide(fs.getType().getShortName(), 5, false) + ':' + geti2addr(fs._id); } if (v == null) return "null"; if (v instanceof String) { String s = Misc.elide((String) v, 50, false); return Misc.replaceWhiteSpace(s, "_"); } if (v instanceof Integer) { int iv = (int) v; switch (fi.getSlotKind()) { case Slot_Boolean: return (iv == 1) ? "true" : "false"; case Slot_Byte: case Slot_Short: case Slot_Int: return Integer.toString(iv); case Slot_Float: return Float.toString(int2float(iv)); } } if (v instanceof Long) { long vl = (long) v; return (fi.getSlotKind() == SlotKind.Slot_DoubleRef) ? Double.toString(long2double(vl)) : Long.toString(vl); } return Misc.replaceWhiteSpace(v.toString(), "_"); } private String geti2addr(int id) { if (id >= svd.id2addr.size()) { return Integer.toString(id) + '!'; } return Integer.toString(svd.id2addr.get(id)); } void traceFSfeatUpdate(FeatureStructureImplC fs) { traceFSflush(); traceFSfs(fs); svd.traceFSisCreate = false; } public StringBuilder traceFSflush() { if (!traceFSs) return null; StringBuilder b = svd.traceFScreationSb; if (b.length() > 0) { traceOut.println((svd.traceFSisCreate ? "cr: " : "up: ") + b); b.setLength(0); svd.traceFSisCreate = false; } return b; } private static class MeasureSwitchType { TypeImpl oldType; TypeImpl newType; String oldJCasClassName; String newJCasClassName; int count = 0; boolean newSubsumesOld; boolean oldSubsumesNew; long scantime = 0; MeasureSwitchType(TypeImpl oldType, TypeImpl newType) { this.oldType = oldType; this.oldJCasClassName = oldType.getJavaClass().getName(); this.newType = newType; this.newJCasClassName = newType.getJavaClass().getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((newJCasClassName == null) ? 0 : newJCasClassName.hashCode()); result = prime * result + ((newType == null) ? 0 : newType.hashCode()); result = prime * result + ((oldJCasClassName == null) ? 0 : oldJCasClassName.hashCode()); result = prime * result + ((oldType == null) ? 0 : oldType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MeasureSwitchType)) { return false; } MeasureSwitchType other = (MeasureSwitchType) obj; if (newJCasClassName == null) { if (other.newJCasClassName != null) { return false; } } else if (!newJCasClassName.equals(other.newJCasClassName)) { return false; } if (newType == null) { if (other.newType != null) { return false; } } else if (!newType.equals(other.newType)) { return false; } if (oldJCasClassName == null) { if (other.oldJCasClassName != null) { return false; } } else if (!oldJCasClassName.equals(other.oldJCasClassName)) { return false; } if (oldType == null) { if (other.oldType != null) { return false; } } else if (!oldType.equals(other.oldType)) { return false; } return true; } } private static final Map<MeasureSwitchType, MeasureSwitchType> measureSwitches = new HashMap<>(); static { if (MEASURE_SETINT) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("debug Switch Types dump, # entries: " + measureSwitches.size()); int s1 = 0, s2 = 0, s3 = 0; for (MeasureSwitchType mst : measureSwitches.keySet()) { s1 = Math.max(s1, mst.oldType.getName().length()); s2 = Math.max(s2, mst.newType.getName().length()); s3 = Math.max(s3, mst.oldJCasClassName.length()); } for (MeasureSwitchType mst : measureSwitches.keySet()) { System.out.format("count: %,6d scantime = %,7d ms, subsumes: %s %s, type: %-" + s1 + "s newType: %-" + s2 + "s, cl: %-" + s3 + "s, newCl: %s%n", mst.count, mst.scantime / 1000000, mst.newSubsumesOld ? "n>o" : " ", mst.oldSubsumesNew ? "o>w" : " ", mst.oldType.getName(), mst.newType.getName(), mst.oldJCasClassName, mst.newJCasClassName); } // if (traceFSs) { // System.err.println("debug closing traceFSs output"); // traceOut.close(); // } }, "Dump SwitchTypes")); } // this is definitely needed if (traceFSs) { Runtime.getRuntime().addShutdownHook(new Thread(null, () -> { System.out.println("closing traceOut"); traceOut.close(); }, "close trace output")); } } /* * (non-Javadoc) * * @see org.apache.uima.cas.admin.CASMgr#setCAS(org.apache.uima.cas.CAS) * Internal use Never called Kept because it's in the interface. */ @Override @Deprecated public void setCAS(CAS cas) {} /** * @return true if in Pear context, or external context outside AnalysisEngine having a UIMA Extension class loader * e.g., if calling a call-back routine loaded outside the AE. */ boolean inPearContext() { return svd.previousJCasClassLoader != null; } /** * Pear context suspended while creating a base version, when we need to create a new FS * (we need to create both the base and the trampoline version) */ private void suspendPearContext() { svd.suspendPreviousJCasClassLoader = svd.previousJCasClassLoader; svd.previousJCasClassLoader = null; } private void restorePearContext() { svd.previousJCasClassLoader = svd.suspendPreviousJCasClassLoader; } /** * * @return the initial heap size specified or defaulted */ public int getInitialHeapSize() { return this.svd.initialHeapSize; } // backwards compatibility - reinit calls // just the public apis /** * Deserializer for Java-object serialized instance of CASSerializer * Used by Soap * @param ser - The instance to convert back to a CAS */ public void reinit(CASSerializer ser) { svd.bcsd.reinit(ser); } /** * Deserializer for CASCompleteSerializer instances - includes type system and index definitions * Never delta * @param casCompSer - */ public void reinit(CASCompleteSerializer casCompSer) { svd.bcsd.reinit(casCompSer); } /** * --------------------------------------------------------------------- * see Blob Format in CASSerializer * * This reads in and deserializes CAS data from a stream. Byte swapping may be * needed if the blob is from C++ -- C++ blob serialization writes data in * native byte order. * * Supports delta deserialization. For that, the the csds from the serialization event must be used. * * @param istream - * @return - the format of the input stream detected * @throws CASRuntimeException wraps IOException */ public SerialFormat reinit(InputStream istream) throws CASRuntimeException { return svd.bcsd.reinit(istream); } void maybeHoldOntoFS(FeatureStructureImplC fs) { if (IS_ALWAYS_HOLD_ONTO_FSS) { svd.id2fs.putUnconditionally((TOP)fs); } } public void swapInPearVersion(Object[] a) { if (!inPearContext()) { return; } for (int i = 0; i < a.length; i++) { Object ao = a[i]; if (ao instanceof TOP) { a[i] = pearConvert((TOP) ao); } } } public Collection<?> collectNonPearVersions(Collection<?> c) { if (c.size() == 0 || !inPearContext()) { return c; } ArrayList<Object> items = new ArrayList<>(c.size()); for (Object o : c) { if (o instanceof TOP) { items.add(pearConvert((TOP) o)); } } return items; } public <T> Spliterator<T> makePearAware(Spliterator<T> baseSi) { if (!inPearContext()) { return baseSi; } return new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return baseSi.tryAdvance(item -> action.accept( (item instanceof TOP) ? (T) pearConvert((TOP)item) : item)); } @Override public Spliterator<T> trySplit() { return baseSi.trySplit(); } @Override public long estimateSize() { return baseSi.estimateSize(); } @Override public int characteristics() { return baseSi.characteristics(); } }; } // int allocIntData(int sz) { // // if (sz > INT_DATA_FOR_ALLOC_SIZE / 4) { // returnIntDataForAlloc = new int[sz]; // return 0; // } // // if (sz + nextIntDataOffsetForAlloc > INT_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentIntDataForAlloc = new int[INT_DATA_FOR_ALLOC_SIZE]; // nextIntDataOffsetForAlloc = 0; // } // int r = nextIntDataOffsetForAlloc; // nextIntDataOffsetForAlloc += sz; // returnIntDataForAlloc = currentIntDataForAlloc; // return r; // } // // int[] getReturnIntDataForAlloc() { // return returnIntDataForAlloc; // } // // int allocRefData(int sz) { // // if (sz > REF_DATA_FOR_ALLOC_SIZE / 4) { // returnRefDataForAlloc = new Object[sz]; // return 0; // } // // if (sz + nextRefDataOffsetForAlloc > REF_DATA_FOR_ALLOC_SIZE) { // // too large to fit, alloc a new one // currentRefDataForAlloc = new Object[REF_DATA_FOR_ALLOC_SIZE]; // nextRefDataOffsetForAlloc = 0; // } // int r = nextRefDataOffsetForAlloc; // nextRefDataOffsetForAlloc += sz; // returnRefDataForAlloc = currentRefDataForAlloc; // return r; // } // // Object[] getReturnRefDataForAlloc() { // return returnRefDataForAlloc; // } }
[UIMA-5442] add 2 methods for backwards compatibility with v2 git-svn-id: d56ff9e7d7ea0b208561738885f328c1a8397aa6@1798057 13f79535-47bb-0310-9956-ffa450edef68
uimaj-core/src/main/java/org/apache/uima/cas/impl/CASImpl.java
[UIMA-5442] add 2 methods for backwards compatibility with v2
Java
apache-2.0
52499f7a6c09a92688ccb555674ee9ba8b57adf3
0
d3xter/bo-android,wuan/bo-android,d3xter/bo-android
package org.blitzortung.android.data; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.os.AsyncTask; import android.os.PowerManager; import android.util.Log; import org.blitzortung.android.app.Main; import org.blitzortung.android.app.view.PreferenceKey; import org.blitzortung.android.data.beans.StrikeAbstract; import org.blitzortung.android.data.provider.DataProvider; import org.blitzortung.android.data.provider.DataProviderFactory; import org.blitzortung.android.data.provider.DataProviderType; import org.blitzortung.android.data.provider.result.ClearDataEvent; import org.blitzortung.android.data.provider.result.DataEvent; import org.blitzortung.android.data.provider.result.RequestStartedEvent; import org.blitzortung.android.data.provider.result.ResultEvent; import org.blitzortung.android.protocol.Consumer; import org.blitzortung.android.util.optional.Optional; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class DataHandler implements OnSharedPreferenceChangeListener { private final Lock lock = new ReentrantLock(); private final PackageInfo pInfo; private DataProvider dataProvider; private String username; private String password; private final Parameters parameters; private Consumer<DataEvent> dataEventConsumer; private int preferencesRasterBaselength; private int preferencesRegion; private DataProviderFactory dataProviderFactory; public static final RequestStartedEvent REQUEST_STARTED_EVENT = new RequestStartedEvent(); public static final ClearDataEvent CLEAR_DATA_EVENT = new ClearDataEvent(); private PowerManager.WakeLock wakeLock; public static final Set<DataChannel> DEFAULT_DATA_CHANNELS = new HashSet<DataChannel>(); static { DEFAULT_DATA_CHANNELS.add(DataChannel.STRIKES); } public DataHandler(PowerManager.WakeLock wakeLock, SharedPreferences sharedPreferences, PackageInfo pInfo) { this(wakeLock, sharedPreferences, pInfo, new DataProviderFactory()); } public DataHandler(PowerManager.WakeLock wakeLock, SharedPreferences sharedPreferences, PackageInfo pInfo, DataProviderFactory dataProviderFactory) { this.wakeLock = wakeLock; this.dataProviderFactory = dataProviderFactory; parameters = new Parameters(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); this.pInfo = pInfo; onSharedPreferenceChanged(sharedPreferences, PreferenceKey.DATA_SOURCE); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.USERNAME); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.PASSWORD); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.RASTER_SIZE); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.COUNT_THRESHOLD); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.REGION); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.INTERVAL_DURATION); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.HISTORIC_TIMESTEP); updateProviderSpecifics(); } private class FetchDataTask extends AsyncTask<Integer, Integer, Optional<ResultEvent>> { protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Optional<ResultEvent> result) { if (result.isPresent()) { final ResultEvent payload = result.get(); sendEvent(payload); } } @Override protected Optional<ResultEvent> doInBackground(Integer... params) { int intervalDuration = params[0]; int intervalOffset = params[1]; int rasterBaselength = params[2]; int region = params[3]; boolean updateParticipants = params[4] != 0; int countThreshold = params[5]; ResultEvent result = null; if (lock.tryLock()) { result = new ResultEvent(); try { dataProvider.setUp(); dataProvider.setCredentials(username, password); List<StrikeAbstract> strikes; if (rasterBaselength == 0) { strikes = dataProvider.getStrikes(intervalDuration, intervalOffset, region); } else { strikes = dataProvider.getStrikesGrid(intervalDuration, intervalOffset, rasterBaselength, countThreshold, region); } Parameters parameters = new Parameters(); parameters.setIntervalDuration(intervalDuration); parameters.setIntervalOffset(intervalOffset); parameters.setRegion(region); parameters.setRasterBaselength(rasterBaselength); parameters.setCountThreshold(countThreshold); if (dataProvider.returnsIncrementalData()) { result.setContainsIncrementalData(); } result.setParameters(parameters); result.setReferenceTime(System.currentTimeMillis()); result.setStrikes(strikes); result.setRasterParameters(dataProvider.getRasterParameters()); result.setHistogram(dataProvider.getHistogram()); if (updateParticipants) { result.setStations(dataProvider.getStations(region)); } dataProvider.shutDown(); } catch (RuntimeException e) { e.printStackTrace(); } finally { lock.unlock(); } } return Optional.fromNullable(result); } } private class FetchBackgroundDataTask extends FetchDataTask { private PowerManager.WakeLock wakeLock; public FetchBackgroundDataTask(PowerManager.WakeLock wakeLock) { super(); this.wakeLock = wakeLock; } @Override protected void onPostExecute(Optional<ResultEvent> result) { super.onPostExecute(result); if (wakeLock.isHeld()) { try { wakeLock.release(); Log.v(Main.LOG_TAG, "FetchBackgroundDataTask released wakelock " + wakeLock); } catch (RuntimeException e) { Log.e(Main.LOG_TAG, "FetchBackgroundDataTask release wakelock failed ", e); } } else { Log.e(Main.LOG_TAG, "FetchBackgroundDataTask release wakelock not held "); } } @Override protected Optional<ResultEvent> doInBackground(Integer... params) { wakeLock.acquire(); Log.v(Main.LOG_TAG, "FetchBackgroundDataTask aquire wakelock " + wakeLock); return super.doInBackground(params); } } public void updateDatainBackground() { new FetchBackgroundDataTask(wakeLock).execute(10, 0, dataProvider.getType() == DataProviderType.HTTP ? 0 : parameters.getRasterBaselength(), parameters.getRegion(), 0, parameters.getCountThreshold()); } public void updateData() { updateData(DEFAULT_DATA_CHANNELS); } public void updateData(Set<DataChannel> updateTargets) { sendEvent(REQUEST_STARTED_EVENT); boolean updateParticipants = false; if (updateTargets.contains(DataChannel.PARTICIPANTS)) { if (dataProvider.getType() == DataProviderType.HTTP || parameters.getRasterBaselength() == 0) { updateParticipants = true; } } new FetchDataTask().execute(parameters.getIntervalDuration(), parameters.getIntervalOffset(), dataProvider.getType() == DataProviderType.HTTP ? 0 : parameters.getRasterBaselength(), parameters.getRegion(), updateParticipants ? 1 : 0, parameters.getCountThreshold()); } private void sendEvent(DataEvent dataEvent) { if (dataEventConsumer != null) { dataEventConsumer.consume(dataEvent); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String keyString) { onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString)); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) { switch (key) { case DATA_SOURCE: String providerTypeString = sharedPreferences.getString(key.toString(), DataProviderType.RPC.toString()); DataProviderType providerType = DataProviderType.valueOf(providerTypeString.toUpperCase()); dataProvider = dataProviderFactory.getDataProviderForType(providerType); dataProvider.setPackageInfo(pInfo); updateProviderSpecifics(); notifyDataReset(); break; case USERNAME: username = sharedPreferences.getString(key.toString(), ""); break; case PASSWORD: password = sharedPreferences.getString(key.toString(), ""); break; case RASTER_SIZE: preferencesRasterBaselength = Integer.parseInt(sharedPreferences.getString(key.toString(), "10000")); parameters.setRasterBaselength(preferencesRasterBaselength); notifyDataReset(); break; case COUNT_THRESHOLD: int countThreshold = Integer.parseInt(sharedPreferences.getString(key.toString(), "0")); parameters.setCountThreshold(countThreshold); notifyDataReset(); break; case INTERVAL_DURATION: parameters.setIntervalDuration(Integer.parseInt(sharedPreferences.getString(key.toString(), "120"))); dataProvider.reset(); notifyDataReset(); break; case HISTORIC_TIMESTEP: parameters.setOffsetIncrement(Integer.parseInt(sharedPreferences.getString(key.toString(), "30"))); break; case REGION: preferencesRegion = Integer.parseInt(sharedPreferences.getString(key.toString(), "1")); parameters.setRegion(preferencesRegion); dataProvider.reset(); notifyDataReset(); break; } if (dataProvider != null) { dataProvider.setCredentials(username, password); } } private void updateProviderSpecifics() { DataProviderType providerType = dataProvider.getType(); switch (providerType) { case RPC: enableRasterMode(); break; case HTTP: disableRasterMode(); break; } } private void notifyDataReset() { sendEvent(CLEAR_DATA_EVENT); } public void toggleExtendedMode() { if (parameters.getRasterBaselength() > 0) { disableRasterMode(); parameters.setRegion(0); } else { enableRasterMode(); parameters.setRegion(preferencesRegion); } if (!isRealtime()) { Set<DataChannel> dataChannels = new HashSet<DataChannel>(); dataChannels.add(DataChannel.STRIKES); updateData(dataChannels); } } public void disableRasterMode() { parameters.setRasterBaselength(0); } public void enableRasterMode() { parameters.setRasterBaselength(preferencesRasterBaselength); } public void setDataConsumer(Consumer<DataEvent> consumer) { this.dataEventConsumer = consumer; } public int getIntervalDuration() { return parameters.getIntervalDuration(); } public boolean ffwdInterval() { return parameters.ffwdInterval(); } public boolean rewInterval() { return parameters.revInterval(); } public boolean goRealtime() { return parameters.goRealtime(); } public boolean isRealtime() { return parameters.isRealtime(); } public boolean isCapableOfHistoricalData() { return dataProvider.isCapableOfHistoricalData(); } public Parameters getParameters() { return parameters; } }
app/src/main/java/org/blitzortung/android/data/DataHandler.java
package org.blitzortung.android.data; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.os.AsyncTask; import android.os.PowerManager; import android.util.Log; import org.blitzortung.android.app.Main; import org.blitzortung.android.app.view.PreferenceKey; import org.blitzortung.android.data.beans.StrikeAbstract; import org.blitzortung.android.data.provider.DataProvider; import org.blitzortung.android.data.provider.DataProviderFactory; import org.blitzortung.android.data.provider.DataProviderType; import org.blitzortung.android.data.provider.result.ClearDataEvent; import org.blitzortung.android.data.provider.result.DataEvent; import org.blitzortung.android.data.provider.result.RequestStartedEvent; import org.blitzortung.android.data.provider.result.ResultEvent; import org.blitzortung.android.protocol.Consumer; import org.blitzortung.android.util.optional.Optional; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class DataHandler implements OnSharedPreferenceChangeListener { private final Lock lock = new ReentrantLock(); private final PackageInfo pInfo; private DataProvider dataProvider; private String username; private String password; private final Parameters parameters; private Consumer<DataEvent> dataEventConsumer; private int preferencesRasterBaselength; private int preferencesRegion; private DataProviderFactory dataProviderFactory; public static final RequestStartedEvent REQUEST_STARTED_EVENT = new RequestStartedEvent(); public static final ClearDataEvent CLEAR_DATA_EVENT = new ClearDataEvent(); private PowerManager.WakeLock wakeLock; public static final Set<DataChannel> DEFAULT_DATA_CHANNELS = new HashSet<DataChannel>(); static { DEFAULT_DATA_CHANNELS.add(DataChannel.STRIKES); } public DataHandler(PowerManager.WakeLock wakeLock, SharedPreferences sharedPreferences, PackageInfo pInfo) { this(wakeLock, sharedPreferences, pInfo, new DataProviderFactory()); } public DataHandler(PowerManager.WakeLock wakeLock, SharedPreferences sharedPreferences, PackageInfo pInfo, DataProviderFactory dataProviderFactory) { this.wakeLock = wakeLock; this.dataProviderFactory = dataProviderFactory; parameters = new Parameters(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); this.pInfo = pInfo; onSharedPreferenceChanged(sharedPreferences, PreferenceKey.DATA_SOURCE); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.USERNAME); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.PASSWORD); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.RASTER_SIZE); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.COUNT_THRESHOLD); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.REGION); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.INTERVAL_DURATION); onSharedPreferenceChanged(sharedPreferences, PreferenceKey.HISTORIC_TIMESTEP); updateProviderSpecifics(); } private class FetchDataTask extends AsyncTask<Integer, Integer, Optional<ResultEvent>> { protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Optional<ResultEvent> result) { if (result.isPresent()) { final ResultEvent payload = result.get(); sendEvent(payload); } } @Override protected Optional<ResultEvent> doInBackground(Integer... params) { int intervalDuration = params[0]; int intervalOffset = params[1]; int rasterBaselength = params[2]; int region = params[3]; boolean updateParticipants = params[4] != 0; int countThreshold = params[5]; ResultEvent result = null; if (lock.tryLock()) { result = new ResultEvent(); try { dataProvider.setUp(); dataProvider.setCredentials(username, password); List<StrikeAbstract> strikes; if (rasterBaselength == 0) { strikes = dataProvider.getStrikes(intervalDuration, intervalOffset, region); } else { strikes = dataProvider.getStrikesGrid(intervalDuration, intervalOffset, rasterBaselength, countThreshold, region); } Parameters parameters = new Parameters(); parameters.setIntervalDuration(intervalDuration); parameters.setIntervalOffset(intervalOffset); parameters.setRegion(region); parameters.setRasterBaselength(rasterBaselength); parameters.setCountThreshold(countThreshold); if (dataProvider.returnsIncrementalData()) { result.setContainsIncrementalData(); } result.setParameters(parameters); result.setReferenceTime(System.currentTimeMillis()); result.setStrikes(strikes); result.setRasterParameters(dataProvider.getRasterParameters()); result.setHistogram(dataProvider.getHistogram()); if (updateParticipants) { result.setStations(dataProvider.getStations(region)); } dataProvider.shutDown(); } catch (RuntimeException e) { e.printStackTrace(); } finally { lock.unlock(); } } return Optional.fromNullable(result); } } private class FetchBackgroundDataTask extends FetchDataTask { private PowerManager.WakeLock wakeLock; public FetchBackgroundDataTask(PowerManager.WakeLock wakeLock) { super(); this.wakeLock = wakeLock; } @Override protected void onPostExecute(Optional<ResultEvent> result) { super.onPostExecute(result); if (wakeLock.isHeld()) { try { wakeLock.release(); Log.v(Main.LOG_TAG, "FetchBackgroundDataTask released wakelock " + wakeLock); } catch (RuntimeException e) { Log.e(Main.LOG_TAG, "FetchBackgroundDataTask release wakelock failed ", e); } } else { Log.e(Main.LOG_TAG, "FetchBackgroundDataTask release wakelock not held "); } } @Override protected Optional<ResultEvent> doInBackground(Integer... params) { wakeLock.acquire(); Log.v(Main.LOG_TAG, "FetchBackgroundDataTask aquire wakelock " + wakeLock); return super.doInBackground(params); } } public void updateDatainBackground() { new FetchBackgroundDataTask(wakeLock).execute(10, 0, dataProvider.getType() == DataProviderType.HTTP ? 0 : parameters.getRasterBaselength(), parameters.getRegion(), 0); } public void updateData() { updateData(DEFAULT_DATA_CHANNELS); } public void updateData(Set<DataChannel> updateTargets) { sendEvent(REQUEST_STARTED_EVENT); boolean updateParticipants = false; if (updateTargets.contains(DataChannel.PARTICIPANTS)) { if (dataProvider.getType() == DataProviderType.HTTP || parameters.getRasterBaselength() == 0) { updateParticipants = true; } } new FetchDataTask().execute(parameters.getIntervalDuration(), parameters.getIntervalOffset(), dataProvider.getType() == DataProviderType.HTTP ? 0 : parameters.getRasterBaselength(), parameters.getRegion(), updateParticipants ? 1 : 0, parameters.getCountThreshold()); } private void sendEvent(DataEvent dataEvent) { if (dataEventConsumer != null) { dataEventConsumer.consume(dataEvent); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String keyString) { onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString)); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) { switch (key) { case DATA_SOURCE: String providerTypeString = sharedPreferences.getString(key.toString(), DataProviderType.RPC.toString()); DataProviderType providerType = DataProviderType.valueOf(providerTypeString.toUpperCase()); dataProvider = dataProviderFactory.getDataProviderForType(providerType); dataProvider.setPackageInfo(pInfo); updateProviderSpecifics(); notifyDataReset(); break; case USERNAME: username = sharedPreferences.getString(key.toString(), ""); break; case PASSWORD: password = sharedPreferences.getString(key.toString(), ""); break; case RASTER_SIZE: preferencesRasterBaselength = Integer.parseInt(sharedPreferences.getString(key.toString(), "10000")); parameters.setRasterBaselength(preferencesRasterBaselength); notifyDataReset(); break; case COUNT_THRESHOLD: int countThreshold = Integer.parseInt(sharedPreferences.getString(key.toString(), "0")); parameters.setCountThreshold(countThreshold); notifyDataReset(); break; case INTERVAL_DURATION: parameters.setIntervalDuration(Integer.parseInt(sharedPreferences.getString(key.toString(), "120"))); dataProvider.reset(); notifyDataReset(); break; case HISTORIC_TIMESTEP: parameters.setOffsetIncrement(Integer.parseInt(sharedPreferences.getString(key.toString(), "30"))); break; case REGION: preferencesRegion = Integer.parseInt(sharedPreferences.getString(key.toString(), "1")); parameters.setRegion(preferencesRegion); dataProvider.reset(); notifyDataReset(); break; } if (dataProvider != null) { dataProvider.setCredentials(username, password); } } private void updateProviderSpecifics() { DataProviderType providerType = dataProvider.getType(); switch (providerType) { case RPC: enableRasterMode(); break; case HTTP: disableRasterMode(); break; } } private void notifyDataReset() { sendEvent(CLEAR_DATA_EVENT); } public void toggleExtendedMode() { if (parameters.getRasterBaselength() > 0) { disableRasterMode(); parameters.setRegion(0); } else { enableRasterMode(); parameters.setRegion(preferencesRegion); } if (!isRealtime()) { Set<DataChannel> dataChannels = new HashSet<DataChannel>(); dataChannels.add(DataChannel.STRIKES); updateData(dataChannels); } } public void disableRasterMode() { parameters.setRasterBaselength(0); } public void enableRasterMode() { parameters.setRasterBaselength(preferencesRasterBaselength); } public void setDataConsumer(Consumer<DataEvent> consumer) { this.dataEventConsumer = consumer; } public int getIntervalDuration() { return parameters.getIntervalDuration(); } public boolean ffwdInterval() { return parameters.ffwdInterval(); } public boolean rewInterval() { return parameters.revInterval(); } public boolean goRealtime() { return parameters.goRealtime(); } public boolean isRealtime() { return parameters.isRealtime(); } public boolean isCapableOfHistoricalData() { return dataProvider.isCapableOfHistoricalData(); } public Parameters getParameters() { return parameters; } }
fixed missing parameter in background execution
app/src/main/java/org/blitzortung/android/data/DataHandler.java
fixed missing parameter in background execution
Java
apache-2.0
2a28424bdb73a30048077783ee124a0c8ef7ade3
0
gerasimenko-ivan/java_pft_34
package ru.stqa.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.appmanager.HelperBase.FormAction; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.GroupData; import java.util.Comparator; import java.util.HashSet; import java.util.List; public class ContactCreationTests extends TestBase { private String groupName = "test1"; @BeforeClass public void ensurePreconditions() { app.getNavigationHelper().gotoGroupPage(); app.getNavigationHelper().isOnGroupPage(); if (! app.getGroupHelper().isThereAGroup(groupName)) { GroupData groupData = new GroupData(groupName, null, null); app.getGroupHelper().createGroup(groupData); } } @Test public void testContactCreation() { app.getNavigationHelper().gotoHome(); List<ContactData> contactsBefore = app.getContactHelper().getContactList(); ContactData contact = new ContactData(); contact .setId(Integer.MAX_VALUE) .setFirstname(rnd.getFirstnameEng()) .setMiddlename("E.") .setLastname(rnd.getSurnameEng()) .setTitle("Dr.") .setAddress("221B Baker Street London") .setHomePhone("9(2131)324-33-33") .setEmail("[email protected]") .setGroup(groupName); app.getContactHelper().createContact(contact); List<ContactData> contactsAfter = app.getContactHelper().getContactList(); Assert.assertEquals(contactsAfter.size(), contactsBefore.size() + 1); contactsBefore.add(contact); Comparator<? super ContactData> byId = (g1, g2) -> Integer.compare(g1.getId(), g2.getId()); contactsBefore.sort(byId); contactsAfter.sort(byId); Assert.assertEquals(contactsAfter, contactsBefore); } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactCreationTests.java
package ru.stqa.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.appmanager.HelperBase.FormAction; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.GroupData; import java.util.Comparator; import java.util.HashSet; import java.util.List; public class ContactCreationTests extends TestBase { private String groupName = "test1"; @BeforeClass public void ensurePreconditions() { app.getNavigationHelper().gotoGroupPage(); app.getNavigationHelper().isOnGroupPage(); if (! app.getGroupHelper().isThereAGroup(groupName)) { GroupData groupData = new GroupData(groupName, null, null); app.getGroupHelper().createGroup(groupData); } } @Test public void testContactCreation() { app.getNavigationHelper().gotoHome(); List<ContactData> contactsBefore = app.getContactHelper().getContactList(); ContactData contact = new ContactData(); contact .setId(Integer.MAX_VALUE) .setFirstname("Yan") .setMiddlename("E.") .setLastname("Doe") .setTitle("Dr.") .setAddress("221B Baker Street London") .setHomePhone("9(2131)324-33-33") .setEmail("[email protected]") .setGroup(groupName); app.getContactHelper().createContact(contact); List<ContactData> contactsAfter = app.getContactHelper().getContactList(); Assert.assertEquals(contactsAfter.size(), contactsBefore.size() + 1); contactsBefore.add(contact); Comparator<? super ContactData> byId = (g1, g2) -> Integer.compare(g1.getId(), g2.getId()); contactsBefore.sort(byId); contactsAfter.sort(byId); Assert.assertEquals(contactsAfter, contactsBefore); } }
random name&surname in contact creation
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactCreationTests.java
random name&surname in contact creation
Java
apache-2.0
407fa8afd0cc9c7cb69859528f3cbb2e6b0f4c8e
0
tdiesler/camel,cunningt/camel,tlehoux/camel,salikjan/camel,jkorab/camel,pmoerenhout/camel,NickCis/camel,lburgazzoli/camel,acartapanis/camel,tadayosi/camel,snurmine/camel,jamesnetherton/camel,kevinearls/camel,zregvart/camel,DariusX/camel,Fabryprog/camel,mgyongyosi/camel,nikhilvibhav/camel,lburgazzoli/apache-camel,scranton/camel,w4tson/camel,punkhorn/camel-upstream,curso007/camel,nboukhed/camel,isavin/camel,acartapanis/camel,curso007/camel,anton-k11/camel,prashant2402/camel,pkletsko/camel,jamesnetherton/camel,acartapanis/camel,anton-k11/camel,nboukhed/camel,anton-k11/camel,alvinkwekel/camel,davidkarlsen/camel,tdiesler/camel,mcollovati/camel,gilfernandes/camel,cunningt/camel,ullgren/camel,allancth/camel,nboukhed/camel,RohanHart/camel,onders86/camel,allancth/camel,sverkera/camel,snurmine/camel,anoordover/camel,alvinkwekel/camel,veithen/camel,anoordover/camel,dmvolod/camel,CodeSmell/camel,snurmine/camel,chirino/camel,DariusX/camel,onders86/camel,davidkarlsen/camel,isavin/camel,sverkera/camel,gautric/camel,lburgazzoli/camel,prashant2402/camel,anoordover/camel,pax95/camel,nicolaferraro/camel,NickCis/camel,akhettar/camel,objectiser/camel,RohanHart/camel,ullgren/camel,nicolaferraro/camel,RohanHart/camel,scranton/camel,chirino/camel,pax95/camel,adessaigne/camel,mcollovati/camel,w4tson/camel,gilfernandes/camel,veithen/camel,drsquidop/camel,apache/camel,rmarting/camel,mgyongyosi/camel,lburgazzoli/apache-camel,dmvolod/camel,jamesnetherton/camel,driseley/camel,prashant2402/camel,RohanHart/camel,apache/camel,pkletsko/camel,jonmcewen/camel,Thopap/camel,veithen/camel,punkhorn/camel-upstream,gnodet/camel,pkletsko/camel,objectiser/camel,tlehoux/camel,pax95/camel,pmoerenhout/camel,mgyongyosi/camel,snurmine/camel,pmoerenhout/camel,salikjan/camel,adessaigne/camel,CodeSmell/camel,adessaigne/camel,jamesnetherton/camel,ssharma/camel,curso007/camel,mgyongyosi/camel,jonmcewen/camel,akhettar/camel,pkletsko/camel,yuruki/camel,allancth/camel,acartapanis/camel,scranton/camel,sverkera/camel,pax95/camel,dmvolod/camel,anton-k11/camel,alvinkwekel/camel,gnodet/camel,jonmcewen/camel,nikhilvibhav/camel,dmvolod/camel,nboukhed/camel,tadayosi/camel,pmoerenhout/camel,veithen/camel,rmarting/camel,tlehoux/camel,akhettar/camel,christophd/camel,Thopap/camel,acartapanis/camel,alvinkwekel/camel,onders86/camel,prashant2402/camel,rmarting/camel,w4tson/camel,davidkarlsen/camel,sverkera/camel,acartapanis/camel,scranton/camel,davidkarlsen/camel,snurmine/camel,ssharma/camel,lburgazzoli/apache-camel,lburgazzoli/apache-camel,kevinearls/camel,adessaigne/camel,chirino/camel,Thopap/camel,cunningt/camel,Fabryprog/camel,tadayosi/camel,DariusX/camel,driseley/camel,nikhilvibhav/camel,allancth/camel,isavin/camel,drsquidop/camel,kevinearls/camel,objectiser/camel,gnodet/camel,NickCis/camel,chirino/camel,allancth/camel,pkletsko/camel,pax95/camel,sverkera/camel,Thopap/camel,zregvart/camel,gautric/camel,yuruki/camel,jonmcewen/camel,chirino/camel,yuruki/camel,tdiesler/camel,CodeSmell/camel,akhettar/camel,snurmine/camel,RohanHart/camel,w4tson/camel,tdiesler/camel,tadayosi/camel,rmarting/camel,christophd/camel,gautric/camel,allancth/camel,jkorab/camel,adessaigne/camel,ullgren/camel,tlehoux/camel,cunningt/camel,tlehoux/camel,pmoerenhout/camel,gilfernandes/camel,Fabryprog/camel,pmoerenhout/camel,tadayosi/camel,anoordover/camel,jonmcewen/camel,isavin/camel,nboukhed/camel,jkorab/camel,punkhorn/camel-upstream,yuruki/camel,dmvolod/camel,onders86/camel,prashant2402/camel,lburgazzoli/camel,tadayosi/camel,nboukhed/camel,gilfernandes/camel,kevinearls/camel,apache/camel,apache/camel,apache/camel,pax95/camel,CodeSmell/camel,tdiesler/camel,sverkera/camel,gnodet/camel,gautric/camel,Thopap/camel,tlehoux/camel,ssharma/camel,jonmcewen/camel,nikhilvibhav/camel,tdiesler/camel,DariusX/camel,jkorab/camel,isavin/camel,gnodet/camel,lburgazzoli/camel,curso007/camel,veithen/camel,kevinearls/camel,chirino/camel,cunningt/camel,dmvolod/camel,jkorab/camel,driseley/camel,isavin/camel,Thopap/camel,curso007/camel,zregvart/camel,pkletsko/camel,christophd/camel,ssharma/camel,driseley/camel,curso007/camel,ssharma/camel,jamesnetherton/camel,punkhorn/camel-upstream,anton-k11/camel,jkorab/camel,cunningt/camel,w4tson/camel,lburgazzoli/apache-camel,ullgren/camel,gautric/camel,drsquidop/camel,yuruki/camel,gilfernandes/camel,objectiser/camel,christophd/camel,rmarting/camel,w4tson/camel,lburgazzoli/apache-camel,veithen/camel,mcollovati/camel,gautric/camel,akhettar/camel,jamesnetherton/camel,zregvart/camel,lburgazzoli/camel,driseley/camel,Fabryprog/camel,prashant2402/camel,lburgazzoli/camel,mgyongyosi/camel,drsquidop/camel,akhettar/camel,onders86/camel,ssharma/camel,NickCis/camel,mgyongyosi/camel,adessaigne/camel,christophd/camel,driseley/camel,onders86/camel,drsquidop/camel,mcollovati/camel,yuruki/camel,anoordover/camel,apache/camel,rmarting/camel,anton-k11/camel,NickCis/camel,scranton/camel,christophd/camel,RohanHart/camel,kevinearls/camel,scranton/camel,nicolaferraro/camel,nicolaferraro/camel,gilfernandes/camel,NickCis/camel,drsquidop/camel,anoordover/camel
/** * 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.camel.swagger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.RefModel; import io.swagger.models.Response; import io.swagger.models.Swagger; import io.swagger.models.Tag; import io.swagger.models.parameters.AbstractSerializableParameter; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.PathParameter; import io.swagger.models.parameters.QueryParameter; import io.swagger.models.parameters.SerializableParameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import org.apache.camel.model.rest.RestDefinition; import org.apache.camel.model.rest.RestOperationParamDefinition; import org.apache.camel.model.rest.RestOperationResponseHeaderDefinition; import org.apache.camel.model.rest.RestOperationResponseMsgDefinition; import org.apache.camel.model.rest.RestParamType; import org.apache.camel.model.rest.VerbDefinition; import org.apache.camel.spi.ClassResolver; import org.apache.camel.util.FileUtil; import org.apache.camel.util.ObjectHelper; /** * A Camel REST-DSL swagger reader that parse the rest-dsl into a swagger model representation. * <p/> * This reader supports the <a href="http://swagger.io/specification/">Swagger Specification 2.0</a> */ public class RestSwaggerReader { /** * Read the REST-DSL definition's and parse that as a Swagger model representation * * @param rests the rest-dsl * @param route optional route path to filter the rest-dsl to only include from the chose route * @param config the swagger configuration * @param classResolver class resolver to use * @return the swagger model */ public Swagger read(List<RestDefinition> rests, String route, BeanConfig config, String camelContextId, ClassResolver classResolver) { Swagger swagger = new Swagger(); for (RestDefinition rest : rests) { if (ObjectHelper.isNotEmpty(route) && !route.equals("/")) { // filter by route if (!rest.getPath().equals(route)) { continue; } } parse(swagger, rest, camelContextId, classResolver); } // configure before returning swagger = config.configure(swagger); return swagger; } private void parse(Swagger swagger, RestDefinition rest, String camelContextId, ClassResolver classResolver) { List<VerbDefinition> verbs = new ArrayList<>(rest.getVerbs()); // must sort the verbs by uri so we group them together when an uri has multiple operations Collections.sort(verbs, new VerbOrdering()); // we need to group the operations within the same tag, so use the path as default if not configured String pathAsTag = rest.getTag() != null ? rest.getTag() : FileUtil.stripLeadingSeparator(rest.getPath()); String summary = rest.getDescriptionText(); if (ObjectHelper.isNotEmpty(pathAsTag)) { // add rest as tag Tag tag = new Tag(); tag.description(summary); tag.name(pathAsTag); swagger.addTag(tag); } // gather all types in use Set<String> types = new LinkedHashSet<>(); for (VerbDefinition verb : verbs) { // check if the Verb Definition must be excluded from documentation Boolean apiDocs; if (verb.getApiDocs() != null) { apiDocs = verb.getApiDocs(); } else { // fallback to option on rest apiDocs = rest.getApiDocs(); } if (apiDocs != null && !apiDocs) { continue; } String type = verb.getType(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } type = verb.getOutType(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } // there can also be types in response messages if (verb.getResponseMsgs() != null) { for (RestOperationResponseMsgDefinition def : verb.getResponseMsgs()) { type = def.getResponseModel(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } } } } // use annotation scanner to find models (annotated classes) for (String type : types) { Class<?> clazz = classResolver.resolveClass(type); appendModels(clazz, swagger); } doParseVerbs(swagger, rest, camelContextId, verbs, pathAsTag); } private void doParseVerbs(Swagger swagger, RestDefinition rest, String camelContextId, List<VerbDefinition> verbs, String pathAsTag) { // used during gathering of apis List<Path> paths = new ArrayList<>(); String basePath = rest.getPath(); for (VerbDefinition verb : verbs) { // check if the Verb Definition must be excluded from documentation Boolean apiDocs; if (verb.getApiDocs() != null) { apiDocs = verb.getApiDocs(); } else { // fallback to option on rest apiDocs = rest.getApiDocs(); } if (apiDocs != null && !apiDocs) { continue; } // the method must be in lower case String method = verb.asVerb().toLowerCase(Locale.US); // operation path is a key String opPath = SwaggerHelper.buildUrl(basePath, verb.getUri()); Operation op = new Operation(); if (ObjectHelper.isNotEmpty(pathAsTag)) { // group in the same tag op.addTag(pathAsTag); } // add id as vendor extensions op.getVendorExtensions().put("x-camelContextId", camelContextId); op.getVendorExtensions().put("x-routeId", verb.getRouteId()); Path path = swagger.getPath(opPath); if (path == null) { path = new Path(); paths.add(path); } path = path.set(method, op); String consumes = verb.getConsumes() != null ? verb.getConsumes() : rest.getConsumes(); if (consumes != null) { String[] parts = consumes.split(","); for (String part : parts) { op.addConsumes(part); } } String produces = verb.getProduces() != null ? verb.getProduces() : rest.getProduces(); if (produces != null) { String[] parts = produces.split(","); for (String part : parts) { op.addProduces(part); } } if (verb.getDescriptionText() != null) { op.summary(verb.getDescriptionText()); } for (RestOperationParamDefinition param : verb.getParams()) { Parameter parameter = null; if (param.getType().equals(RestParamType.body)) { parameter = new BodyParameter(); } else if (param.getType().equals(RestParamType.formData)) { parameter = new FormParameter(); } else if (param.getType().equals(RestParamType.header)) { parameter = new HeaderParameter(); } else if (param.getType().equals(RestParamType.path)) { parameter = new PathParameter(); } else if (param.getType().equals(RestParamType.query)) { parameter = new QueryParameter(); } if (parameter != null) { parameter.setName(param.getName()); parameter.setDescription(param.getDescription()); parameter.setRequired(param.getRequired()); // set type on parameter if (parameter instanceof SerializableParameter) { SerializableParameter serializableParameter = (SerializableParameter) parameter; if (param.getDataType() != null) { serializableParameter.setType(param.getDataType()); if (param.getDataType().equalsIgnoreCase("array")) { if (param.getArrayType() != null) { if (param.getArrayType().equalsIgnoreCase("string")) { serializableParameter.setItems(new StringProperty()); } if (param.getArrayType().equalsIgnoreCase("int") || param.getArrayType().equalsIgnoreCase("integer")) { serializableParameter.setItems(new IntegerProperty()); } if (param.getArrayType().equalsIgnoreCase("long")) { serializableParameter.setItems(new LongProperty()); } if (param.getArrayType().equalsIgnoreCase("float")) { serializableParameter.setItems(new FloatProperty()); } if (param.getArrayType().equalsIgnoreCase("double")) { serializableParameter.setItems(new DoubleProperty()); } if (param.getArrayType().equalsIgnoreCase("boolean")) { serializableParameter.setItems(new BooleanProperty()); } } } } if (param.getCollectionFormat() != null) { serializableParameter.setCollectionFormat(param.getCollectionFormat().name()); } if (param.getAllowableValues() != null && !param.getAllowableValues().isEmpty()) { serializableParameter.setEnum(param.getAllowableValues()); } } // set default value on parameter if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter qp = (AbstractSerializableParameter) parameter; if (param.getDefaultValue() != null) { qp.setDefaultValue(param.getDefaultValue()); } } // set schema on body parameter if (parameter instanceof BodyParameter) { BodyParameter bp = (BodyParameter) parameter; if (verb.getType() != null) { if (verb.getType().endsWith("[]")) { String typeName = verb.getType(); typeName = typeName.substring(0, typeName.length() - 2); Property prop = modelTypeAsProperty(typeName, swagger); if (prop != null) { ArrayModel arrayModel = new ArrayModel(); arrayModel.setItems(prop); bp.setSchema(arrayModel); } } else { String ref = modelTypeAsRef(verb.getType(), swagger); if (ref != null) { bp.setSchema(new RefModel(ref)); } } } } op.addParameter(parameter); } } // if we have an out type then set that as response message if (verb.getOutType() != null) { Response response = new Response(); Property prop = modelTypeAsProperty(verb.getOutType(), swagger); response.setSchema(prop); response.setDescription("Output type"); op.addResponse("200", response); } // enrich with configured response messages from the rest-dsl doParseResponseMessages(swagger, verb, op); // add path swagger.path(opPath, path); } } private void doParseResponseMessages(Swagger swagger, VerbDefinition verb, Operation op) { for (RestOperationResponseMsgDefinition msg : verb.getResponseMsgs()) { Response response = null; if (op.getResponses() != null) { response = op.getResponses().get(msg.getCode()); } if (response == null) { response = new Response(); } if (ObjectHelper.isNotEmpty(msg.getResponseModel())) { Property prop = modelTypeAsProperty(msg.getResponseModel(), swagger); response.setSchema(prop); } response.setDescription(msg.getMessage()); // add headers if (msg.getHeaders() != null) { for (RestOperationResponseHeaderDefinition header : msg.getHeaders()) { String name = header.getName(); String type = header.getDataType(); if ("string".equals(type)) { StringProperty sp = new StringProperty(); sp.setName(name); sp.setDescription(header.getDescription()); if (header.getAllowableValues() != null) { sp.setEnum(header.getAllowableValues()); } response.addHeader(name, sp); } else if ("int".equals(type) || "integer".equals(type)) { IntegerProperty ip = new IntegerProperty(); ip.setName(name); ip.setDescription(header.getDescription()); List<Integer> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Integer>(); for (String text : header.getAllowableValues()) { values.add(Integer.valueOf(text)); } ip.setEnum(values); } response.addHeader(name, ip); } else if ("long".equals(type)) { LongProperty lp = new LongProperty(); lp.setName(name); lp.setDescription(header.getDescription()); List<Long> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Long>(); for (String text : header.getAllowableValues()) { values.add(Long.valueOf(text)); } lp.setEnum(values); } response.addHeader(name, lp); } else if ("float".equals(type)) { FloatProperty lp = new FloatProperty(); lp.setName(name); lp.setDescription(header.getDescription()); List<Float> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Float>(); for (String text : header.getAllowableValues()) { values.add(Float.valueOf(text)); } lp.setEnum(values); } response.addHeader(name, lp); } else if ("double".equals(type)) { DoubleProperty dp = new DoubleProperty(); dp.setName(name); dp.setDescription(header.getDescription()); List<Double> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Double>(); for (String text : header.getAllowableValues()) { values.add(Double.valueOf(text)); } dp.setEnum(values); } response.addHeader(name, dp); } else if ("boolean".equals(type)) { BooleanProperty bp = new BooleanProperty(); bp.setName(name); bp.setDescription(header.getDescription()); response.addHeader(name, bp); } else if ("array".equals(type)) { ArrayProperty ap = new ArrayProperty(); ap.setName(name); ap.setDescription(header.getDescription()); if (header.getArrayType() != null) { if (header.getArrayType().equalsIgnoreCase("string")) { ap.setItems(new StringProperty()); } if (header.getArrayType().equalsIgnoreCase("int") || header.getArrayType().equalsIgnoreCase("integer")) { ap.setItems(new IntegerProperty()); } if (header.getArrayType().equalsIgnoreCase("long")) { ap.setItems(new LongProperty()); } if (header.getArrayType().equalsIgnoreCase("float")) { ap.setItems(new FloatProperty()); } if (header.getArrayType().equalsIgnoreCase("double")) { ap.setItems(new DoubleProperty()); } if (header.getArrayType().equalsIgnoreCase("boolean")) { ap.setItems(new BooleanProperty()); } } response.addHeader(name, ap); } } } op.addResponse(msg.getCode(), response); } } private Model asModel(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } if (swagger.getDefinitions() != null) { for (Model model : swagger.getDefinitions().values()) { StringProperty modelType = (StringProperty) model.getVendorExtensions().get("x-className"); if (modelType != null && typeName.equals(modelType.getFormat())) { return model; } } } return null; } private String modelTypeAsRef(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } Model model = asModel(typeName, swagger); if (model != null) { typeName = ((ModelImpl) model).getName(); return typeName; } return null; } private Property modelTypeAsProperty(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } String ref = modelTypeAsRef(typeName, swagger); Property prop = ref != null ? new RefProperty(ref) : new StringProperty(typeName); if (array) { return new ArrayProperty(prop); } else { return prop; } } /** * If the class is annotated with swagger annotations its parsed into a Swagger model representation * which is added to swagger * * @param clazz the class such as pojo with swagger annotation * @param swagger the swagger model */ private void appendModels(Class clazz, Swagger swagger) { RestModelConverters converters = new RestModelConverters(); final Map<String, Model> models = converters.readClass(clazz); for (Map.Entry<String, Model> entry : models.entrySet()) { // favor keeping any existing model that has the vendor extension in the model boolean oldExt = false; if (swagger.getDefinitions() != null && swagger.getDefinitions().get(entry.getKey()) != null) { Model oldModel = swagger.getDefinitions().get(entry.getKey()); if (oldModel.getVendorExtensions() != null && !oldModel.getVendorExtensions().isEmpty()) { oldExt = oldModel.getVendorExtensions().get("x-className") != null; } } if (!oldExt) { swagger.model(entry.getKey(), entry.getValue()); } } } /** * To sort the rest operations */ private static class VerbOrdering implements Comparator<VerbDefinition> { @Override public int compare(VerbDefinition a, VerbDefinition b) { String u1 = ""; if (a.getUri() != null) { // replace { with _ which comes before a when soring by char u1 = a.getUri().replace("{", "_"); } String u2 = ""; if (b.getUri() != null) { // replace { with _ which comes before a when soring by char u2 = b.getUri().replace("{", "_"); } int num = u1.compareTo(u2); if (num == 0) { // same uri, so use http method as sorting num = a.asVerb().compareTo(b.asVerb()); } return num; } } }
components/camel-swagger-java/src/main/java/org/apache/camel/swagger/RestSwaggerReader.java
/** * 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.camel.swagger; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import io.swagger.jaxrs.config.BeanConfig; import io.swagger.models.ArrayModel; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.RefModel; import io.swagger.models.Response; import io.swagger.models.Swagger; import io.swagger.models.Tag; import io.swagger.models.parameters.AbstractSerializableParameter; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.parameters.PathParameter; import io.swagger.models.parameters.QueryParameter; import io.swagger.models.parameters.SerializableParameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DoubleProperty; import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; import org.apache.camel.model.rest.RestDefinition; import org.apache.camel.model.rest.RestOperationParamDefinition; import org.apache.camel.model.rest.RestOperationResponseHeaderDefinition; import org.apache.camel.model.rest.RestOperationResponseMsgDefinition; import org.apache.camel.model.rest.RestParamType; import org.apache.camel.model.rest.VerbDefinition; import org.apache.camel.spi.ClassResolver; import org.apache.camel.util.FileUtil; import org.apache.camel.util.ObjectHelper; /** * A Camel REST-DSL swagger reader that parse the rest-dsl into a swagger model representation. * <p/> * This reader supports the <a href="http://swagger.io/specification/">Swagger Specification 2.0</a> */ public class RestSwaggerReader { /** * Read the REST-DSL definition's and parse that as a Swagger model representation * * @param rests the rest-dsl * @param route optional route path to filter the rest-dsl to only include from the chose route * @param config the swagger configuration * @param classResolver class resolver to use * @return the swagger model */ public Swagger read(List<RestDefinition> rests, String route, BeanConfig config, String camelContextId, ClassResolver classResolver) { Swagger swagger = new Swagger(); for (RestDefinition rest : rests) { if (ObjectHelper.isNotEmpty(route) && !route.equals("/")) { // filter by route if (!rest.getPath().equals(route)) { continue; } } parse(swagger, rest, camelContextId, classResolver); } // configure before returning swagger = config.configure(swagger); return swagger; } private void parse(Swagger swagger, RestDefinition rest, String camelContextId, ClassResolver classResolver) { List<VerbDefinition> verbs = new ArrayList<>(rest.getVerbs()); // must sort the verbs by uri so we group them together when an uri has multiple operations Collections.sort(verbs, new VerbOrdering()); // we need to group the operations within the same tag, so use the path as default if not configured String pathAsTag = rest.getTag() != null ? rest.getTag() : FileUtil.stripLeadingSeparator(rest.getPath()); String summary = rest.getDescriptionText(); if (ObjectHelper.isNotEmpty(pathAsTag)) { // add rest as tag Tag tag = new Tag(); tag.description(summary); tag.name(pathAsTag); swagger.addTag(tag); } // gather all types in use Set<String> types = new LinkedHashSet<>(); for (VerbDefinition verb : verbs) { // check if the Verb Definition must be excluded from documentation Boolean apiDocs; if (verb.getApiDocs() != null) { apiDocs = verb.getApiDocs(); } else { // fallback to option on rest apiDocs = rest.getApiDocs(); } if (apiDocs != null && !apiDocs) { continue; } String type = verb.getType(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } type = verb.getOutType(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } // there can also be types in response messages if (verb.getResponseMsgs() != null) { for (RestOperationResponseMsgDefinition def : verb.getResponseMsgs()) { type = def.getResponseModel(); if (ObjectHelper.isNotEmpty(type)) { if (type.endsWith("[]")) { type = type.substring(0, type.length() - 2); } types.add(type); } } } } // use annotation scanner to find models (annotated classes) for (String type : types) { Class<?> clazz = classResolver.resolveClass(type); appendModels(clazz, swagger); } doParseVerbs(swagger, rest, camelContextId, verbs, pathAsTag); } private void doParseVerbs(Swagger swagger, RestDefinition rest, String camelContextId, List<VerbDefinition> verbs, String pathAsTag) { // used during gathering of apis List<Path> paths = new ArrayList<>(); String basePath = rest.getPath(); for (VerbDefinition verb : verbs) { // check if the Verb Definition must be excluded from documentation Boolean apiDocs; if (verb.getApiDocs() != null) { apiDocs = verb.getApiDocs(); } else { // fallback to option on rest apiDocs = rest.getApiDocs(); } if (apiDocs != null && !apiDocs) { continue; } // the method must be in lower case String method = verb.asVerb().toLowerCase(Locale.US); // operation path is a key String opPath = SwaggerHelper.buildUrl(basePath, verb.getUri()); Operation op = new Operation(); if (ObjectHelper.isNotEmpty(pathAsTag)) { // group in the same tag op.addTag(pathAsTag); } // add id as vendor extensions op.getVendorExtensions().put("x-camelContextId", camelContextId); op.getVendorExtensions().put("x-routeId", verb.getRouteId()); Path path = swagger.getPath(opPath); if (path == null) { path = new Path(); paths.add(path); } path = path.set(method, op); String consumes = verb.getConsumes() != null ? verb.getConsumes() : rest.getConsumes(); if (consumes != null) { String[] parts = consumes.split(","); for (String part : parts) { op.addConsumes(part); } } String produces = verb.getProduces() != null ? verb.getProduces() : rest.getProduces(); if (produces != null) { String[] parts = produces.split(","); for (String part : parts) { op.addProduces(part); } } if (verb.getDescriptionText() != null) { op.summary(verb.getDescriptionText()); } for (RestOperationParamDefinition param : verb.getParams()) { Parameter parameter = null; if (param.getType().equals(RestParamType.body)) { parameter = new BodyParameter(); } else if (param.getType().equals(RestParamType.formData)) { parameter = new FormParameter(); } else if (param.getType().equals(RestParamType.header)) { parameter = new HeaderParameter(); } else if (param.getType().equals(RestParamType.path)) { parameter = new PathParameter(); } else if (param.getType().equals(RestParamType.query)) { parameter = new QueryParameter(); } if (parameter != null) { parameter.setName(param.getName()); parameter.setDescription(param.getDescription()); parameter.setRequired(param.getRequired()); // set type on parameter if (parameter instanceof SerializableParameter) { SerializableParameter serializableParameter = (SerializableParameter) parameter; if (param.getDataType() != null) { serializableParameter.setType(param.getDataType()); if (param.getDataType().equalsIgnoreCase("array")) { if (param.getArrayType() != null) { if (param.getArrayType().equalsIgnoreCase("string")) { serializableParameter.setItems(new StringProperty()); } if (param.getArrayType().equalsIgnoreCase("int") || param.getArrayType().equalsIgnoreCase("integer")) { serializableParameter.setItems(new IntegerProperty()); } if (param.getArrayType().equalsIgnoreCase("long")) { serializableParameter.setItems(new LongProperty()); } if (param.getArrayType().equalsIgnoreCase("float")) { serializableParameter.setItems(new FloatProperty()); } if (param.getArrayType().equalsIgnoreCase("double")) { serializableParameter.setItems(new DoubleProperty()); } if (param.getArrayType().equalsIgnoreCase("boolean")) { serializableParameter.setItems(new BooleanProperty()); } } } } if (param.getCollectionFormat() != null) { serializableParameter.setCollectionFormat(param.getCollectionFormat().name()); } if (param.getAllowableValues() != null && !param.getAllowableValues().isEmpty()) { serializableParameter.setEnum(param.getAllowableValues()); } } // set default value on parameter if (parameter instanceof AbstractSerializableParameter) { AbstractSerializableParameter qp = (AbstractSerializableParameter) parameter; if (param.getDefaultValue() != null) { qp.setDefaultValue(param.getDefaultValue()); } } // set schema on body parameter if (parameter instanceof BodyParameter) { BodyParameter bp = (BodyParameter) parameter; if (verb.getType() != null) { if (verb.getType().endsWith("[]")) { String typeName = verb.getType(); typeName = typeName.substring(0, typeName.length() - 2); Property prop = modelTypeAsProperty(typeName, swagger); if (prop != null) { ArrayModel arrayModel = new ArrayModel(); arrayModel.setItems(prop); bp.setSchema(arrayModel); } } else { String ref = modelTypeAsRef(verb.getType(), swagger); if (ref != null) { bp.setSchema(new RefModel(ref)); } } } } op.addParameter(parameter); } } // if we have an out type then set that as response message if (verb.getOutType() != null) { Response response = new Response(); Property prop = modelTypeAsProperty(verb.getOutType(), swagger); response.setSchema(prop); response.setDescription("Output type"); op.addResponse("200", response); } // enrich with configured response messages from the rest-dsl doParseResponseMessages(swagger, verb, op); // add path swagger.path(opPath, path); } } private void doParseResponseMessages(Swagger swagger, VerbDefinition verb, Operation op) { for (RestOperationResponseMsgDefinition msg : verb.getResponseMsgs()) { Response response = null; if (op.getResponses() != null) { response = op.getResponses().get(msg.getCode()); } if (response == null) { response = new Response(); } if (ObjectHelper.isNotEmpty(msg.getResponseModel())) { Property prop = modelTypeAsProperty(msg.getResponseModel(), swagger); response.setSchema(prop); } response.setDescription(msg.getMessage()); // add headers if (msg.getHeaders() != null) { for (RestOperationResponseHeaderDefinition header : msg.getHeaders()) { String name = header.getName(); String type = header.getDataType(); if ("string".equals(type)) { StringProperty sp = new StringProperty(); sp.setName(name); sp.setDescription(header.getDescription()); if (header.getAllowableValues() != null) { sp.setEnum(header.getAllowableValues()); } response.addHeader(name, sp); } else if ("int".equals(type) || "integer".equals(type)) { IntegerProperty ip = new IntegerProperty(); ip.setName(name); ip.setDescription(header.getDescription()); List<Integer> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Integer>(); for (String text : header.getAllowableValues()) { values.add(Integer.valueOf(text)); } ip.setEnum(values); } response.addHeader(name, ip); } else if ("long".equals(type)) { LongProperty lp = new LongProperty(); lp.setName(name); lp.setDescription(header.getDescription()); List<Long> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Long>(); for (String text : header.getAllowableValues()) { values.add(Long.valueOf(text)); } lp.setEnum(values); } response.addHeader(name, lp); } else if ("float".equals(type)) { FloatProperty lp = new FloatProperty(); lp.setName(name); lp.setDescription(header.getDescription()); List<Float> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Float>(); for (String text : header.getAllowableValues()) { values.add(Float.valueOf(text)); } lp.setEnum(values); } response.addHeader(name, lp); } else if ("double".equals(type)) { DoubleProperty dp = new DoubleProperty(); dp.setName(name); dp.setDescription(header.getDescription()); List<Double> values; if (!header.getAllowableValues().isEmpty()) { values = new ArrayList<Double>(); for (String text : header.getAllowableValues()) { values.add(Double.valueOf(text)); } dp.setEnum(values); } response.addHeader(name, dp); } else if ("boolean".equals(type)) { BooleanProperty bp = new BooleanProperty(); bp.setName(name); bp.setDescription(header.getDescription()); response.addHeader(name, bp); } else if ("array".equals(type)) { ArrayProperty ap = new ArrayProperty(); ap.setName(name); ap.setDescription(header.getDescription()); if (header.getArrayType() != null) { if (header.getArrayType().equalsIgnoreCase("string")) { ap.setItems(new StringProperty()); } if (header.getArrayType().equalsIgnoreCase("int") || header.getArrayType().equalsIgnoreCase("integer")) { ap.setItems(new IntegerProperty()); } if (header.getArrayType().equalsIgnoreCase("long")) { ap.setItems(new LongProperty()); } if (header.getArrayType().equalsIgnoreCase("float")) { ap.setItems(new FloatProperty()); } if (header.getArrayType().equalsIgnoreCase("double")) { ap.setItems(new DoubleProperty()); } if (header.getArrayType().equalsIgnoreCase("boolean")) { ap.setItems(new BooleanProperty()); } } response.addHeader(name, ap); } } } op.addResponse(msg.getCode(), response); } } private Model asModel(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } if (swagger.getDefinitions() != null) { for (Model model : swagger.getDefinitions().values()) { StringProperty modelType = (StringProperty) model.getVendorExtensions().get("x-className"); if (modelType != null && typeName.equals(modelType.getFormat())) { return model; } } } return null; } private String modelTypeAsRef(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } Model model = asModel(typeName, swagger); if (model != null) { typeName = ((ModelImpl) model).getName(); return typeName; } return null; } private Property modelTypeAsProperty(String typeName, Swagger swagger) { boolean array = typeName.endsWith("[]"); if (array) { typeName = typeName.substring(0, typeName.length() - 2); } String ref = modelTypeAsRef(typeName, swagger); Property prop = ref != null ? new RefProperty(ref) : new StringProperty(typeName); if (array) { return new ArrayProperty(prop); } else { return prop; } } /** * If the class is annotated with swagger annotations its parsed into a Swagger model representation * which is added to swagger * * @param clazz the class such as pojo with swagger annotation * @param swagger the swagger model */ private void appendModels(Class clazz, Swagger swagger) { RestModelConverters converters = new RestModelConverters(); final Map<String, Model> models = converters.readClass(clazz); for (Map.Entry<String, Model> entry : models.entrySet()) { // favor keeping any existing model that has the vendor extension in the model boolean oldExt = false; if (swagger.getDefinitions() != null && swagger.getDefinitions().get(entry.getKey()) != null) { Model oldModel = swagger.getDefinitions().get(entry.getKey()); if (oldModel.getVendorExtensions() != null && !oldModel.getVendorExtensions().isEmpty()) { oldExt = oldModel.getVendorExtensions().get("x-className") == null; } } if (!oldExt) { swagger.model(entry.getKey(), entry.getValue()); } } } /** * To sort the rest operations */ private static class VerbOrdering implements Comparator<VerbDefinition> { @Override public int compare(VerbDefinition a, VerbDefinition b) { String u1 = ""; if (a.getUri() != null) { // replace { with _ which comes before a when soring by char u1 = a.getUri().replace("{", "_"); } String u2 = ""; if (b.getUri() != null) { // replace { with _ which comes before a when soring by char u2 = b.getUri().replace("{", "_"); } int num = u1.compareTo(u2); if (num == 0) { // same uri, so use http method as sorting num = a.asVerb().compareTo(b.asVerb()); } return num; } } }
Fix for invalid logic in swagger java component - models were not updated to models with vendor extension
components/camel-swagger-java/src/main/java/org/apache/camel/swagger/RestSwaggerReader.java
Fix for invalid logic in swagger java component - models were not updated to models with vendor extension
Java
apache-2.0
4484ca86a427870457388280e1f95f5fa29060a2
0
apache/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,apache/jmeter,ham1/jmeter,apache/jmeter,ham1/jmeter,benbenw/jmeter,etnetera/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,benbenw/jmeter,ham1/jmeter,etnetera/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter
/* * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache JMeter" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache JMeter", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.jmeter.visualizers; import java.text.DecimalFormat; import org.apache.jmeter.samplers.SampleResult; /** * Aggegate sample data container. Just instantiate a new instance of this * class, and then call {@link #addSample(SampleResult)} a few times, and pull * the stats out with whatever methods you prefer. * * @author James Boutcher * @version $Revision$ */ public class RunningSample { private static DecimalFormat rateFormatter = new DecimalFormat("#.0"); private static DecimalFormat errorFormatter = new DecimalFormat("#0.00%"); private long counter; private long runningSum; private long max, min; private long errorCount; private long firstTime; private long lastTime; private String label; private int index; private RunningSample(){// Don't (can't) use this... } /** * Use this constructor. */ public RunningSample(String label, int index) { this.label = label; this.index = index; init(); } /** * Copy constructor to a duplicate of existing instance * (without the disadvantages of clone()0 * @param src RunningSample */ public RunningSample(RunningSample src){ this.counter = src.counter; this.errorCount = src.errorCount; this.firstTime = src.firstTime; this.index = src.index; this.label = src.label; this.lastTime = src.lastTime; this.max = src.max; this.min = src.min; this.runningSum = src.runningSum; } private void init(){ counter = 0L; runningSum = 0L; max = Long.MIN_VALUE; min = Long.MAX_VALUE; errorCount = 0L; firstTime = Long.MAX_VALUE; lastTime = 0L; } /** * Clear the counters (useful for differential stats) * */ public synchronized void clear(){ init(); } /** * Get the elapsed time for the samples * @return how long the samples took */ public long getElapsed(){ if (lastTime == 0) return 0;// No samples collected ... return lastTime - firstTime; } /** * Returns the throughput associated to this sampler in requests per second. * May be slightly skewed because it takes the timestamps of the first and * last samples as the total time passed, and the test may actually have * started before that start time and ended after that end time. **/ public double getRate() { if (counter == 0) return 0.0; //Better behaviour when howLong=0 or lastTime=0 long howLongRunning = lastTime - firstTime; if (howLongRunning == 0) { return Double.MAX_VALUE; } return (double) counter / howLongRunning * 1000.0; } /** * Returns the throughput associated to this sampler in requests per min. * May be slightly skewed because it takes the timestamps of the first and * last samples as the total time passed, and the test may actually have * started before that start time and ended after that end time. **/ public double getRatePerMin() { if (counter == 0) return 0.0; //Better behaviour when howLong=0 or lastTime=0 long howLongRunning = lastTime - firstTime; if (howLongRunning == 0) { return Double.MAX_VALUE; } return (double) counter / howLongRunning * 60000.0; } /** * Returns a String that represents the throughput associated for this * sampler, in units appropriate to its dimension: * <p> * The number is represented in requests/second or requests/minute or * requests/hour. * <p> * Examples: * "34.2/sec" * "0.1/sec" * "43.0/hour" * "15.9/min" * @return a String representation of the rate the samples are being taken * at. */ public String getRateString() { double rate = getRate(); if (rate == Double.MAX_VALUE) { return "N/A"; } String unit = "sec"; if (rate < 1.0) { rate *= 60.0; unit = "min"; } if (rate < 1.0) { rate *= 60.0; unit = "/hour"; } String rval = rateFormatter.format(rate) + "/" + unit; return (rval); } public String getLabel() { return label; } public int getIndex() { return index; } /** * Records a sample. * */ public synchronized void addSample(SampleResult res) { long aTimeInMillis = res.getTime(); boolean aSuccessFlag = res.isSuccessful(); counter++; long startTime = res.getTimeStamp() - aTimeInMillis; if (firstTime > startTime) { // this is our first sample, set the start time to current timestamp firstTime = startTime; } if(lastTime < res.getTimeStamp()) { lastTime = res.getTimeStamp(); } runningSum += aTimeInMillis; if (aTimeInMillis > max) { max = aTimeInMillis; } if (aTimeInMillis < min) { min = aTimeInMillis; } if (!aSuccessFlag) { errorCount++; } } /** * Adds another RunningSample to this one * Does not check if it has the same label and index */ public synchronized void addSample(RunningSample rs) { this.counter += rs.counter; this.errorCount += rs.errorCount; this.runningSum += rs.runningSum; if (this.firstTime > rs.firstTime) this.firstTime = rs.firstTime; if (this.lastTime < rs.lastTime) this.lastTime = rs.lastTime; if (this.max < rs.max) this.max = rs.max; if (this.min > rs.min) this.min = rs.min; } /** * Returns the time in milliseconds of the quickest sample. * @return the time in milliseconds of the quickest sample. */ public long getMin() { long rval = 0; if (min != Long.MAX_VALUE) { rval = min; } return (rval); } /** * Returns the time in milliseconds of the slowest sample. * @return the time in milliseconds of the slowest sample. */ public long getMax() { long rval = 0; if (max != Long.MIN_VALUE) { rval = max; } return (rval); } /** * Returns the average time in milliseconds that samples ran in. * @return the average time in milliseconds that samples ran in. */ public long getAverage() { if (counter == 0) { return (0); } return (runningSum / counter); } /** * Returns the number of samples that have been recorded by this instance * of the RunningSample class. * @return the number of samples that have been recorded by this instance * of the RunningSample class. */ public long getNumSamples() { return (counter); } /** * Returns the raw double value of the percentage of samples with errors * that were recorded. (Between 0.0 and 1.0) * If you want a nicer return format, see * {@link #getErrorPercentageString()}. * * @return the raw double value of the percentage of samples with errors * that were recorded. */ public double getErrorPercentage() { double rval = 0.0; if (counter == 0) { return (rval); } rval = (double) errorCount / (double) counter; return (rval); } /** * Returns a String which represents the percentage of sample errors that * have occurred. ("0.00%" through "100.00%") * * @return a String which represents the percentage of sample errors that * have occurred. */ public String getErrorPercentageString() { double myErrorPercentage = this.getErrorPercentage(); return (errorFormatter.format(myErrorPercentage)); } /** * For debugging purposes, mainly. */ public String toString() { StringBuffer mySB = new StringBuffer(); mySB.append("Samples: " + this.getNumSamples() + " "); mySB.append("Avg: " + this.getAverage() + " "); mySB.append("Min: " + this.getMin() + " "); mySB.append("Max: " + this.getMax() + " "); mySB.append("Error Rate: " + this.getErrorPercentageString() + " "); mySB.append("Sample Rate: " + this.getRateString()); return (mySB.toString()); } /** * @return errorCount */ public long getErrorCount() { return errorCount; } } // class RunningSample
src/components/org/apache/jmeter/visualizers/RunningSample.java
/* * ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache JMeter" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache JMeter", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.jmeter.visualizers; import java.text.DecimalFormat; import org.apache.jmeter.samplers.SampleResult; /** * Aggegate sample data container. Just instantiate a new instance of this * class, and then call {@link #addSample(SampleResult)} a few times, and pull * the stats out with whatever methods you prefer. * * @author James Boutcher * @version $Revision$ */ public class RunningSample { private static DecimalFormat rateFormatter = new DecimalFormat("#.0"); private static DecimalFormat errorFormatter = new DecimalFormat("#0.00%"); private long counter; private long runningSum; private long max, min; private long errorCount; private long firstTime; private long lastTime; private String label; private int index; private RunningSample(){// Don't (can't) use this... } /** * Use this constructor. */ public RunningSample(String label, int index) { this.label = label; this.index = index; init(); } private void init(){ counter = 0L; runningSum = 0L; max = Long.MIN_VALUE; min = Long.MAX_VALUE; errorCount = 0L; firstTime = Long.MAX_VALUE; lastTime = 0L; } /** * Clear the counters (useful for differential stats) * */ public synchronized void clear(){ init(); } /** * Returns the throughput associated to this sampler in requests per second. * May be slightly skewed because it takes the timestamps of the first and * last samples as the total time passed, and the test may actually have * started before that start time and ended after that end time. **/ public double getRate() { long howLongRunning = lastTime - firstTime; if (howLongRunning == 0) { return Double.MAX_VALUE; } return (double) counter / howLongRunning * 1000.0; } /** * Returns the throughput associated to this sampler in requests per min. * May be slightly skewed because it takes the timestamps of the first and * last samples as the total time passed, and the test may actually have * started before that start time and ended after that end time. **/ public double getRatePerMin() { long howLongRunning = lastTime - firstTime; if (howLongRunning == 0) { return Double.MAX_VALUE; } return (double) counter / howLongRunning * 60000.0; } /** * Returns a String that represents the throughput associated for this * sampler, in units appropriate to its dimension: * <p> * The number is represented in requests/second or requests/minute or * requests/hour. * <p> * Examples: * "34.2/sec" * "0.1/sec" * "43.0/hour" * "15.9/min" * @return a String representation of the rate the samples are being taken * at. */ public String getRateString() { double rate = getRate(); if (rate == Double.MAX_VALUE) { return "N/A"; } String unit = "sec"; if (rate < 1.0) { rate *= 60.0; unit = "min"; } if (rate < 1.0) { rate *= 60.0; unit = "/hour"; } String rval = rateFormatter.format(rate) + "/" + unit; return (rval); } public String getLabel() { return label; } public int getIndex() { return index; } /** * Records a sample. * */ public synchronized void addSample(SampleResult res) { long aTimeInMillis = res.getTime(); boolean aSuccessFlag = res.isSuccessful(); counter++; long startTime = res.getTimeStamp() - aTimeInMillis; if (firstTime > startTime) { // this is our first sample, set the start time to current timestamp firstTime = startTime; } if(lastTime < res.getTimeStamp()) { lastTime = res.getTimeStamp(); } runningSum += aTimeInMillis; if (aTimeInMillis > max) { max = aTimeInMillis; } if (aTimeInMillis < min) { min = aTimeInMillis; } if (!aSuccessFlag) { errorCount++; } } /** * Returns the time in milliseconds of the quickest sample. * @return the time in milliseconds of the quickest sample. */ public long getMin() { long rval = 0; if (min != Long.MAX_VALUE) { rval = min; } return (rval); } /** * Returns the time in milliseconds of the slowest sample. * @return the time in milliseconds of the slowest sample. */ public long getMax() { long rval = 0; if (max != Long.MIN_VALUE) { rval = max; } return (rval); } /** * Returns the average time in milliseconds that samples ran in. * @return the average time in milliseconds that samples ran in. */ public long getAverage() { if (counter == 0) { return (0); } return (runningSum / counter); } /** * Returns the number of samples that have been recorded by this instance * of the RunningSample class. * @return the number of samples that have been recorded by this instance * of the RunningSample class. */ public long getNumSamples() { return (counter); } /** * Returns the raw double value of the percentage of samples with errors * that were recorded. (Between 0.0 and 1.0) * If you want a nicer return format, see * {@link #getErrorPercentageString()}. * * @return the raw double value of the percentage of samples with errors * that were recorded. */ public double getErrorPercentage() { double rval = 0.0; if (counter == 0) { return (rval); } rval = (double) errorCount / (double) counter; return (rval); } /** * Returns a String which represents the percentage of sample errors that * have occurred. ("0.00%" through "100.00%") * * @return a String which represents the percentage of sample errors that * have occurred. */ public String getErrorPercentageString() { double myErrorPercentage = this.getErrorPercentage(); return (errorFormatter.format(myErrorPercentage)); } /** * For debugging purposes, mainly. */ public String toString() { StringBuffer mySB = new StringBuffer(); mySB.append("Samples: " + this.getNumSamples() + " "); mySB.append("Avg: " + this.getAverage() + " "); mySB.append("Min: " + this.getMin() + " "); mySB.append("Max: " + this.getMax() + " "); mySB.append("Error Rate: " + this.getErrorPercentageString() + " "); mySB.append("Sample Rate: " + this.getRateString()); return (mySB.toString()); } /** * @return errorCount */ public long getErrorCount() { return errorCount; } } // class RunningSample
New method to add two RunningSamples; copy constructor; better getRate() behaviour when count=0 git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@323656 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: f42137062ac69ef94eacac795d6625e400daba39
src/components/org/apache/jmeter/visualizers/RunningSample.java
New method to add two RunningSamples; copy constructor; better getRate() behaviour when count=0
Java
apache-2.0
3078a109be89a96b02f73d3e9340c4f28f5ff22d
0
rojlarge/rice-kc,rojlarge/rice-kc,sonamuthu/rice-1,smith750/rice,smith750/rice,ewestfal/rice,jwillia/kc-rice1,cniesen/rice,ewestfal/rice-svn2git-test,geothomasp/kualico-rice-kc,kuali/kc-rice,shahess/rice,rojlarge/rice-kc,gathreya/rice-kc,ewestfal/rice,UniversityOfHawaiiORS/rice,bhutchinson/rice,shahess/rice,shahess/rice,ewestfal/rice-svn2git-test,bhutchinson/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,bhutchinson/rice,ewestfal/rice,gathreya/rice-kc,UniversityOfHawaiiORS/rice,jwillia/kc-rice1,jwillia/kc-rice1,sonamuthu/rice-1,kuali/kc-rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,kuali/kc-rice,bhutchinson/rice,shahess/rice,smith750/rice,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,cniesen/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,smith750/rice,sonamuthu/rice-1,rojlarge/rice-kc,geothomasp/kualico-rice-kc,jwillia/kc-rice1,gathreya/rice-kc,geothomasp/kualico-rice-kc,gathreya/rice-kc,bsmith83/rice-1,ewestfal/rice-svn2git-test,gathreya/rice-kc,sonamuthu/rice-1,bsmith83/rice-1,cniesen/rice,kuali/kc-rice,shahess/rice,smith750/rice,bhutchinson/rice,ewestfal/rice,kuali/kc-rice,cniesen/rice,ewestfal/rice,cniesen/rice,rojlarge/rice-kc
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.uif.container; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.exception.RiceRuntimeException; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifParameters; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.component.ComponentSecurity; import org.kuali.rice.krad.uif.component.DataBinding; import org.kuali.rice.krad.uif.element.Action; import org.kuali.rice.krad.uif.element.Label; import org.kuali.rice.krad.uif.field.DataField; import org.kuali.rice.krad.uif.field.Field; import org.kuali.rice.krad.uif.util.ComponentUtils; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.uif.widget.QuickFinder; import java.util.ArrayList; import java.util.List; /** * Group that holds a collection of objects and configuration for presenting the * collection in the UI. Supports functionality such as add line, line actions, * and nested collections. * * <p> * Note the standard header/footer can be used to give a header to the * collection as a whole, or to provide actions that apply to the entire * collection * </p> * * <p> * For binding purposes the binding path of each row field is indexed. The name * property inherited from <code>ComponentBase</code> is used as the collection * name. The collectionObjectClass property is used to lookup attributes from * the data dictionary. * </p> * * @author Kuali Rice Team ([email protected]) */ public class CollectionGroup extends Group implements DataBinding { private static final long serialVersionUID = -6496712566071542452L; private Class<?> collectionObjectClass; private String propertyName; private BindingInfo bindingInfo; private boolean renderAddLine; private String addLinePropertyName; private BindingInfo addLineBindingInfo; private Label addLineLabel; private List<? extends Component> addLineItems; private List<Action> addLineActions; private boolean renderLineActions; private List<Action> lineActions; private boolean includeLineSelectionField; private String lineSelectPropertyName; private QuickFinder collectionLookup; private boolean renderInactiveToggleButton; private boolean showInactiveLines; private CollectionFilter activeCollectionFilter; private List<CollectionFilter> filters; private List<CollectionGroup> subCollections; private String subCollectionSuffix; private CollectionGroupBuilder collectionGroupBuilder; private int displayCollectionSize = -1; private boolean highlightNewItems; private boolean highlightAddItem; private String newItemsCssClass; private String addItemCssClass; private boolean renderAddBlankLineButton; private Action addBlankLineAction; private String addLinePlacement; private boolean renderSaveLineActions; private boolean addViaLightBox; private Action addViaLightBoxAction; private List<String> totalColumns; public CollectionGroup() { renderAddLine = true; renderLineActions = true; renderSaveLineActions = false; showInactiveLines = false; renderInactiveToggleButton = true; includeLineSelectionField = false; highlightNewItems = true; addLinePlacement = "TOP"; filters = new ArrayList<CollectionFilter>(); lineActions = new ArrayList<Action>(); addLineItems = new ArrayList<Field>(); addLineActions = new ArrayList<Action>(); subCollections = new ArrayList<CollectionGroup>(); } /** * The following actions are performed: * * <ul> * <li>Set fieldBindModelPath to the collection model path (since the fields * have to belong to the same model as the collection)</li> * <li>Set defaults for binding</li> * <li>Default add line field list to groups items list</li> * <li>Sets default active collection filter if not set</li> * <li>Sets the dictionary entry (if blank) on each of the items to the * collection class</li> * </ul> * * @see org.kuali.rice.krad.uif.component.ComponentBase#performInitialization(org.kuali.rice.krad.uif.view.View, * java.lang.Object) */ @Override public void performInitialization(View view, Object model) { setFieldBindingObjectPath(getBindingInfo().getBindingObjectPath()); super.performInitialization(view, model); if (bindingInfo != null) { bindingInfo.setDefaults(view, getPropertyName()); } if (addLineBindingInfo != null) { // add line binds to model property if (StringUtils.isNotBlank(addLinePropertyName)) { addLineBindingInfo.setDefaults(view, getPropertyName()); addLineBindingInfo.setBindingName(addLinePropertyName); if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) { addLineBindingInfo.setBindByNamePrefix(getFieldBindByNamePrefix()); } } } for (Component item : getItems()) { if (item instanceof DataField) { DataField field = (DataField) item; if (StringUtils.isBlank(field.getDictionaryObjectEntry())) { field.setDictionaryObjectEntry(collectionObjectClass.getName()); } } } for (Component addLineField : addLineItems) { if (addLineField instanceof DataField) { DataField field = (DataField) addLineField; if (StringUtils.isBlank(field.getDictionaryObjectEntry())) { field.setDictionaryObjectEntry(collectionObjectClass.getName()); } } } if ((addLineItems == null) || addLineItems.isEmpty()) { addLineItems = getItems(); } // if active collection filter not set use default if (this.activeCollectionFilter == null) { activeCollectionFilter = new ActiveCollectionFilter(); } // set static collection path on items String collectionPath = ""; if (StringUtils.isNotBlank(getBindingInfo().getCollectionPath())) { collectionPath += getBindingInfo().getCollectionPath() + "."; } if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) { collectionPath += getBindingInfo().getBindByNamePrefix() + "."; } collectionPath += getBindingInfo().getBindingName(); List<DataField> collectionFields = ComponentUtils.getComponentsOfTypeDeep(getItems(), DataField.class); for (DataField collectionField : collectionFields) { collectionField.getBindingInfo().setCollectionPath(collectionPath); } List<DataField> addLineCollectionFields = ComponentUtils.getComponentsOfTypeDeep(addLineItems, DataField.class); for (DataField collectionField : addLineCollectionFields) { collectionField.getBindingInfo().setCollectionPath(collectionPath); } for (CollectionGroup collectionGroup : getSubCollections()) { collectionGroup.getBindingInfo().setCollectionPath(collectionPath); } // add collection entry to abstract classes if (!view.getObjectPathToConcreteClassMapping().containsKey(collectionPath)) { view.getObjectPathToConcreteClassMapping().put(collectionPath, getCollectionObjectClass()); } } /** * Calls the configured <code>CollectionGroupBuilder</code> to build the * necessary components based on the collection data * * @see org.kuali.rice.krad.uif.container.ContainerBase#performApplyModel(org.kuali.rice.krad.uif.view.View, * java.lang.Object, org.kuali.rice.krad.uif.component.Component) */ @Override public void performApplyModel(View view, Object model, Component parent) { super.performApplyModel(view, model, parent); pushCollectionGroupToReference(); // if rendering the collection group, build out the lines if (isRender()) { getCollectionGroupBuilder().build(view, model, this); } // TODO: is this necessary to call again? // This may be necessary to call in case getCollectionGroupBuilder().build resets the context map pushCollectionGroupToReference(); } /** * Sets a reference in the context map for all nested components to the collection group * instance, and sets name as parameter for an action fields in the group */ protected void pushCollectionGroupToReference() { List<Component> components = getComponentsForLifecycle(); components.addAll(getComponentPrototypes()); ComponentUtils.pushObjectToContext(components, UifConstants.ContextVariableNames.COLLECTION_GROUP, this); List<Action> actions = ComponentUtils.getComponentsOfTypeDeep(components, Action.class); for (Action action : actions) { action.addActionParameter(UifParameters.SELLECTED_COLLECTION_PATH, this.getBindingInfo().getBindingPath()); } } /** * New collection lines are handled in the framework by maintaining a map on * the form. The map contains as a key the collection name, and as value an * instance of the collection type. An entry is created here for the * collection represented by the <code>CollectionGroup</code> if an instance * is not available (clearExistingLine will force a new instance). The given * model must be a subclass of <code>UifFormBase</code> in order to find the * Map. * * @param model - Model instance that contains the new collection lines Map * @param clearExistingLine - boolean that indicates whether the line should be set to a * new instance if it already exists */ public void initializeNewCollectionLine(View view, Object model, CollectionGroup collectionGroup, boolean clearExistingLine) { getCollectionGroupBuilder().initializeNewCollectionLine(view, model, collectionGroup, clearExistingLine); } /** * @see org.kuali.rice.krad.uif.container.ContainerBase#getComponentsForLifecycle() */ @Override public List<Component> getComponentsForLifecycle() { List<Component> components = super.getComponentsForLifecycle(); components.add(addLineLabel); components.add(collectionLookup); components.add(addBlankLineAction); components.add(addViaLightBoxAction); // remove the containers items because we don't want them as children // (they will become children of the layout manager as the rows are created) for (Component item : getItems()) { if (components.contains(item)) { components.remove(item); } } return components; } /** * @see org.kuali.rice.krad.uif.component.Component#getComponentPrototypes() */ @Override public List<Component> getComponentPrototypes() { List<Component> components = super.getComponentPrototypes(); components.addAll(lineActions); components.addAll(addLineActions); components.addAll(getItems()); components.addAll(getSubCollections()); // iterate through addLineItems to make sure we have not already // added them as prototypes (they could have been copied from add lines) if (addLineItems != null) { for (Component addLineItem : addLineItems) { if (!components.contains(addLineItem)) { components.add(addLineItem); } } } return components; } /** * Object class the collection maintains. Used to get dictionary information * in addition to creating new instances for the collection when necessary * * @return Class<?> collection object class */ public Class<?> getCollectionObjectClass() { return this.collectionObjectClass; } /** * Setter for the collection object class * * @param collectionObjectClass */ public void setCollectionObjectClass(Class<?> collectionObjectClass) { this.collectionObjectClass = collectionObjectClass; } /** * @see org.kuali.rice.krad.uif.component.DataBinding#getPropertyName() */ public String getPropertyName() { return this.propertyName; } /** * Setter for the collections property name * * @param propertyName */ public void setPropertyName(String propertyName) { this.propertyName = propertyName; } /** * Determines the binding path for the collection. Used to get the * collection value from the model in addition to setting the binding path * for the collection attributes * * @see org.kuali.rice.krad.uif.component.DataBinding#getBindingInfo() */ public BindingInfo getBindingInfo() { return this.bindingInfo; } /** * Setter for the binding info instance * * @param bindingInfo */ public void setBindingInfo(BindingInfo bindingInfo) { this.bindingInfo = bindingInfo; } /** * Action fields that should be rendered for each collection line. Example * line action is the delete action * * @return List<Action> line action fields */ public List<Action> getLineActions() { return this.lineActions; } /** * Setter for the line action fields list * * @param lineActions */ public void setLineActions(List<Action> lineActions) { this.lineActions = lineActions; } /** * Indicates whether the action column for the collection should be rendered * * @return boolean true if the actions should be rendered, false if not * @see #getLineActions() */ public boolean isRenderLineActions() { return this.renderLineActions; } /** * Setter for the render line actions indicator * * @param renderLineActions */ public void setRenderLineActions(boolean renderLineActions) { this.renderLineActions = renderLineActions; } /** * Indicates whether an add line should be rendered for the collection * * @return boolean true if add line should be rendered, false if it should * not be */ public boolean isRenderAddLine() { return this.renderAddLine; } /** * Setter for the render add line indicator * * @param renderAddLine */ public void setRenderAddLine(boolean renderAddLine) { this.renderAddLine = renderAddLine; } /** * Convenience getter for the add line label field text. The text is used to * label the add line when rendered and its placement depends on the * <code>LayoutManager</code> * * <p> * For the <code>TableLayoutManager</code> the label appears in the sequence * column to the left of the add line fields. For the * <code>StackedLayoutManager</code> the label is placed into the group * header for the line. * </p> * * @return String add line label */ public String getAddLabel() { if (getAddLineLabel() != null) { return getAddLineLabel().getLabelText(); } return null; } /** * Setter for the add line label text * * @param addLabelText */ public void setAddLabel(String addLabelText) { if (getAddLineLabel() != null) { getAddLineLabel().setLabelText(addLabelText); } } /** * <code>Label</code> instance for the add line label * * @return Label add line label field * @see #getAddLabel */ public Label getAddLineLabel() { return this.addLineLabel; } /** * Setter for the <code>Label</code> instance for the add line label * * @param addLineLabel * @see #getAddLabel */ public void setAddLineLabel(Label addLineLabel) { this.addLineLabel = addLineLabel; } /** * Name of the property that contains an instance for the add line. If set * this is used with the binding info to create the path to the add line. * Can be left blank in which case the framework will manage the add line * instance in a generic map. * * @return String add line property name */ public String getAddLinePropertyName() { return this.addLinePropertyName; } /** * Setter for the add line property name * * @param addLinePropertyName */ public void setAddLinePropertyName(String addLinePropertyName) { this.addLinePropertyName = addLinePropertyName; } /** * <code>BindingInfo</code> instance for the add line property used to * determine the full binding path. If add line name given * {@link #getAddLabel} then it is set as the binding name on the * binding info. Add line label and binding info are not required, in which * case the framework will manage the new add line instances through a * generic map (model must extend UifFormBase) * * @return BindingInfo add line binding info */ public BindingInfo getAddLineBindingInfo() { return this.addLineBindingInfo; } /** * Setter for the add line binding info * * @param addLineBindingInfo */ public void setAddLineBindingInfo(BindingInfo addLineBindingInfo) { this.addLineBindingInfo = addLineBindingInfo; } /** * List of <code>Component</code> instances that should be rendered for the * collection add line (if enabled). If not set, the default group's items * list will be used * * @return List<? extends Component> add line field list * @see CollectionGroup#performInitialization(org.kuali.rice.krad.uif.view.View, java.lang.Object) */ public List<? extends Component> getAddLineItems() { return this.addLineItems; } /** * Setter for the add line field list * * @param addLineItems */ public void setAddLineItems(List<? extends Component> addLineItems) { this.addLineItems = addLineItems; } /** * Action fields that should be rendered for the add line. This is generally * the add action (button) but can be configured to contain additional * actions * * @return List<Action> add line action fields */ public List<Action> getAddLineActions() { return this.addLineActions; } /** * Setter for the add line action fields * * @param addLineActions */ public void setAddLineActions(List<Action> addLineActions) { this.addLineActions = addLineActions; } /** * Indicates whether lines of the collection group should be selected by rendering a * field for each line that will allow selection * * <p> * For example, having the select field enabled could allow selecting multiple lines from a search * to return (multi-value lookup) * </p> * * @return boolean true if select field should be rendered, false if not */ public boolean isIncludeLineSelectionField() { return includeLineSelectionField; } /** * Setter for the render selected field indicator * * @param includeLineSelectionField */ public void setIncludeLineSelectionField(boolean includeLineSelectionField) { this.includeLineSelectionField = includeLineSelectionField; } /** * When {@link #isIncludeLineSelectionField()} is true, gives the name of the property the select field * should bind to * * <p> * Note if no prefix is given in the property name, such as 'form.', it is assumed the property is * contained on the collection line. In this case the binding path to the collection line will be * appended. In other cases, it is assumed the property is a list or set of String that will hold the * selected identifier strings * </p> * * <p> * This property is not required. If not the set the framework will use a property contained on * <code>UifFormBase</code> * </p> * * @return String property name for select field */ public String getLineSelectPropertyName() { return lineSelectPropertyName; } /** * Setter for the property name that will bind to the select field * * @param lineSelectPropertyName */ public void setLineSelectPropertyName(String lineSelectPropertyName) { this.lineSelectPropertyName = lineSelectPropertyName; } /** * Instance of the <code>QuickFinder</code> widget that configures a multi-value lookup for the collection * * <p> * If the collection lookup is enabled (by the render property of the quick finder), {@link * #getCollectionObjectClass()} will be used as the data object class for the lookup (if not set). Field * conversions need to be set as usual and will be applied for each line returned * </p> * * @return QuickFinder instance configured for the collection lookup */ public QuickFinder getCollectionLookup() { return collectionLookup; } /** * Setter for the collection lookup quickfinder instance * * @param collectionLookup */ public void setCollectionLookup(QuickFinder collectionLookup) { this.collectionLookup = collectionLookup; } /** * Indicates whether inactive collections lines should be displayed * * <p> * Setting only applies when the collection line type implements the * <code>Inactivatable</code> interface. If true and showInactive is * set to false, the collection will be filtered to remove any items * whose active status returns false * </p> * * @return boolean true to show inactive records, false to not render inactive records */ public boolean isShowInactiveLines() { return showInactiveLines; } /** * Setter for the show inactive indicator * * @param showInactiveLines boolean show inactive */ public void setShowInactiveLines(boolean showInactiveLines) { this.showInactiveLines = showInactiveLines; } /** * Collection filter instance for filtering the collection data when the * showInactive flag is set to false * * @return CollectionFilter */ public CollectionFilter getActiveCollectionFilter() { return activeCollectionFilter; } /** * Setter for the collection filter to use for filter inactive records from the * collection * * @param activeCollectionFilter - CollectionFilter instance */ public void setActiveCollectionFilter(CollectionFilter activeCollectionFilter) { this.activeCollectionFilter = activeCollectionFilter; } /** * List of {@link CollectionFilter} instances that should be invoked to filter the collection before * displaying * * @return List<CollectionFilter> */ public List<CollectionFilter> getFilters() { return filters; } /** * Setter for the List of collection filters for which the collection will be filtered against * * @param filters */ public void setFilters(List<CollectionFilter> filters) { this.filters = filters; } /** * List of <code>CollectionGroup</code> instances that are sub-collections * of the collection represented by this collection group * * @return List<CollectionGroup> sub collections */ public List<CollectionGroup> getSubCollections() { return this.subCollections; } /** * Setter for the sub collection list * * @param subCollections */ public void setSubCollections(List<CollectionGroup> subCollections) { this.subCollections = subCollections; } /** * Suffix for IDs that identifies the collection line the sub-collection belongs to * * <p> * Built by the framework as the collection lines are being generated * </p> * * @return String id suffix for sub-collection */ public String getSubCollectionSuffix() { return subCollectionSuffix; } /** * Setter for the sub-collection suffix (used by framework, should not be * set in configuration) * * @param subCollectionSuffix */ public void setSubCollectionSuffix(String subCollectionSuffix) { this.subCollectionSuffix = subCollectionSuffix; } /** * Collection Security object that indicates what authorization (permissions) exist for the collection * * @return CollectionGroupSecurity instance */ @Override public CollectionGroupSecurity getComponentSecurity() { return (CollectionGroupSecurity) super.getComponentSecurity(); } /** * Override to assert a {@link CollectionGroupSecurity} instance is set * * @param componentSecurity - instance of CollectionGroupSecurity */ @Override public void setComponentSecurity(ComponentSecurity componentSecurity) { if (!(componentSecurity instanceof CollectionGroupSecurity)) { throw new RiceRuntimeException( "Component security for CollectionGroup should be instance of CollectionGroupSecurity"); } super.setComponentSecurity(componentSecurity); } @Override protected Class<? extends ComponentSecurity> getComponentSecurityClass() { return CollectionGroupSecurity.class; } /** * <code>CollectionGroupBuilder</code> instance that will build the * components dynamically for the collection instance * * @return CollectionGroupBuilder instance */ public CollectionGroupBuilder getCollectionGroupBuilder() { if (this.collectionGroupBuilder == null) { this.collectionGroupBuilder = new CollectionGroupBuilder(); } return this.collectionGroupBuilder; } /** * Setter for the collection group building instance * * @param collectionGroupBuilder */ public void setCollectionGroupBuilder(CollectionGroupBuilder collectionGroupBuilder) { this.collectionGroupBuilder = collectionGroupBuilder; } /** * @param renderInactiveToggleButton the showHideInactiveButton to set */ public void setRenderInactiveToggleButton(boolean renderInactiveToggleButton) { this.renderInactiveToggleButton = renderInactiveToggleButton; } /** * @return the showHideInactiveButton */ public boolean isRenderInactiveToggleButton() { return renderInactiveToggleButton; } /** * The number of records to display for a collection * * @return int */ public int getDisplayCollectionSize() { return this.displayCollectionSize; } /** * Setter for the display collection size * * @param displayCollectionSize */ public void setDisplayCollectionSize(int displayCollectionSize) { this.displayCollectionSize = displayCollectionSize; } /** * Indicates whether new items should be styled with the #newItemsCssClass * * @return boolean true if new items must be highlighted */ public boolean isHighlightNewItems() { return highlightNewItems; } /** * Setter for the flag that allows for different styling of new items * * @param highlightNewItems */ public void setHighlightNewItems(boolean highlightNewItems) { this.highlightNewItems = highlightNewItems; } /** * The css style class that will be added on new items * * @return String - the new items css style class */ public String getNewItemsCssClass() { return newItemsCssClass; } /** * Setter for the new items css style class * * @param newItemsCssClass */ public void setNewItemsCssClass(String newItemsCssClass) { this.newItemsCssClass = newItemsCssClass; } /** * The css style class that will be added on the add item group or row * * @return String - the add item group or row css style class */ public String getAddItemCssClass() { return addItemCssClass; } /** * Setter for the add item css style class * * @param addItemCssClass */ public void setAddItemCssClass(String addItemCssClass) { this.addItemCssClass = addItemCssClass; } /** * Indicates whether the add item group or row should be styled with the #addItemCssClass * * @return boolean true if add item group or row must be highlighted */ public boolean isHighlightAddItem() { return highlightAddItem; } /** * Setter for the flag that allows for different styling of the add item group or row * * @param highlightAddItem */ public void setHighlightAddItem(boolean highlightAddItem) { this.highlightAddItem = highlightAddItem; } /** * Indicates that a button will be rendered that allows the user to add blank lines to the collection * * <p> * The button will be added separately from the collection items. The default add line wil not be rendered. The * action of the button will call the controller, add the blank line to the collection and do a component refresh. * </p> * * @return boolean */ public boolean isRenderAddBlankLineButton() { return renderAddBlankLineButton; } /** * Setter for the flag indicating that the add blank line button must be rendered * * @param renderAddBlankLineButton */ public void setRenderAddBlankLineButton(boolean renderAddBlankLineButton) { this.renderAddBlankLineButton = renderAddBlankLineButton; } /** * The add blank line {@link Action} field rendered when renderAddBlankLineButton is true * * @return boolean */ public Action getAddBlankLineAction() { return addBlankLineAction; } /** * Setter for the add blank line {@link Action} field * * @param addBlankLineAction */ public void setAddBlankLineAction(Action addBlankLineAction) { this.addBlankLineAction = addBlankLineAction; } /** * Indicates the add line placement * * <p> * Valid values are 'TOP' or 'BOTTOM'. The default is 'TOP'. When the value is 'BOTTOM' the blank line will be * added * to the end of the collection. * </p> * * @return String - the add blank line action placement */ public String getAddLinePlacement() { return addLinePlacement; } /** * Setter for the add line placement * * @param addLinePlacement - add line placement string */ public void setAddLinePlacement(String addLinePlacement) { this.addLinePlacement = addLinePlacement; } /** * Indicates whether the save line actions should be rendered * * @return boolean */ public boolean isRenderSaveLineActions() { return renderSaveLineActions; } /** * Setter for the flag indicating whether the save actions should be rendered * * @param renderSaveLineActions */ public void setRenderSaveLineActions(boolean renderSaveLineActions) { this.renderSaveLineActions = renderSaveLineActions; } /** * Indicates that a add action should be rendered and that the add group be displayed in a lightbox * * @return boolean */ public boolean isAddViaLightBox() { return addViaLightBox; } /** * Setter for the flag to indicate that add groups should be displayed in a light box * * @param addViaLightBox */ public void setAddViaLightBox(boolean addViaLightBox) { this.addViaLightBox = addViaLightBox; } /** * The {@link Action} that will be displayed that will open the add line group in a lightbox * * @return Action */ public Action getAddViaLightBoxAction() { return addViaLightBoxAction; } /** * Setter for the add line via lightbox {@link Action} * * @param addViaLightBoxAction */ public void setAddViaLightBoxAction(Action addViaLightBoxAction) { this.addViaLightBoxAction = addViaLightBoxAction; } }
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/CollectionGroup.java
/** * Copyright 2005-2012 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.uif.container; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.exception.RiceRuntimeException; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifParameters; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.component.ComponentSecurity; import org.kuali.rice.krad.uif.component.DataBinding; import org.kuali.rice.krad.uif.element.Action; import org.kuali.rice.krad.uif.element.Label; import org.kuali.rice.krad.uif.field.DataField; import org.kuali.rice.krad.uif.field.Field; import org.kuali.rice.krad.uif.util.ComponentUtils; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.uif.widget.QuickFinder; import java.util.ArrayList; import java.util.List; /** * Group that holds a collection of objects and configuration for presenting the * collection in the UI. Supports functionality such as add line, line actions, * and nested collections. * * <p> * Note the standard header/footer can be used to give a header to the * collection as a whole, or to provide actions that apply to the entire * collection * </p> * * <p> * For binding purposes the binding path of each row field is indexed. The name * property inherited from <code>ComponentBase</code> is used as the collection * name. The collectionObjectClass property is used to lookup attributes from * the data dictionary. * </p> * * @author Kuali Rice Team ([email protected]) */ public class CollectionGroup extends Group implements DataBinding { private static final long serialVersionUID = -6496712566071542452L; private Class<?> collectionObjectClass; private String propertyName; private BindingInfo bindingInfo; private boolean renderAddLine; private String addLinePropertyName; private BindingInfo addLineBindingInfo; private Label addLineLabel; private List<? extends Component> addLineItems; private List<Action> addLineActions; private boolean renderLineActions; private List<Action> lineActions; private boolean includeLineSelectionField; private String lineSelectPropertyName; private QuickFinder collectionLookup; private boolean renderInactiveToggleButton; private boolean showInactiveLines; private CollectionFilter activeCollectionFilter; private List<CollectionFilter> filters; private List<CollectionGroup> subCollections; private String subCollectionSuffix; private CollectionGroupBuilder collectionGroupBuilder; private int displayCollectionSize = -1; private boolean highlightNewItems; private boolean highlightAddItem; private String newItemsCssClass; private String addItemCssClass; private boolean renderAddBlankLineButton; private Action addBlankLineAction; private String addLinePlacement; private boolean renderSaveLineActions; private boolean addViaLightBox; private Action addViaLightBoxAction; private List<String> totalColumns; public CollectionGroup() { renderAddLine = true; renderLineActions = true; renderSaveLineActions = false; showInactiveLines = false; renderInactiveToggleButton = true; includeLineSelectionField = false; highlightNewItems = true; addLinePlacement = "TOP"; filters = new ArrayList<CollectionFilter>(); lineActions = new ArrayList<Action>(); addLineItems = new ArrayList<Field>(); addLineActions = new ArrayList<Action>(); subCollections = new ArrayList<CollectionGroup>(); } /** * The following actions are performed: * * <ul> * <li>Set fieldBindModelPath to the collection model path (since the fields * have to belong to the same model as the collection)</li> * <li>Set defaults for binding</li> * <li>Default add line field list to groups items list</li> * <li>Sets default active collection filter if not set</li> * <li>Sets the dictionary entry (if blank) on each of the items to the * collection class</li> * </ul> * * @see org.kuali.rice.krad.uif.component.ComponentBase#performInitialization(org.kuali.rice.krad.uif.view.View, * java.lang.Object) */ @Override public void performInitialization(View view, Object model) { setFieldBindingObjectPath(getBindingInfo().getBindingObjectPath()); super.performInitialization(view, model); if (bindingInfo != null) { bindingInfo.setDefaults(view, getPropertyName()); } if (addLineBindingInfo != null) { // add line binds to model property if (StringUtils.isNotBlank(addLinePropertyName)) { addLineBindingInfo.setDefaults(view, getPropertyName()); addLineBindingInfo.setBindingName(addLinePropertyName); if (StringUtils.isNotBlank(getFieldBindByNamePrefix())) { addLineBindingInfo.setBindByNamePrefix(getFieldBindByNamePrefix()); } } } for (Component item : getItems()) { if (item instanceof DataField) { DataField field = (DataField) item; if (StringUtils.isBlank(field.getDictionaryObjectEntry())) { field.setDictionaryObjectEntry(collectionObjectClass.getName()); } } } for (Component addLineField : addLineItems) { if (addLineField instanceof DataField) { DataField field = (DataField) addLineField; if (StringUtils.isBlank(field.getDictionaryObjectEntry())) { field.setDictionaryObjectEntry(collectionObjectClass.getName()); } } } if ((addLineItems == null) || addLineItems.isEmpty()) { addLineItems = getItems(); } // if active collection filter not set use default if (this.activeCollectionFilter == null) { activeCollectionFilter = new ActiveCollectionFilter(); } // set static collection path on items String collectionPath = ""; if (StringUtils.isNotBlank(getBindingInfo().getCollectionPath())) { collectionPath += getBindingInfo().getCollectionPath() + "."; } if (StringUtils.isNotBlank(getBindingInfo().getBindByNamePrefix())) { collectionPath += getBindingInfo().getBindByNamePrefix() + "."; } collectionPath += getBindingInfo().getBindingName(); List<DataField> collectionFields = ComponentUtils.getComponentsOfTypeDeep(getItems(), DataField.class); for (DataField collectionField : collectionFields) { collectionField.getBindingInfo().setCollectionPath(collectionPath); } List<DataField> addLineCollectionFields = ComponentUtils.getComponentsOfTypeDeep(addLineItems, DataField.class); for (DataField collectionField : addLineCollectionFields) { collectionField.getBindingInfo().setCollectionPath(collectionPath); } for (CollectionGroup collectionGroup : getSubCollections()) { collectionGroup.getBindingInfo().setCollectionPath(collectionPath); } // add collection entry to abstract classes if (!view.getObjectPathToConcreteClassMapping().containsKey(collectionPath)) { view.getObjectPathToConcreteClassMapping().put(collectionPath, getCollectionObjectClass()); } } /** * Calls the configured <code>CollectionGroupBuilder</code> to build the * necessary components based on the collection data * * @see org.kuali.rice.krad.uif.container.ContainerBase#performApplyModel(org.kuali.rice.krad.uif.view.View, * java.lang.Object, org.kuali.rice.krad.uif.component.Component) */ @Override public void performApplyModel(View view, Object model, Component parent) { super.performApplyModel(view, model, parent); pushCollectionGroupToReference(); // if rendering the collection group, build out the lines if (isRender()) { getCollectionGroupBuilder().build(view, model, this); } // TODO: is this necessary to call again? // This may be necessary to call in case getCollectionGroupBuilder().build resets the context map pushCollectionGroupToReference(); } /** * Sets a reference in the context map for all nested components to the collection group * instance, and sets name as parameter for an action fields in the group */ protected void pushCollectionGroupToReference() { List<Component> components = getComponentsForLifecycle(); components.addAll(getComponentPrototypes()); ComponentUtils.pushObjectToContext(components, UifConstants.ContextVariableNames.COLLECTION_GROUP, this); List<Action> actions = ComponentUtils.getComponentsOfTypeDeep(components, Action.class); for (Action action : actions) { action.addActionParameter(UifParameters.SELLECTED_COLLECTION_PATH, this.getBindingInfo().getBindingPath()); } } /** * New collection lines are handled in the framework by maintaining a map on * the form. The map contains as a key the collection name, and as value an * instance of the collection type. An entry is created here for the * collection represented by the <code>CollectionGroup</code> if an instance * is not available (clearExistingLine will force a new instance). The given * model must be a subclass of <code>UifFormBase</code> in order to find the * Map. * * @param model - Model instance that contains the new collection lines Map * @param clearExistingLine - boolean that indicates whether the line should be set to a * new instance if it already exists */ public void initializeNewCollectionLine(View view, Object model, CollectionGroup collectionGroup, boolean clearExistingLine) { getCollectionGroupBuilder().initializeNewCollectionLine(view, model, collectionGroup, clearExistingLine); } /** * @see org.kuali.rice.krad.uif.container.ContainerBase#getComponentsForLifecycle() */ @Override public List<Component> getComponentsForLifecycle() { List<Component> components = super.getComponentsForLifecycle(); components.add(addLineLabel); components.add(collectionLookup); components.add(addBlankLineAction); components.add(addViaLightBoxAction); // remove the containers items because we don't want them as children // (they will become children of the layout manager as the rows are created) for (Component item : getItems()) { if (components.contains(item)) { components.remove(item); } } return components; } /** * @see org.kuali.rice.krad.uif.component.Component#getComponentPrototypes() */ @Override public List<Component> getComponentPrototypes() { List<Component> components = super.getComponentPrototypes(); components.addAll(lineActions); components.addAll(addLineActions); components.addAll(getItems()); components.addAll(getSubCollections()); components.addAll(addLineItems); return components; } /** * Object class the collection maintains. Used to get dictionary information * in addition to creating new instances for the collection when necessary * * @return Class<?> collection object class */ public Class<?> getCollectionObjectClass() { return this.collectionObjectClass; } /** * Setter for the collection object class * * @param collectionObjectClass */ public void setCollectionObjectClass(Class<?> collectionObjectClass) { this.collectionObjectClass = collectionObjectClass; } /** * @see org.kuali.rice.krad.uif.component.DataBinding#getPropertyName() */ public String getPropertyName() { return this.propertyName; } /** * Setter for the collections property name * * @param propertyName */ public void setPropertyName(String propertyName) { this.propertyName = propertyName; } /** * Determines the binding path for the collection. Used to get the * collection value from the model in addition to setting the binding path * for the collection attributes * * @see org.kuali.rice.krad.uif.component.DataBinding#getBindingInfo() */ public BindingInfo getBindingInfo() { return this.bindingInfo; } /** * Setter for the binding info instance * * @param bindingInfo */ public void setBindingInfo(BindingInfo bindingInfo) { this.bindingInfo = bindingInfo; } /** * Action fields that should be rendered for each collection line. Example * line action is the delete action * * @return List<Action> line action fields */ public List<Action> getLineActions() { return this.lineActions; } /** * Setter for the line action fields list * * @param lineActions */ public void setLineActions(List<Action> lineActions) { this.lineActions = lineActions; } /** * Indicates whether the action column for the collection should be rendered * * @return boolean true if the actions should be rendered, false if not * @see #getLineActions() */ public boolean isRenderLineActions() { return this.renderLineActions; } /** * Setter for the render line actions indicator * * @param renderLineActions */ public void setRenderLineActions(boolean renderLineActions) { this.renderLineActions = renderLineActions; } /** * Indicates whether an add line should be rendered for the collection * * @return boolean true if add line should be rendered, false if it should * not be */ public boolean isRenderAddLine() { return this.renderAddLine; } /** * Setter for the render add line indicator * * @param renderAddLine */ public void setRenderAddLine(boolean renderAddLine) { this.renderAddLine = renderAddLine; } /** * Convenience getter for the add line label field text. The text is used to * label the add line when rendered and its placement depends on the * <code>LayoutManager</code> * * <p> * For the <code>TableLayoutManager</code> the label appears in the sequence * column to the left of the add line fields. For the * <code>StackedLayoutManager</code> the label is placed into the group * header for the line. * </p> * * @return String add line label */ public String getAddLabel() { if (getAddLineLabel() != null) { return getAddLineLabel().getLabelText(); } return null; } /** * Setter for the add line label text * * @param addLabelText */ public void setAddLabel(String addLabelText) { if (getAddLineLabel() != null) { getAddLineLabel().setLabelText(addLabelText); } } /** * <code>Label</code> instance for the add line label * * @return Label add line label field * @see #getAddLabel */ public Label getAddLineLabel() { return this.addLineLabel; } /** * Setter for the <code>Label</code> instance for the add line label * * @param addLineLabel * @see #getAddLabel */ public void setAddLineLabel(Label addLineLabel) { this.addLineLabel = addLineLabel; } /** * Name of the property that contains an instance for the add line. If set * this is used with the binding info to create the path to the add line. * Can be left blank in which case the framework will manage the add line * instance in a generic map. * * @return String add line property name */ public String getAddLinePropertyName() { return this.addLinePropertyName; } /** * Setter for the add line property name * * @param addLinePropertyName */ public void setAddLinePropertyName(String addLinePropertyName) { this.addLinePropertyName = addLinePropertyName; } /** * <code>BindingInfo</code> instance for the add line property used to * determine the full binding path. If add line name given * {@link #getAddLabel} then it is set as the binding name on the * binding info. Add line label and binding info are not required, in which * case the framework will manage the new add line instances through a * generic map (model must extend UifFormBase) * * @return BindingInfo add line binding info */ public BindingInfo getAddLineBindingInfo() { return this.addLineBindingInfo; } /** * Setter for the add line binding info * * @param addLineBindingInfo */ public void setAddLineBindingInfo(BindingInfo addLineBindingInfo) { this.addLineBindingInfo = addLineBindingInfo; } /** * List of <code>Component</code> instances that should be rendered for the * collection add line (if enabled). If not set, the default group's items * list will be used * * @return List<? extends Component> add line field list * @see CollectionGroup#performInitialization(org.kuali.rice.krad.uif.view.View, java.lang.Object) */ public List<? extends Component> getAddLineItems() { return this.addLineItems; } /** * Setter for the add line field list * * @param addLineItems */ public void setAddLineItems(List<? extends Component> addLineItems) { this.addLineItems = addLineItems; } /** * Action fields that should be rendered for the add line. This is generally * the add action (button) but can be configured to contain additional * actions * * @return List<Action> add line action fields */ public List<Action> getAddLineActions() { return this.addLineActions; } /** * Setter for the add line action fields * * @param addLineActions */ public void setAddLineActions(List<Action> addLineActions) { this.addLineActions = addLineActions; } /** * Indicates whether lines of the collection group should be selected by rendering a * field for each line that will allow selection * * <p> * For example, having the select field enabled could allow selecting multiple lines from a search * to return (multi-value lookup) * </p> * * @return boolean true if select field should be rendered, false if not */ public boolean isIncludeLineSelectionField() { return includeLineSelectionField; } /** * Setter for the render selected field indicator * * @param includeLineSelectionField */ public void setIncludeLineSelectionField(boolean includeLineSelectionField) { this.includeLineSelectionField = includeLineSelectionField; } /** * When {@link #isIncludeLineSelectionField()} is true, gives the name of the property the select field * should bind to * * <p> * Note if no prefix is given in the property name, such as 'form.', it is assumed the property is * contained on the collection line. In this case the binding path to the collection line will be * appended. In other cases, it is assumed the property is a list or set of String that will hold the * selected identifier strings * </p> * * <p> * This property is not required. If not the set the framework will use a property contained on * <code>UifFormBase</code> * </p> * * @return String property name for select field */ public String getLineSelectPropertyName() { return lineSelectPropertyName; } /** * Setter for the property name that will bind to the select field * * @param lineSelectPropertyName */ public void setLineSelectPropertyName(String lineSelectPropertyName) { this.lineSelectPropertyName = lineSelectPropertyName; } /** * Instance of the <code>QuickFinder</code> widget that configures a multi-value lookup for the collection * * <p> * If the collection lookup is enabled (by the render property of the quick finder), {@link * #getCollectionObjectClass()} will be used as the data object class for the lookup (if not set). Field * conversions need to be set as usual and will be applied for each line returned * </p> * * @return QuickFinder instance configured for the collection lookup */ public QuickFinder getCollectionLookup() { return collectionLookup; } /** * Setter for the collection lookup quickfinder instance * * @param collectionLookup */ public void setCollectionLookup(QuickFinder collectionLookup) { this.collectionLookup = collectionLookup; } /** * Indicates whether inactive collections lines should be displayed * * <p> * Setting only applies when the collection line type implements the * <code>Inactivatable</code> interface. If true and showInactive is * set to false, the collection will be filtered to remove any items * whose active status returns false * </p> * * @return boolean true to show inactive records, false to not render inactive records */ public boolean isShowInactiveLines() { return showInactiveLines; } /** * Setter for the show inactive indicator * * @param showInactiveLines boolean show inactive */ public void setShowInactiveLines(boolean showInactiveLines) { this.showInactiveLines = showInactiveLines; } /** * Collection filter instance for filtering the collection data when the * showInactive flag is set to false * * @return CollectionFilter */ public CollectionFilter getActiveCollectionFilter() { return activeCollectionFilter; } /** * Setter for the collection filter to use for filter inactive records from the * collection * * @param activeCollectionFilter - CollectionFilter instance */ public void setActiveCollectionFilter(CollectionFilter activeCollectionFilter) { this.activeCollectionFilter = activeCollectionFilter; } /** * List of {@link CollectionFilter} instances that should be invoked to filter the collection before * displaying * * @return List<CollectionFilter> */ public List<CollectionFilter> getFilters() { return filters; } /** * Setter for the List of collection filters for which the collection will be filtered against * * @param filters */ public void setFilters(List<CollectionFilter> filters) { this.filters = filters; } /** * List of <code>CollectionGroup</code> instances that are sub-collections * of the collection represented by this collection group * * @return List<CollectionGroup> sub collections */ public List<CollectionGroup> getSubCollections() { return this.subCollections; } /** * Setter for the sub collection list * * @param subCollections */ public void setSubCollections(List<CollectionGroup> subCollections) { this.subCollections = subCollections; } /** * Suffix for IDs that identifies the collection line the sub-collection belongs to * * <p> * Built by the framework as the collection lines are being generated * </p> * * @return String id suffix for sub-collection */ public String getSubCollectionSuffix() { return subCollectionSuffix; } /** * Setter for the sub-collection suffix (used by framework, should not be * set in configuration) * * @param subCollectionSuffix */ public void setSubCollectionSuffix(String subCollectionSuffix) { this.subCollectionSuffix = subCollectionSuffix; } /** * Collection Security object that indicates what authorization (permissions) exist for the collection * * @return CollectionGroupSecurity instance */ @Override public CollectionGroupSecurity getComponentSecurity() { return (CollectionGroupSecurity) super.getComponentSecurity(); } /** * Override to assert a {@link CollectionGroupSecurity} instance is set * * @param componentSecurity - instance of CollectionGroupSecurity */ @Override public void setComponentSecurity(ComponentSecurity componentSecurity) { if (!(componentSecurity instanceof CollectionGroupSecurity)) { throw new RiceRuntimeException( "Component security for CollectionGroup should be instance of CollectionGroupSecurity"); } super.setComponentSecurity(componentSecurity); } @Override protected Class<? extends ComponentSecurity> getComponentSecurityClass() { return CollectionGroupSecurity.class; } /** * <code>CollectionGroupBuilder</code> instance that will build the * components dynamically for the collection instance * * @return CollectionGroupBuilder instance */ public CollectionGroupBuilder getCollectionGroupBuilder() { if (this.collectionGroupBuilder == null) { this.collectionGroupBuilder = new CollectionGroupBuilder(); } return this.collectionGroupBuilder; } /** * Setter for the collection group building instance * * @param collectionGroupBuilder */ public void setCollectionGroupBuilder(CollectionGroupBuilder collectionGroupBuilder) { this.collectionGroupBuilder = collectionGroupBuilder; } /** * @param renderInactiveToggleButton the showHideInactiveButton to set */ public void setRenderInactiveToggleButton(boolean renderInactiveToggleButton) { this.renderInactiveToggleButton = renderInactiveToggleButton; } /** * @return the showHideInactiveButton */ public boolean isRenderInactiveToggleButton() { return renderInactiveToggleButton; } /** * The number of records to display for a collection * * @return int */ public int getDisplayCollectionSize() { return this.displayCollectionSize; } /** * Setter for the display collection size * * @param displayCollectionSize */ public void setDisplayCollectionSize(int displayCollectionSize) { this.displayCollectionSize = displayCollectionSize; } /** * Indicates whether new items should be styled with the #newItemsCssClass * * @return boolean true if new items must be highlighted */ public boolean isHighlightNewItems() { return highlightNewItems; } /** * Setter for the flag that allows for different styling of new items * * @param highlightNewItems */ public void setHighlightNewItems(boolean highlightNewItems) { this.highlightNewItems = highlightNewItems; } /** * The css style class that will be added on new items * * @return String - the new items css style class */ public String getNewItemsCssClass() { return newItemsCssClass; } /** * Setter for the new items css style class * * @param newItemsCssClass */ public void setNewItemsCssClass(String newItemsCssClass) { this.newItemsCssClass = newItemsCssClass; } /** * The css style class that will be added on the add item group or row * * @return String - the add item group or row css style class */ public String getAddItemCssClass() { return addItemCssClass; } /** * Setter for the add item css style class * * @param addItemCssClass */ public void setAddItemCssClass(String addItemCssClass) { this.addItemCssClass = addItemCssClass; } /** * Indicates whether the add item group or row should be styled with the #addItemCssClass * * @return boolean true if add item group or row must be highlighted */ public boolean isHighlightAddItem() { return highlightAddItem; } /** * Setter for the flag that allows for different styling of the add item group or row * * @param highlightAddItem */ public void setHighlightAddItem(boolean highlightAddItem) { this.highlightAddItem = highlightAddItem; } /** * Indicates that a button will be rendered that allows the user to add blank lines to the collection * * <p> * The button will be added separately from the collection items. The default add line wil not be rendered. The * action of the button will call the controller, add the blank line to the collection and do a component refresh. * </p> * * @return boolean */ public boolean isRenderAddBlankLineButton() { return renderAddBlankLineButton; } /** * Setter for the flag indicating that the add blank line button must be rendered * * @param renderAddBlankLineButton */ public void setRenderAddBlankLineButton(boolean renderAddBlankLineButton) { this.renderAddBlankLineButton = renderAddBlankLineButton; } /** * The add blank line {@link Action} field rendered when renderAddBlankLineButton is true * * @return boolean */ public Action getAddBlankLineAction() { return addBlankLineAction; } /** * Setter for the add blank line {@link Action} field * * @param addBlankLineAction */ public void setAddBlankLineAction(Action addBlankLineAction) { this.addBlankLineAction = addBlankLineAction; } /** * Indicates the add line placement * * <p> * Valid values are 'TOP' or 'BOTTOM'. The default is 'TOP'. When the value is 'BOTTOM' the blank line will be * added * to the end of the collection. * </p> * * @return String - the add blank line action placement */ public String getAddLinePlacement() { return addLinePlacement; } /** * Setter for the add line placement * * @param addLinePlacement - add line placement string */ public void setAddLinePlacement(String addLinePlacement) { this.addLinePlacement = addLinePlacement; } /** * Indicates whether the save line actions should be rendered * * @return boolean */ public boolean isRenderSaveLineActions() { return renderSaveLineActions; } /** * Setter for the flag indicating whether the save actions should be rendered * * @param renderSaveLineActions */ public void setRenderSaveLineActions(boolean renderSaveLineActions) { this.renderSaveLineActions = renderSaveLineActions; } /** * Indicates that a add action should be rendered and that the add group be displayed in a lightbox * * @return boolean */ public boolean isAddViaLightBox() { return addViaLightBox; } /** * Setter for the flag to indicate that add groups should be displayed in a light box * * @param addViaLightBox */ public void setAddViaLightBox(boolean addViaLightBox) { this.addViaLightBox = addViaLightBox; } /** * The {@link Action} that will be displayed that will open the add line group in a lightbox * * @return Action */ public Action getAddViaLightBoxAction() { return addViaLightBoxAction; } /** * Setter for the add line via lightbox {@link Action} * * @param addViaLightBoxAction */ public void setAddViaLightBoxAction(Action addViaLightBoxAction) { this.addViaLightBoxAction = addViaLightBoxAction; } }
KULRICE-7888 - collection items getting added to lifecycle twice causing dup styles
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/container/CollectionGroup.java
KULRICE-7888 - collection items getting added to lifecycle twice causing dup styles
Java
apache-2.0
79f698a7463fc1193a49cd944d8dc6ea556cc7d7
0
rzel/xruby,rzel/xruby,weimingtom/xruby,weimingtom/xruby,weimingtom/xruby,rzel/xruby
/** * Copyright 2005-2007 Xue Yong Zhi, Ye Zheng * Distributed under the GNU General Public License 2.0 */ package com.xruby.runtime.value; import java.util.*; import com.xruby.runtime.lang.*; /** * @breif Internal representation of a ruby array * */ public class RubyArray extends RubyBasic implements Iterable<RubyValue> { private ArrayList<RubyValue> array_; private boolean is_not_single_asterisk_; //e.g. does not look like yield *[[]] public RubyArray() { this(1, true); } public RubyArray(int size) { this(size, true); } public RubyArray(RubyValue v) { this(1, true); add(v); } public RubyArray(RubyValue value1, RubyValue value2) { this(2, true); add(value1); add(value2); } public RubyArray(int size, RubyValue default_value) { this(size, true); for (int i = 0; i < size; ++i) { array_.add(default_value); } } public RubyArray(int size, boolean isNotSingleAsterisk) { super(RubyRuntime.ArrayClass); array_ = new ArrayList<RubyValue>(size); this.is_not_single_asterisk_ = isNotSingleAsterisk; } @SuppressWarnings("unchecked") public RubyArray clone() { RubyArray v = (RubyArray)super.clone(); v.array_ = (ArrayList<RubyValue>)array_.clone(); return v; } public boolean isNotSingleAsterisk() { return this.is_not_single_asterisk_; } public RubyArray add(RubyValue v) { array_.add(v); return this; } public RubyArray insert(int index, RubyValue v) { array_.add(index, v); return this; } public RubyValue remove(int index) { if (index < 0 || index > size()) { return ObjectFactory.nilValue; } return array_.remove(index); } public int size() { return array_.size(); } public RubyValue delete(RubyValue arg) { boolean found = false; while (array_.remove(arg)) { found = true; } return found ? arg : ObjectFactory.nilValue; } public Iterator<RubyValue> iterator() { return array_.iterator(); } private int getRealIndex(int i) { int index = i; if (index < 0) { index = array_.size() + index; } if (index < 0) { throw new RubyException(RubyRuntime.IndexErrorClass, "index " + i + " out of array"); } return index; } public RubyValue set(int start, RubyValue value) { int index = getRealIndex(start); if (index < array_.size()) { array_.set(index, value); } else { array_.ensureCapacity(index + 1); for (int i = array_.size(); i < index; ++i) { array_.add(ObjectFactory.nilValue); } array_.add(value); } return value; } public RubyValue replace(int start, int length, RubyValue value) { int index = getRealIndex(start); if (length < 0) { throw new RubyException(RubyRuntime.IndexErrorClass, "negative length ("+ length + ")"); } else if (0 == length) { if (value instanceof RubyArray) { array_.addAll(index, ((RubyArray)value).getInternal()); } else { array_.add(index, value); } } else { for (int i = 0; i < length - 1; ++i) { array_.remove(index); } //TODO should we use addAll if value is RubyArray? array_.set(index, value); } return value; } public RubyValue get(int index) { if (index < 0) { index = array_.size() + index; } if (index < 0 || index >= size()) { return ObjectFactory.nilValue; } else { return array_.get(index); } } public RubyArray copy() { RubyArray resultArray = new RubyArray(array_.size()); for (RubyValue v : array_) { resultArray.add(v); } return resultArray; } public RubyValue compare(RubyArray other_array) { int length = (size() <= other_array.size()) ? size() : other_array.size(); for (int i = 0; i < length; ++i) { RubyValue v = RubyAPI.callPublicOneArgMethod(get(i), other_array.get(i), null, "<=>"); if (!RubyAPI.testEqual(v, ObjectFactory.fixnum0)) { return v; } } if (size() == other_array.size()) { return ObjectFactory.fixnum0; } else if (size() > other_array.size()) { return ObjectFactory.fixnum1; } else { return ObjectFactory.createFixnum(-1); } } public RubyArray subarray(int begin, int length) { final int arraySize = array_.size(); if (begin > arraySize) { return null; } if (length < 0) { return null; } if (begin < 0) { begin += arraySize; } if (begin + length > arraySize) { length = arraySize - begin; if (length < 0) { length = 0; } } if (length == 0) { return new RubyArray(0); } RubyArray resultArray = new RubyArray(length); int last = begin + length; for (int i = begin; i < last; i++) { resultArray.add(array_.get(i)); } return resultArray; } public boolean equals(RubyArray that) { if (array_.size() != that.size()) { return false; } for (int i = 0; i < array_.size(); ++i) { if (!RubyAPI.testEqual(this.get(i), that.get(i))) { return false; } } return true; } public RubyValue to_s() { RubyString r = ObjectFactory.createString(); for (RubyValue v : array_) { r.appendString(v); // TODO: The output of to_s is not as the same as cruby, we should solve this issue // TODO: and change the corresponding testcases in RubyCompilerTest, such as test_array_expand. } return r; } ArrayList<RubyValue> getInternal() { return array_; } public void concat(RubyValue v) { if (!(v instanceof RubyArray)) { throw new RubyException(RubyRuntime.TypeErrorClass, "can't convert " + v.getRubyClass().toString() + " into Array"); } array_.addAll(((RubyArray)v).getInternal()); } public RubyArray plus(RubyArray v) { int size = array_.size() + v.size(); RubyArray resultArray = new RubyArray(size); resultArray.array_.addAll(array_); resultArray.array_.addAll(v.array_); return resultArray; } private boolean remove(RubyValue v) { boolean r = false; while (array_.remove(v)) { r = true; } return r; } public RubyArray minus(RubyArray other) { RubyArray a = this.copy(); for (RubyValue v : other) { a.remove(v); } return a; } public RubyArray times(int times) { if (times < 0) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "negative argument"); } int size = array_.size() * times; RubyArray resultArray = new RubyArray(size); for (int i = 0; i < times; i++) { resultArray.array_.addAll(array_); } return resultArray; } /// Returns true if the given object is present public boolean include(RubyValue v) { for (RubyValue value : array_) { if (RubyAPI.testEqual(value, v)) { return true; } } return false; } public void rb_iterate(RubyValue receiver, RubyBlock block) { for(RubyValue item: array_) { RubyArray args = new RubyArray(); args.add(item); block.invoke(receiver, args); } } public RubyArray expand(RubyValue v) { if (v instanceof RubyArray) { //[5,6,*[1, 2]] array_.addAll(((RubyArray)v).getInternal()); } else { //[5,6,*1], [5,6,*nil] array_.add(v); } return this; } //create a new Array containing every element from index to the end public RubyValue collect(int index) { assert(index >= 0); final int size = array_.size() - index; if (size < 0) { return new RubyArray(); } RubyArray a = new RubyArray(size, true); for (int i = index; i < array_.size(); ++i) { a.add(array_.get(i)); } return a; } public RubyArray unshift(RubyValue value){ array_.add(0, value); return this; } public RubyArray unshift(RubyArray value){ array_.addAll(0, value.getInternal()); return this; } public void sort() { Collections.sort(array_, new Comparator<RubyValue>() { public int compare(RubyValue arg0, RubyValue arg1) { RubyValue v = RubyAPI.callPublicOneArgMethod(arg0, arg1, null, "<=>"); return ((RubyFixnum)v).intValue(); } } ); } public void sort(final RubyBlock block) { final RubyArray self = this; Collections.sort(array_, new Comparator<RubyValue>() { public int compare(RubyValue arg0, RubyValue arg1) { //TODO can not check if block return/break occured. RubyValue v = block.invoke(self, new RubyArray(arg0, arg1)); return ((RubyFixnum)v).intValue(); } } ); } public int hash() { return array_.hashCode(); } public RubyArray and(RubyArray other) { RubyArray a = new RubyArray(); for (RubyValue v : array_) { if (other.include(v) && !a.include(v)) { a.add(v); } } return a; } public RubyArray or(RubyArray other) { RubyArray a = new RubyArray(); for (RubyValue v : array_) { if (!a.include(v)) { a.add(v); } } for (RubyValue v : other) { if (!a.include(v)) { a.add(v); } } return a; } public boolean compact() { return remove(ObjectFactory.nilValue); } public boolean uniq() { boolean b = false; for (int i = 0; i < array_.size(); ++i) { for (int j = i + 1; j < array_.size();) { if (RubyAPI.testEqual(array_.get(i), array_.get(j))) { array_.remove(j); b = true; } else { ++j; } } } return b; } public void reverse() { Collections.reverse(array_); } }
src/com/xruby/runtime/value/RubyArray.java
/** * Copyright 2005-2007 Xue Yong Zhi, Ye Zheng * Distributed under the GNU General Public License 2.0 */ package com.xruby.runtime.value; import java.util.*; import com.xruby.runtime.lang.*; /** * @breif Internal representation of a ruby array * */ public class RubyArray extends RubyBasic implements Iterable<RubyValue> { private ArrayList<RubyValue> array_; private boolean is_not_single_asterisk_; //e.g. does not look like yield *[[]] public RubyArray() { this(1, true); } public RubyArray(int size) { this(size, true); } public RubyArray(RubyValue v) { this(1, true); add(v); } public RubyArray(RubyValue value1, RubyValue value2) { this(2, true); add(value1); add(value2); } public RubyArray(int size, RubyValue default_value) { this(size, true); for (int i = 0; i < size; ++i) { array_.add(default_value); } } public RubyArray(int size, boolean isNotSingleAsterisk) { super(RubyRuntime.ArrayClass); array_ = new ArrayList<RubyValue>(size); this.is_not_single_asterisk_ = isNotSingleAsterisk; } @SuppressWarnings("unchecked") public RubyArray clone() { RubyArray v = (RubyArray)super.clone(); v.array_ = (ArrayList<RubyValue>)array_.clone(); return v; } public boolean isNotSingleAsterisk() { return this.is_not_single_asterisk_; } public RubyArray add(RubyValue v) { array_.add(v); return this; } public RubyArray insert(int index, RubyValue v) { array_.add(index, v); return this; } public RubyValue remove(int index) { if (index < 0 || index > size()) { return ObjectFactory.nilValue; } return array_.remove(index); } public int size() { return array_.size(); } public RubyValue delete(RubyValue arg) { boolean found = false; while (array_.remove(arg)) { found = true; } return found ? arg : ObjectFactory.nilValue; } public Iterator<RubyValue> iterator() { return array_.iterator(); } private int getRealIndex(int i) { int index = i; if (index < 0) { index = array_.size() + index; } if (index < 0) { throw new RubyException(RubyRuntime.IndexErrorClass, "index " + i + " out of array"); } return index; } public RubyValue set(int start, RubyValue value) { int index = getRealIndex(start); if (index < array_.size()) { array_.set(index, value); } else { array_.ensureCapacity(index + 1); for (int i = array_.size(); i < index; ++i) { array_.add(ObjectFactory.nilValue); } array_.add(value); } return value; } public RubyValue replace(int start, int length, RubyValue value) { int index = getRealIndex(start); if (length < 0) { throw new RubyException(RubyRuntime.IndexErrorClass, "negative length ("+ length + ")"); } else if (0 == length) { if (value instanceof RubyArray) { array_.addAll(index, ((RubyArray)value).getInternal()); } else { array_.add(index, value); } } else { for (int i = 0; i < length - 1; ++i) { array_.remove(index); } //TODO should we use addAll if value is RubyArray? array_.set(index, value); } return value; } public RubyValue get(int index) { if (index < 0) { index = array_.size() + index; } if (index < 0 || index >= size()) { return ObjectFactory.nilValue; } else { return array_.get(index); } } public RubyArray copy() { RubyArray resultArray = new RubyArray(array_.size()); for (RubyValue v : array_) { resultArray.add(v); } return resultArray; } public RubyValue compare(RubyArray other_array) { int length = (size() <= other_array.size()) ? size() : other_array.size(); for (int i = 0; i < length; ++i) { RubyValue v = RubyAPI.callPublicOneArgMethod(get(i), other_array.get(i), null, "<=>"); if (!RubyAPI.testEqual(v, ObjectFactory.fixnum0)) { return v; } } if (size() == other_array.size()) { return ObjectFactory.fixnum0; } else if (size() > other_array.size()) { return ObjectFactory.fixnum1; } else { return ObjectFactory.createFixnum(-1); } } public RubyArray subarray(int begin, int length) { final int arraySize = array_.size(); if (begin > arraySize) { return null; } if (length < 0) { return null; } if (begin < 0) { begin += arraySize; } if (begin + length > arraySize) { length = arraySize - begin; if (length < 0) { length = 0; } } if (length == 0) { return new RubyArray(0); } RubyArray resultArray = new RubyArray(length); int last = begin + length; for (int i = begin; i < last; i++) { resultArray.add(array_.get(i)); } return resultArray; } public boolean equals(RubyArray that) { if (array_.size() != that.size()) { return false; } for (int i = 0; i < array_.size(); ++i) { if (!RubyAPI.testEqual(this.get(i), that.get(i))) { return false; } } return true; } public RubyValue to_s() { RubyString r = ObjectFactory.createString(); for (RubyValue v : array_) { RubyValue s = RubyAPI.callPublicMethod(v, null, null, "to_s"); r.appendString(s.toString()); // TODO: The output of to_s is not as the same as cruby, we should solve this issue // TODO: and change the corresponding testcases in RubyCompilerTest, such as test_array_expand. } return r; } ArrayList<RubyValue> getInternal() { return array_; } public void concat(RubyValue v) { if (!(v instanceof RubyArray)) { throw new RubyException(RubyRuntime.TypeErrorClass, "can't convert " + v.getRubyClass().toString() + " into Array"); } array_.addAll(((RubyArray)v).getInternal()); } public RubyArray plus(RubyArray v) { int size = array_.size() + v.size(); RubyArray resultArray = new RubyArray(size); resultArray.array_.addAll(array_); resultArray.array_.addAll(v.array_); return resultArray; } private boolean remove(RubyValue v) { boolean r = false; while (array_.remove(v)) { r = true; } return r; } public RubyArray minus(RubyArray other) { RubyArray a = this.copy(); for (RubyValue v : other) { a.remove(v); } return a; } public RubyArray times(int times) { if (times < 0) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "negative argument"); } int size = array_.size() * times; RubyArray resultArray = new RubyArray(size); for (int i = 0; i < times; i++) { resultArray.array_.addAll(array_); } return resultArray; } /// Returns true if the given object is present public boolean include(RubyValue v) { for (RubyValue value : array_) { if (RubyAPI.testEqual(value, v)) { return true; } } return false; } public void rb_iterate(RubyValue receiver, RubyBlock block) { for(RubyValue item: array_) { RubyArray args = new RubyArray(); args.add(item); block.invoke(receiver, args); } } public RubyArray expand(RubyValue v) { if (v instanceof RubyArray) { //[5,6,*[1, 2]] array_.addAll(((RubyArray)v).getInternal()); } else { //[5,6,*1], [5,6,*nil] array_.add(v); } return this; } //create a new Array containing every element from index to the end public RubyValue collect(int index) { assert(index >= 0); final int size = array_.size() - index; if (size < 0) { return new RubyArray(); } RubyArray a = new RubyArray(size, true); for (int i = index; i < array_.size(); ++i) { a.add(array_.get(i)); } return a; } public RubyArray unshift(RubyValue value){ array_.add(0, value); return this; } public RubyArray unshift(RubyArray value){ array_.addAll(0, value.getInternal()); return this; } public void sort() { Collections.sort(array_, new Comparator<RubyValue>() { public int compare(RubyValue arg0, RubyValue arg1) { RubyValue v = RubyAPI.callPublicOneArgMethod(arg0, arg1, null, "<=>"); return ((RubyFixnum)v).intValue(); } } ); } public void sort(final RubyBlock block) { final RubyArray self = this; Collections.sort(array_, new Comparator<RubyValue>() { public int compare(RubyValue arg0, RubyValue arg1) { //TODO can not check if block return/break occured. RubyValue v = block.invoke(self, new RubyArray(arg0, arg1)); return ((RubyFixnum)v).intValue(); } } ); } public int hash() { return array_.hashCode(); } public RubyArray and(RubyArray other) { RubyArray a = new RubyArray(); for (RubyValue v : array_) { if (other.include(v) && !a.include(v)) { a.add(v); } } return a; } public RubyArray or(RubyArray other) { RubyArray a = new RubyArray(); for (RubyValue v : array_) { if (!a.include(v)) { a.add(v); } } for (RubyValue v : other) { if (!a.include(v)) { a.add(v); } } return a; } public boolean compact() { return remove(ObjectFactory.nilValue); } public boolean uniq() { boolean b = false; for (int i = 0; i < array_.size(); ++i) { for (int j = i + 1; j < array_.size();) { if (RubyAPI.testEqual(array_.get(i), array_.get(j))) { array_.remove(j); b = true; } else { ++j; } } } return b; } public void reverse() { Collections.reverse(array_); } }
call appendString directly
src/com/xruby/runtime/value/RubyArray.java
call appendString directly
Java
apache-2.0
9491607699337d6fd3907bc6ee951964f2453dee
0
michaelgallacher/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,adedayo/intellij-community,kdwink/intellij-community,amith01994/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,caot/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,kdwink/intellij-community,samthor/intellij-community,apixandru/intellij-community,supersven/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,diorcety/intellij-community,fitermay/intellij-community,holmes/intellij-community,amith01994/intellij-community,ryano144/intellij-community,FHannes/intellij-community,caot/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ibinti/intellij-community,asedunov/intellij-community,caot/intellij-community,fnouama/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,jagguli/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,holmes/intellij-community,hurricup/intellij-community,holmes/intellij-community,supersven/intellij-community,ryano144/intellij-community,vladmm/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,jexp/idea2,dslomov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,consulo/consulo,idea4bsd/idea4bsd,izonder/intellij-community,robovm/robovm-studio,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,kool79/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,allotria/intellij-community,samthor/intellij-community,apixandru/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,holmes/intellij-community,apixandru/intellij-community,fnouama/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,asedunov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,signed/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,SerCeMan/intellij-community,kool79/intellij-community,jagguli/intellij-community,joewalnes/idea-community,signed/intellij-community,semonte/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,signed/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,jexp/idea2,ivan-fedorov/intellij-community,adedayo/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,jagguli/intellij-community,diorcety/intellij-community,allotria/intellij-community,fnouama/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,adedayo/intellij-community,fnouama/intellij-community,blademainer/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,allotria/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ernestp/consulo,youdonghai/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,youdonghai/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,blademainer/intellij-community,blademainer/intellij-community,apixandru/intellij-community,vladmm/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,da1z/intellij-community,amith01994/intellij-community,adedayo/intellij-community,jexp/idea2,da1z/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ibinti/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,jexp/idea2,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,vladmm/intellij-community,FHannes/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,supersven/intellij-community,adedayo/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,supersven/intellij-community,dslomov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,fnouama/intellij-community,FHannes/intellij-community,vladmm/intellij-community,ryano144/intellij-community,blademainer/intellij-community,supersven/intellij-community,caot/intellij-community,consulo/consulo,petteyg/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,jexp/idea2,nicolargo/intellij-community,kdwink/intellij-community,FHannes/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,caot/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,caot/intellij-community,semonte/intellij-community,amith01994/intellij-community,vladmm/intellij-community,robovm/robovm-studio,retomerz/intellij-community,suncycheng/intellij-community,izonder/intellij-community,semonte/intellij-community,retomerz/intellij-community,consulo/consulo,izonder/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,slisson/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,dslomov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,allotria/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,signed/intellij-community,kool79/intellij-community,asedunov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,allotria/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,joewalnes/idea-community,samthor/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,xfournet/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,caot/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,robovm/robovm-studio,fnouama/intellij-community,vladmm/intellij-community,kdwink/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,supersven/intellij-community,vladmm/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,FHannes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,holmes/intellij-community,slisson/intellij-community,signed/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,clumsy/intellij-community,consulo/consulo,ryano144/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,xfournet/intellij-community,signed/intellij-community,youdonghai/intellij-community,ernestp/consulo,petteyg/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ernestp/consulo,diorcety/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,robovm/robovm-studio,consulo/consulo,caot/intellij-community,apixandru/intellij-community,signed/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,ernestp/consulo,diorcety/intellij-community,kdwink/intellij-community,ernestp/consulo,orekyuu/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,allotria/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,apixandru/intellij-community,jexp/idea2,Lekanich/intellij-community,vvv1559/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,slisson/intellij-community,ryano144/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,asedunov/intellij-community,consulo/consulo,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,samthor/intellij-community,dslomov/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,izonder/intellij-community,gnuhub/intellij-community,holmes/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,izonder/intellij-community,kool79/intellij-community,signed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,caot/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,kool79/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,fitermay/intellij-community,holmes/intellij-community,akosyakov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,izonder/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,robovm/robovm-studio,kdwink/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,blademainer/intellij-community,xfournet/intellij-community,samthor/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,jexp/idea2,Distrotech/intellij-community,gnuhub/intellij-community,izonder/intellij-community,hurricup/intellij-community,slisson/intellij-community,kool79/intellij-community,adedayo/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,joewalnes/idea-community
/* * Copyright 2000-2006 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.xml.model; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.xml.XmlFile; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomFileElement; import com.intellij.util.xml.DomManager; import com.intellij.util.xml.ModelMerger; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Dmitry Avdeev */ public abstract class DomModelFactory<T extends DomElement, M extends DomModel<T>, C extends PsiElement> extends SimpleDomModelFactory<T> { private final DomModelCache<M, XmlFile> myModelCache; private final DomModelCache<M, Module> myCombinedModelCache; private final DomModelCache<List<M>, Module> myAllModelsCache; protected DomModelFactory(@NotNull Class<T> aClass, @NotNull ModelMerger modelMerger, final Project project, @NonNls String name) { super(aClass, modelMerger); myModelCache = new DomModelCache<M, XmlFile>(project, name + " model") { @NotNull protected CachedValueProvider.Result<M> computeValue(@NotNull XmlFile file) { final PsiFile originalFile = file.getOriginalFile(); if (originalFile != null) { file = (XmlFile)originalFile; } final Module module = ModuleUtil.findModuleForPsiElement(file); final M model = computeModel(file, module); return new CachedValueProvider.Result<M>(model, computeDependencies(file, module)); } }; myCombinedModelCache = new DomModelCache<M, Module>(project, name + " combined model") { @NotNull protected CachedValueProvider.Result<M> computeValue(@NotNull final Module module) { final M combinedModel = computeCombinedModel(module); return new CachedValueProvider.Result<M>(combinedModel, combinedModel == null ? computeDependencies(module) : computeDependencies(combinedModel, module)); } }; myAllModelsCache = new DomModelCache<List<M>, Module>(project, name + " models list") { @NotNull protected CachedValueProvider.Result<List<M>> computeValue(@NotNull final Module module) { final List<M> models = computeAllModels(module); return new CachedValueProvider.Result<List<M>>(models, computeDependencies(module)); } }; } @NotNull protected Object[] computeDependencies(@NotNull XmlFile file, @Nullable Module module) { if (module == null) { return new Object[] {file}; } else { final Object[] moduleDependencies = computeDependencies(module); return ArrayUtil.append(moduleDependencies, file); } } @NotNull protected Object[] computeDependencies(@NotNull Module module) { final ProjectRootManager manager = ProjectRootManager.getInstance(module.getProject()); return new Object[] { manager }; } @NotNull public Object[] computeDependencies(@NotNull M model, @NotNull Module module) { final Object[] moduleDependencies = computeDependencies(module); final Set<XmlFile> files = model.getConfigFiles(); final ArrayList<Object> dependencies = new ArrayList<Object>(moduleDependencies.length + files.size()); dependencies.addAll(files); Collections.addAll(dependencies, moduleDependencies); return dependencies.toArray(new Object[dependencies.size()]); } @Nullable public abstract M getModel(@NotNull C context); @NotNull public List<M> getAllModels(@NotNull Module module) { final List<M> models = myAllModelsCache.getCachedValue(module); if (models == null) { return Collections.emptyList(); } else { return models; } } @Nullable protected abstract List<M> computeAllModels(@NotNull Module module); @Nullable public M getModelByConfigFile(@Nullable XmlFile psiFile) { if (psiFile == null) { return null; } return myModelCache.getCachedValue(psiFile); } @Nullable protected M computeModel(@NotNull XmlFile psiFile, @Nullable Module module) { if (module == null) { return null; } final List<M> models = getAllModels(module); for (M model: models) { final Set<XmlFile> configFiles = model.getConfigFiles(); if (configFiles.contains(psiFile)) { return model; } } return null; } @Nullable public M getCombinedModel(@Nullable Module module) { if (module == null) { return null; } return myCombinedModelCache.getCachedValue(module); } @Nullable protected M computeCombinedModel(@NotNull Module module) { final List<M> models = getAllModels(module); switch (models.size()) { case 0: return null; case 1: return models.get(0); } Set<XmlFile> configFiles = new LinkedHashSet<XmlFile>(); final ArrayList<T> list = new ArrayList<T>(models.size()); for (M model: models) { final Set<XmlFile> files = model.getConfigFiles(); for (XmlFile file: files) { final T t = getDom(file); if (t != null) { list.add(t); } } configFiles.addAll(files); } final T mergedModel = getModelMerger().mergeModels(getClazz(), list); final M firstModel = models.get(0); return createCombinedModel(configFiles, mergedModel, firstModel); } /** * Factory method to create combined model for given module. * Used by {@link #computeCombinedModel(com.intellij.openapi.module.Module)}. * * @param configFiles file set including all files for all models returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @param mergedModel merged model for all models returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @param firstModel the first model returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @return combined model. */ protected abstract M createCombinedModel(Set<XmlFile> configFiles, T mergedModel, M firstModel); @NotNull public Set<XmlFile> getConfigFiles(@Nullable C context) { if (context == null) { return Collections.emptySet(); } final M model = getModel(context); if (model == null) { return Collections.emptySet(); } else { return model.getConfigFiles(); } } @NotNull public Set<XmlFile> getAllConfigFiles(@NotNull Module module) { final HashSet<XmlFile> xmlFiles = new HashSet<XmlFile>(); for (M model: getAllModels(module)) { xmlFiles.addAll(model.getConfigFiles()); } return xmlFiles; } public List<DomFileElement<T>> getFileElements(M model) { final ArrayList<DomFileElement<T>> list = new ArrayList<DomFileElement<T>>(model.getConfigFiles().size()); for (XmlFile configFile: model.getConfigFiles()) { final DomFileElement<T> element = DomManager.getDomManager(configFile.getProject()).getFileElement(configFile, myClass); if (element != null) { list.add(element); } } return list; } public ModelMerger getModelMerger() { return myModelMerger; } public Class<T> getClazz() { return myClass; } }
dom/openapi/src/com/intellij/util/xml/model/DomModelFactory.java
/* * Copyright 2000-2006 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.xml.model; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.xml.XmlFile; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomFileElement; import com.intellij.util.xml.DomManager; import com.intellij.util.xml.ModelMerger; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Dmitry Avdeev */ public abstract class DomModelFactory<T extends DomElement, M extends DomModel<T>, C extends PsiElement> extends SimpleDomModelFactory<T> { private final DomModelCache<M, XmlFile> myModelCache; private final DomModelCache<M, Module> myCombinedModelCache; private final DomModelCache<List<M>, Module> myAllModelsCache; protected DomModelFactory(@NotNull Class<T> aClass, @NotNull ModelMerger modelMerger, final Project project, @NonNls String name) { super(aClass, modelMerger); myModelCache = new DomModelCache<M, XmlFile>(project, name + " model") { @NotNull protected CachedValueProvider.Result<M> computeValue(@NotNull XmlFile file) { final PsiFile originalFile = file.getOriginalFile(); if (originalFile != null) { file = (XmlFile)originalFile; } final Module module = ModuleUtil.findModuleForPsiElement(file); final M model = module != null ? computeModel(file, module) : null; return new CachedValueProvider.Result<M>(model, computeDependencies(file, module)); } }; myCombinedModelCache = new DomModelCache<M, Module>(project, name + " combined model") { @NotNull protected CachedValueProvider.Result<M> computeValue(@NotNull final Module module) { final M combinedModel = computeCombinedModel(module); return new CachedValueProvider.Result<M>(combinedModel, combinedModel == null ? computeDependencies(module) : computeDependencies(combinedModel, module)); } }; myAllModelsCache = new DomModelCache<List<M>, Module>(project, name + " models list") { @NotNull protected CachedValueProvider.Result<List<M>> computeValue(@NotNull final Module module) { final List<M> models = computeAllModels(module); return new CachedValueProvider.Result<List<M>>(models, computeDependencies(module)); } }; } @NotNull protected Object[] computeDependencies(@NotNull XmlFile file, @Nullable Module module) { if (module == null) { return new Object[] {file}; } else { final Object[] moduleDependencies = computeDependencies(module); return ArrayUtil.append(moduleDependencies, file); } } @NotNull protected Object[] computeDependencies(@NotNull Module module) { final ProjectRootManager manager = ProjectRootManager.getInstance(module.getProject()); return new Object[] { manager }; } @NotNull public Object[] computeDependencies(@NotNull M model, @NotNull Module module) { final Object[] moduleDependencies = computeDependencies(module); final Set<XmlFile> files = model.getConfigFiles(); final ArrayList<Object> dependencies = new ArrayList<Object>(moduleDependencies.length + files.size()); dependencies.addAll(files); Collections.addAll(dependencies, moduleDependencies); return dependencies.toArray(new Object[dependencies.size()]); } @Nullable public abstract M getModel(@NotNull C context); @NotNull public List<M> getAllModels(@NotNull Module module) { final List<M> models = myAllModelsCache.getCachedValue(module); if (models == null) { return Collections.emptyList(); } else { return models; } } @Nullable protected abstract List<M> computeAllModels(@NotNull Module module); @Nullable public M getModelByConfigFile(@Nullable XmlFile psiFile) { if (psiFile == null) { return null; } return myModelCache.getCachedValue(psiFile); } @Nullable protected M computeModel(@NotNull XmlFile psiFile, @Nullable Module module) { if (module == null) { return null; } final List<M> models = getAllModels(module); for (M model: models) { final Set<XmlFile> configFiles = model.getConfigFiles(); if (configFiles.contains(psiFile)) { return model; } } return null; } @Nullable public M getCombinedModel(@Nullable Module module) { if (module == null) { return null; } return myCombinedModelCache.getCachedValue(module); } @Nullable protected M computeCombinedModel(@NotNull Module module) { final List<M> models = getAllModels(module); switch (models.size()) { case 0: return null; case 1: return models.get(0); } Set<XmlFile> configFiles = new LinkedHashSet<XmlFile>(); final ArrayList<T> list = new ArrayList<T>(models.size()); for (M model: models) { final Set<XmlFile> files = model.getConfigFiles(); for (XmlFile file: files) { final T t = getDom(file); if (t != null) { list.add(t); } } configFiles.addAll(files); } final T mergedModel = getModelMerger().mergeModels(getClazz(), list); final M firstModel = models.get(0); return createCombinedModel(configFiles, mergedModel, firstModel); } /** * Factory method to create combined model for given module. * Used by {@link #computeCombinedModel(com.intellij.openapi.module.Module)}. * * @param configFiles file set including all files for all models returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @param mergedModel merged model for all models returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @param firstModel the first model returned by {@link #getAllModels(com.intellij.openapi.module.Module)}. * @return combined model. */ protected abstract M createCombinedModel(Set<XmlFile> configFiles, T mergedModel, M firstModel); @NotNull public Set<XmlFile> getConfigFiles(@Nullable C context) { if (context == null) { return Collections.emptySet(); } final M model = getModel(context); if (model == null) { return Collections.emptySet(); } else { return model.getConfigFiles(); } } @NotNull public Set<XmlFile> getAllConfigFiles(@NotNull Module module) { final HashSet<XmlFile> xmlFiles = new HashSet<XmlFile>(); for (M model: getAllModels(module)) { xmlFiles.addAll(model.getConfigFiles()); } return xmlFiles; } public List<DomFileElement<T>> getFileElements(M model) { final ArrayList<DomFileElement<T>> list = new ArrayList<DomFileElement<T>>(model.getConfigFiles().size()); for (XmlFile configFile: model.getConfigFiles()) { final DomFileElement<T> element = DomManager.getDomManager(configFile.getProject()).getFileElement(configFile, myClass); if (element != null) { list.add(element); } } return list; } public ModelMerger getModelMerger() { return myModelMerger; } public Class<T> getClazz() { return myClass; } }
spring configuration initial
dom/openapi/src/com/intellij/util/xml/model/DomModelFactory.java
spring configuration initial
Java
apache-2.0
91b199ed40ade3c8d866173c894e4c7617169a20
0
trask/glowroot,trask/glowroot,trask/glowroot,glowroot/glowroot,trask/glowroot,glowroot/glowroot,glowroot/glowroot,glowroot/glowroot
/* * Copyright 2015-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.glowroot.server.storage; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.Futures; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.immutables.value.Value; import org.glowroot.common.live.ImmutableTracePoint; import org.glowroot.common.live.LiveTraceRepository.Existence; import org.glowroot.common.live.LiveTraceRepository.TracePoint; import org.glowroot.common.live.LiveTraceRepository.TracePointFilter; import org.glowroot.common.model.Result; import org.glowroot.common.util.Styles; import org.glowroot.server.util.Messages; import org.glowroot.storage.repo.ConfigRepository; import org.glowroot.storage.repo.ImmutableErrorMessageCount; import org.glowroot.storage.repo.ImmutableErrorMessagePoint; import org.glowroot.storage.repo.ImmutableErrorMessageResult; import org.glowroot.storage.repo.ImmutableHeaderPlus; import org.glowroot.storage.repo.TraceRepository; import org.glowroot.storage.repo.Utils; import org.glowroot.storage.util.AgentRollups; import org.glowroot.wire.api.model.ProfileOuterClass.Profile; import org.glowroot.wire.api.model.Proto; import org.glowroot.wire.api.model.Proto.StackTraceElement; import org.glowroot.wire.api.model.TraceOuterClass.Trace; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.HOURS; public class TraceDao implements TraceRepository { private static final String WITH_DTCS = "with compaction = { 'class' : 'DateTieredCompactionStrategy' }"; private final Session session; private final ConfigRepository configRepository; private final TraceAttributeNameDao traceAttributeNameDao; private final PreparedStatement insertOverallSlowPoint; private final PreparedStatement insertTransactionSlowPoint; private final PreparedStatement insertOverallSlowCount; private final PreparedStatement insertTransactionSlowCount; private final PreparedStatement insertOverallErrorPoint; private final PreparedStatement insertTransactionErrorPoint; private final PreparedStatement insertOverallErrorCount; private final PreparedStatement insertTransactionErrorCount; private final PreparedStatement insertOverallErrorMessage; private final PreparedStatement insertTransactionErrorMessage; private final PreparedStatement insertHeader; private final PreparedStatement insertEntry; private final PreparedStatement insertMainThreadProfile; private final PreparedStatement insertAuxThreadProfile; private final PreparedStatement readOverallSlowPoint; private final PreparedStatement readTransactionSlowPoint; private final PreparedStatement readOverallErrorPoint; private final PreparedStatement readTransactionErrorPoint; private final PreparedStatement readOverallErrorMessage; private final PreparedStatement readTransactionErrorMessage; private final PreparedStatement readHeader; private final PreparedStatement readEntries; private final PreparedStatement readMainThreadProfile; private final PreparedStatement readAuxThreadProfile; private final PreparedStatement deletePartialOverallSlowPoint; private final PreparedStatement deletePartialTransactionSlowPoint; private final PreparedStatement deletePartialOverallSlowCount; private final PreparedStatement deletePartialTransactionSlowCount; public TraceDao(Session session, ConfigRepository configRepository) { this.session = session; this.configRepository = configRepository; traceAttributeNameDao = new TraceAttributeNameDao(session, configRepository); session.execute("create table if not exists trace_tt_slow_point (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, duration_nanos bigint, error boolean, headline varchar," + " user varchar, attributes blob, primary key ((agent_rollup, transaction_type)," + " capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_slow_point (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, duration_nanos bigint, error boolean," + " headline varchar, user varchar, attributes blob, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_point (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, duration_nanos bigint, error_message varchar," + " headline varchar, user varchar, attributes blob, primary key ((agent_rollup," + " transaction_type), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_point (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, duration_nanos bigint," + " error_message varchar, headline varchar, user varchar, attributes blob," + " primary key ((agent_rollup, transaction_type, transaction_name), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_message (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, error_message varchar, primary key ((agent_rollup," + " transaction_type), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_message (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, error_message varchar, primary key" + " ((agent_rollup, transaction_type, transaction_name), capture_time, agent_id," + " trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_header (agent_id varchar," + " trace_id varchar, header blob, primary key (agent_id, trace_id)) " + WITH_DTCS); // "index" is cassandra reserved word session.execute("create table if not exists trace_entry (agent_id varchar," + " trace_id varchar, index_ int, depth int, start_offset_nanos bigint," + " duration_nanos bigint, active boolean, message varchar, detail blob," + " location_stack_trace blob, error blob, primary key (agent_id, trace_id," + " index_)) " + WITH_DTCS); session.execute("create table if not exists trace_main_thread_profile (agent_id varchar," + " trace_id varchar, profile blob, primary key (agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_aux_thread_profile (agent_id varchar," + " trace_id varchar, profile blob, primary key (agent_id, trace_id)) " + WITH_DTCS); // agent_rollup/capture_time is not necessarily unique // using a counter would be nice since only need sum over capture_time range // but counter has no TTL, see https://issues.apache.org/jira/browse/CASSANDRA-2103 // so adding trace_id to provide uniqueness session.execute("create table if not exists trace_tt_slow_count (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, primary key ((agent_rollup, transaction_type), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_slow_count (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_count (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, primary key ((agent_rollup, transaction_type), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_count (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); insertOverallSlowPoint = session.prepare("insert into trace_tt_slow_point (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id, duration_nanos, error," + " user, attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertTransactionSlowPoint = session.prepare("insert into trace_tn_slow_point" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, duration_nanos, error, user, attributes) values" + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallSlowCount = session.prepare("insert into trace_tt_slow_count (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionSlowCount = session.prepare("insert into trace_tn_slow_count" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorPoint = session.prepare("insert into trace_tt_error_point (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id, duration_nanos," + " error_message, user, attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionErrorPoint = session.prepare("insert into trace_tn_error_point" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, duration_nanos, error_message, user, attributes) values" + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorCount = session.prepare("insert into trace_tt_error_count (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionErrorCount = session.prepare("insert into trace_tn_error_count" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorMessage = session.prepare("insert into trace_tt_error_message" + " (agent_rollup, transaction_type, capture_time, agent_id, trace_id," + " error_message) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertTransactionErrorMessage = session.prepare("insert into trace_tn_error_message" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, error_message) values (?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertHeader = session.prepare("insert into trace_header (agent_id, trace_id, header)" + " values (?, ?, ?) using ttl ?"); insertEntry = session.prepare("insert into trace_entry (agent_id, trace_id, index_, depth," + " start_offset_nanos, duration_nanos, active, message, detail," + " location_stack_trace, error) values (?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?, ?) using ttl ?"); insertMainThreadProfile = session.prepare("insert into trace_main_thread_profile" + " (agent_id, trace_id, profile) values (?, ?, ?) using ttl ?"); insertAuxThreadProfile = session.prepare("insert into trace_aux_thread_profile" + " (agent_id, trace_id, profile) values (?, ?, ?) using ttl ?"); readOverallSlowPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, error, headline, user, attributes from trace_tt_slow_point" + " where agent_rollup = ? and transaction_type = ? and capture_time > ?" + " and capture_time <= ?"); readTransactionSlowPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, error, headline, user, attributes from trace_tn_slow_point" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?"); readOverallErrorPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, headline, error_message, user, attributes" + " from trace_tt_error_point where agent_rollup = ? and transaction_type = ?" + " and capture_time > ? and capture_time <= ?"); readTransactionErrorPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, headline, error_message, user, attributes" + " from trace_tn_error_point where agent_rollup = ? and transaction_type = ?" + " and transaction_name = ? and capture_time > ? and capture_time <= ?"); readOverallErrorMessage = session.prepare("select capture_time, error_message" + " from trace_tt_error_message where agent_rollup = ? and transaction_type = ?" + " and capture_time > ? and capture_time <= ?"); readTransactionErrorMessage = session.prepare("select capture_time, error_message" + " from trace_tn_error_message where agent_rollup = ? and transaction_type = ?" + " and transaction_name = ? and capture_time > ? and capture_time <= ?"); readHeader = session .prepare("select header from trace_header where agent_id = ? and trace_id = ?"); readEntries = session.prepare("select depth, start_offset_nanos, duration_nanos," + " active, message, detail, location_stack_trace, error from" + " trace_entry where agent_id = ? and trace_id = ?"); readMainThreadProfile = session.prepare("select profile from trace_main_thread_profile" + " where agent_id = ? and trace_id = ?"); readAuxThreadProfile = session.prepare("select profile from trace_aux_thread_profile" + " where agent_id = ? and trace_id = ?"); deletePartialOverallSlowPoint = session.prepare("delete from trace_tt_slow_point" + " where agent_rollup = ? and transaction_type = ? and capture_time = ?" + " and agent_id = ? and trace_id = ?"); deletePartialTransactionSlowPoint = session.prepare("delete from trace_tn_slow_point" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time = ? and agent_id = ? and trace_id = ?"); deletePartialOverallSlowCount = session.prepare("delete from trace_tt_slow_count" + " where agent_rollup = ? and transaction_type = ? and capture_time = ?" + " and agent_id = ? and trace_id = ?"); deletePartialTransactionSlowCount = session.prepare("delete from trace_tn_slow_count" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time = ? and agent_id = ? and trace_id = ?"); } @Override public void collect(String agentId, Trace trace) throws Exception { String traceId = trace.getId(); // TODO after roll out agent 0.9.1, no need to read header if !trace.getUpdate() Trace.Header priorHeader = readHeader(agentId, traceId); Trace.Header header = trace.getHeader(); // TEMPORARY UNTIL ROLL OUT AGENT 0.9.1 traceId = traceId.replaceAll("-", ""); traceId = traceId.substring(traceId.length() - 20); traceId = lowerSixBytesHex(header.getStartTime()) + traceId; // END TEMPORARY // TEMPORARY UNTIL ROLL OUT AGENT 0.9.0 if (header.getTransactionType().equals("Servlet")) { header = Trace.Header.newBuilder(header) .setTransactionType("Web") .build(); } // END TEMPORARY // unlike aggregates and gauge values, traces can get written to server rollups immediately List<String> agentRollups = AgentRollups.getAgentRollups(agentId); List<ResultSetFuture> futures = Lists.newArrayList(); int ttl = getTTL(); for (String agentRollup : agentRollups) { List<Trace.Attribute> attributes = header.getAttributeList(); if (header.getSlow()) { BoundStatement boundStatement = insertOverallSlowPoint.bind(); int i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setBool(i++, header.hasError()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setBool(i++, header.hasError()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); if (priorHeader != null) { boundStatement = deletePartialOverallSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialTransactionSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setString(i++, priorHeader.getTransactionName()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialOverallSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialTransactionSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setString(i++, priorHeader.getTransactionName()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); } } // seems unnecessary to insert error info for partial traces // and this avoids having to clean up partial trace data when trace is complete if (header.hasError() && !header.getPartial()) { BoundStatement boundStatement = insertOverallErrorMessage.bind(); int i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorMessage.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallErrorPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallErrorCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } for (Trace.Attribute attributeName : attributes) { traceAttributeNameDao.maybeUpdateLastCaptureTime(agentRollup, header.getTransactionType(), attributeName.getName(), futures); } } BoundStatement boundStatement = insertHeader.bind(); int i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(header.toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); for (int entryIndex = 0; entryIndex < trace.getEntryCount(); entryIndex++) { Trace.Entry entry = trace.getEntry(entryIndex); boundStatement = insertEntry.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, entryIndex); boundStatement.setInt(i++, entry.getDepth()); boundStatement.setLong(i++, entry.getStartOffsetNanos()); boundStatement.setLong(i++, entry.getDurationNanos()); boundStatement.setBool(i++, entry.getActive()); boundStatement.setString(i++, entry.getMessage()); List<Trace.DetailEntry> detailEntries = entry.getDetailEntryList(); if (detailEntries.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(detailEntries)); } List<StackTraceElement> location = entry.getLocationStackTraceElementList(); if (location.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(location)); } if (entry.hasError()) { boundStatement.setBytes(i++, ByteBuffer.wrap(entry.getError().toByteArray())); } else { boundStatement.setToNull(i++); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } if (trace.hasMainThreadProfile()) { boundStatement = insertMainThreadProfile.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(trace.getMainThreadProfile().toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } if (trace.hasAuxThreadProfile()) { boundStatement = insertAuxThreadProfile.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(trace.getAuxThreadProfile().toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } Futures.allAsList(futures).get(); } @Override public List<String> readTraceAttributeNames(String agentRollup, String transactionType) { return traceAttributeNameDao.getTraceAttributeNames(agentRollup, transactionType); } @Override public Result<TracePoint> readSlowPoints(String agentRollup, TraceQuery query, TracePointFilter filter, int limit) throws IOException { String transactionName = query.transactionName(); if (transactionName == null) { BoundStatement boundStatement = readOverallSlowPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, false); } else { BoundStatement boundStatement = readTransactionSlowPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, false); } } @Override public Result<TracePoint> readErrorPoints(String agentRollup, TraceQuery query, TracePointFilter filter, int limit) throws IOException { String transactionName = query.transactionName(); if (transactionName == null) { BoundStatement boundStatement = readOverallErrorPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, true); } else { BoundStatement boundStatement = readTransactionErrorPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, true); } } @Override public long readSlowCount(String agentRollup, TraceQuery query) { String transactionName = query.transactionName(); if (transactionName == null) { ResultSet results = session.execute( "select count(*) from trace_tt_slow_count where agent_rollup = ?" + " and transaction_type = ? and capture_time > ?" + " and capture_time <= ?", agentRollup, query.transactionType(), query.from(), query.to()); return results.one().getLong(0); } else { ResultSet results = session.execute( "select count(*) from trace_tn_slow_count where agent_rollup = ?" + " and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?", agentRollup, query.transactionType(), transactionName, query.from(), query.to()); return results.one().getLong(0); } } @Override public long readErrorCount(String agentRollup, TraceQuery query) { String transactionName = query.transactionName(); if (transactionName == null) { ResultSet results = session.execute( "select count(*) from trace_tt_error_count where agent_rollup = ?" + " and transaction_type = ? and capture_time > ?" + " and capture_time <= ?", agentRollup, query.transactionType(), query.from(), query.to()); return results.one().getLong(0); } else { ResultSet results = session.execute( "select count(*) from trace_tn_error_count where agent_rollup = ?" + " and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?", agentRollup, query.transactionType(), transactionName, query.from(), query.to()); return results.one().getLong(0); } } @Override public ErrorMessageResult readErrorMessages(String agentRollup, TraceQuery query, ErrorMessageFilter filter, long resolutionMillis, int limit) throws Exception { BoundStatement boundStatement; String transactionName = query.transactionName(); if (transactionName == null) { boundStatement = readOverallErrorMessage.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); } else { boundStatement = readTransactionErrorMessage.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); } ResultSet results = session.execute(boundStatement); // rows are already in order by captureTime, so saving sort step by using linked hash map Map<Long, MutableLong> pointCounts = Maps.newLinkedHashMap(); Map<String, MutableLong> messageCounts = Maps.newHashMap(); for (Row row : results) { long captureTime = checkNotNull(row.getTimestamp(0)).getTime(); String errorMessage = checkNotNull(row.getString(1)); if (!matches(filter, errorMessage)) { continue; } long rollupCaptureTime = Utils.getRollupCaptureTime(captureTime, resolutionMillis); pointCounts.computeIfAbsent(rollupCaptureTime, k -> new MutableLong()).increment(); messageCounts.computeIfAbsent(errorMessage, k -> new MutableLong()).increment(); } List<ErrorMessagePoint> points = pointCounts.entrySet().stream() .map(e -> ImmutableErrorMessagePoint.of(e.getKey(), e.getValue().value)) .sorted(Comparator.comparingLong(ErrorMessagePoint::captureTime)) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<ErrorMessagePoint>toList()); List<ErrorMessageCount> counts = messageCounts.entrySet().stream() .map(e -> ImmutableErrorMessageCount.of(e.getKey(), e.getValue().value)) // points above are already ordered by cassandra, but need to reverse sort counts .sorted(Comparator.comparing(ErrorMessageCount::count).reversed()) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<ErrorMessageCount>toList()); if (counts.size() <= limit) { return ImmutableErrorMessageResult.builder() .addAllPoints(points) .counts(new Result<>(counts, false)) .build(); } else { return ImmutableErrorMessageResult.builder() .addAllPoints(points) .counts(new Result<>(counts.subList(0, limit), true)) .build(); } } @Override public @Nullable HeaderPlus readHeaderPlus(String agentId, String traceId) throws InvalidProtocolBufferException { Trace.Header header = readHeader(agentId, traceId); if (header == null) { return null; } Existence entriesExistence = header.getEntryCount() == 0 ? Existence.NO : Existence.YES; Existence profileExistence = header.getMainThreadProfileSampleCount() == 0 && header.getAuxThreadProfileSampleCount() == 0 ? Existence.NO : Existence.YES; return ImmutableHeaderPlus.of(header, entriesExistence, profileExistence); } @Override public List<Trace.Entry> readEntries(String agentId, String traceId) throws IOException { BoundStatement boundStatement = readEntries.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); List<Trace.Entry> entries = Lists.newArrayList(); while (!results.isExhausted()) { Row row = results.one(); int i = 0; Trace.Entry.Builder entry = Trace.Entry.newBuilder() .setDepth(row.getInt(i++)) .setStartOffsetNanos(row.getLong(i++)) .setDurationNanos(row.getLong(i++)) .setActive(row.getBool(i++)) .setMessage(Strings.nullToEmpty(row.getString(i++))); ByteBuffer detailBytes = row.getBytes(i++); if (detailBytes != null) { entry.addAllDetailEntry( Messages.parseDelimitedFrom(detailBytes, Trace.DetailEntry.parser())); } ByteBuffer locationBytes = row.getBytes(i++); if (locationBytes != null) { entry.addAllLocationStackTraceElement(Messages.parseDelimitedFrom(locationBytes, Proto.StackTraceElement.parser())); } ByteBuffer errorBytes = row.getBytes(i++); if (errorBytes != null) { entry.setError(Trace.Error.parseFrom(ByteString.copyFrom(errorBytes))); } entries.add(entry.build()); } return entries; } @Override public @Nullable Profile readMainThreadProfile(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readMainThreadProfile.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Profile.parseFrom(ByteString.copyFrom(bytes)); } @Override public @Nullable Profile readAuxThreadProfile(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readAuxThreadProfile.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Profile.parseFrom(ByteString.copyFrom(bytes)); } private @Nullable Trace.Header readHeader(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readHeader.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Trace.Header.parseFrom(ByteString.copyFrom(bytes)); } private int getTTL() { return Ints.saturatedCast( HOURS.toSeconds(configRepository.getStorageConfig().traceExpirationHours())); } private static Result<TracePoint> processPoints(ResultSet results, TracePointFilter filter, int limit, boolean errorPoints) throws IOException { List<TracePoint> tracePoints = Lists.newArrayList(); for (Row row : results) { int i = 0; String agentId = checkNotNull(row.getString(i++)); String traceId = checkNotNull(row.getString(i++)); long captureTime = checkNotNull(row.getTimestamp(i++)).getTime(); long durationNanos = row.getLong(i++); boolean error = errorPoints ? true : row.getBool(i++); // headline is always non-null, except for old data prior to when headline column added String headline = Strings.nullToEmpty(row.getString(i++)); // error points are defined by having an error message, so safe to checkNotNull String errorMessage = errorPoints ? checkNotNull(row.getString(i++)) : ""; String user = Strings.nullToEmpty(row.getString(i++)); ByteBuffer attributeBytes = row.getBytes(i++); List<Trace.Attribute> attrs = Messages.parseDelimitedFrom(attributeBytes, Trace.Attribute.parser()); Map<String, List<String>> attributes = attrs.stream().collect( Collectors.toMap(Trace.Attribute::getName, Trace.Attribute::getValueList)); if (filter.matchesDuration(durationNanos) && filter.matchesHeadline(headline) && filter.matchesError(errorMessage) && filter.matchesUser(user) && filter.matchesAttributes(attributes)) { tracePoints.add(ImmutableTracePoint.builder() .agentId(agentId) .traceId(traceId) .captureTime(captureTime) .durationNanos(durationNanos) .error(error) .build()); } } // remove duplicates (partially stored traces) since there is (small) window between updated // insert (with new capture time) and the delete of prior insert (with prior capture time) Set<TraceKey> traceKeys = Sets.newHashSet(); ListIterator<TracePoint> i = tracePoints.listIterator(tracePoints.size()); while (i.hasPrevious()) { TracePoint trace = i.previous(); TraceKey traceKey = ImmutableTraceKey.of(trace.agentId(), trace.traceId()); if (!traceKeys.add(traceKey)) { i.remove(); } } // apply limit and re-sort if needed if (tracePoints.size() > limit) { tracePoints = tracePoints.stream() .sorted(Comparator.comparingLong(TracePoint::durationNanos).reversed()) .limit(limit) .sorted(Comparator.comparingLong(TracePoint::captureTime)) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<TracePoint>toList()); return new Result<>(tracePoints, true); } else { return new Result<>(tracePoints, false); } } private static boolean matches(ErrorMessageFilter filter, String errorMessage) { String upper = errorMessage.toUpperCase(Locale.ENGLISH); for (String include : filter.includes()) { if (!upper.contains(include.toUpperCase(Locale.ENGLISH))) { return false; } } for (String exclude : filter.excludes()) { if (upper.contains(exclude.toUpperCase(Locale.ENGLISH))) { return false; } } return true; } private static String lowerSixBytesHex(long startTime) { long mask = 1L << 48; return Long.toHexString(mask | (startTime & (mask - 1))).substring(1); } @Value.Immutable @Styles.AllParameters interface TraceKey { String agentId(); String traceId(); } private static class MutableLong { private long value; private void increment() { value++; } } }
server/src/main/java/org/glowroot/server/storage/TraceDao.java
/* * Copyright 2015-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.glowroot.server.storage; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.Futures; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.immutables.value.Value; import org.glowroot.common.live.ImmutableTracePoint; import org.glowroot.common.live.LiveTraceRepository.Existence; import org.glowroot.common.live.LiveTraceRepository.TracePoint; import org.glowroot.common.live.LiveTraceRepository.TracePointFilter; import org.glowroot.common.model.Result; import org.glowroot.common.util.Styles; import org.glowroot.server.util.Messages; import org.glowroot.storage.repo.ConfigRepository; import org.glowroot.storage.repo.ImmutableErrorMessageCount; import org.glowroot.storage.repo.ImmutableErrorMessagePoint; import org.glowroot.storage.repo.ImmutableErrorMessageResult; import org.glowroot.storage.repo.ImmutableHeaderPlus; import org.glowroot.storage.repo.TraceRepository; import org.glowroot.storage.repo.Utils; import org.glowroot.storage.util.AgentRollups; import org.glowroot.wire.api.model.ProfileOuterClass.Profile; import org.glowroot.wire.api.model.Proto; import org.glowroot.wire.api.model.Proto.StackTraceElement; import org.glowroot.wire.api.model.TraceOuterClass.Trace; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.concurrent.TimeUnit.HOURS; public class TraceDao implements TraceRepository { private static final String WITH_DTCS = "with compaction = { 'class' : 'DateTieredCompactionStrategy' }"; private final Session session; private final ConfigRepository configRepository; private final TraceAttributeNameDao traceAttributeNameDao; private final PreparedStatement insertOverallSlowPoint; private final PreparedStatement insertTransactionSlowPoint; private final PreparedStatement insertOverallSlowCount; private final PreparedStatement insertTransactionSlowCount; private final PreparedStatement insertOverallErrorPoint; private final PreparedStatement insertTransactionErrorPoint; private final PreparedStatement insertOverallErrorCount; private final PreparedStatement insertTransactionErrorCount; private final PreparedStatement insertOverallErrorMessage; private final PreparedStatement insertTransactionErrorMessage; private final PreparedStatement insertHeader; private final PreparedStatement insertEntry; private final PreparedStatement insertMainThreadProfile; private final PreparedStatement insertAuxThreadProfile; private final PreparedStatement readOverallSlowPoint; private final PreparedStatement readTransactionSlowPoint; private final PreparedStatement readOverallErrorPoint; private final PreparedStatement readTransactionErrorPoint; private final PreparedStatement readOverallErrorMessage; private final PreparedStatement readTransactionErrorMessage; private final PreparedStatement readHeader; private final PreparedStatement readEntries; private final PreparedStatement readMainThreadProfile; private final PreparedStatement readAuxThreadProfile; private final PreparedStatement deletePartialOverallSlowPoint; private final PreparedStatement deletePartialTransactionSlowPoint; private final PreparedStatement deletePartialOverallSlowCount; private final PreparedStatement deletePartialTransactionSlowCount; public TraceDao(Session session, ConfigRepository configRepository) { this.session = session; this.configRepository = configRepository; traceAttributeNameDao = new TraceAttributeNameDao(session, configRepository); session.execute("create table if not exists trace_tt_slow_point (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, duration_nanos bigint, error boolean, headline varchar," + " user varchar, attributes blob, primary key ((agent_rollup, transaction_type)," + " capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_slow_point (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, duration_nanos bigint, error boolean," + " headline varchar, user varchar, attributes blob, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_point (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, duration_nanos bigint, error_message varchar," + " headline varchar, user varchar, attributes blob, primary key ((agent_rollup," + " transaction_type), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_point (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, duration_nanos bigint," + " error_message varchar, headline varchar, user varchar, attributes blob," + " primary key ((agent_rollup, transaction_type, transaction_name), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_message (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, error_message varchar, primary key ((agent_rollup," + " transaction_type), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_message (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, error_message varchar, primary key" + " ((agent_rollup, transaction_type, transaction_name), capture_time, agent_id," + " trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_header (agent_id varchar," + " trace_id varchar, header blob, primary key (agent_id, trace_id)) " + WITH_DTCS); // "index" is cassandra reserved word session.execute("create table if not exists trace_entry (agent_id varchar," + " trace_id varchar, index_ int, depth int, start_offset_nanos bigint," + " duration_nanos bigint, active boolean, message varchar, detail blob," + " location_stack_trace blob, error blob, primary key (agent_id, trace_id," + " index_)) " + WITH_DTCS); session.execute("create table if not exists trace_main_thread_profile (agent_id varchar," + " trace_id varchar, profile blob, primary key (agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_aux_thread_profile (agent_id varchar," + " trace_id varchar, profile blob, primary key (agent_id, trace_id)) " + WITH_DTCS); // agent_rollup/capture_time is not necessarily unique // using a counter would be nice since only need sum over capture_time range // but counter has no TTL, see https://issues.apache.org/jira/browse/CASSANDRA-2103 // so adding trace_id to provide uniqueness session.execute("create table if not exists trace_tt_slow_count (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, primary key ((agent_rollup, transaction_type), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_slow_count (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tt_error_count (agent_rollup varchar," + " transaction_type varchar, capture_time timestamp, agent_id varchar," + " trace_id varchar, primary key ((agent_rollup, transaction_type), capture_time," + " agent_id, trace_id)) " + WITH_DTCS); session.execute("create table if not exists trace_tn_error_count (agent_rollup varchar," + " transaction_type varchar, transaction_name varchar, capture_time timestamp," + " agent_id varchar, trace_id varchar, primary key ((agent_rollup," + " transaction_type, transaction_name), capture_time, agent_id, trace_id)) " + WITH_DTCS); insertOverallSlowPoint = session.prepare("insert into trace_tt_slow_point (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id, duration_nanos, error," + " user, attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertTransactionSlowPoint = session.prepare("insert into trace_tn_slow_point" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, duration_nanos, error, user, attributes) values" + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallSlowCount = session.prepare("insert into trace_tt_slow_count (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionSlowCount = session.prepare("insert into trace_tn_slow_count" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorPoint = session.prepare("insert into trace_tt_error_point (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id, duration_nanos," + " error_message, user, attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionErrorPoint = session.prepare("insert into trace_tn_error_point" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, duration_nanos, error_message, user, attributes) values" + " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorCount = session.prepare("insert into trace_tt_error_count (agent_rollup," + " transaction_type, capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?)" + " using ttl ?"); insertTransactionErrorCount = session.prepare("insert into trace_tn_error_count" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertOverallErrorMessage = session.prepare("insert into trace_tt_error_message" + " (agent_rollup, transaction_type, capture_time, agent_id, trace_id," + " error_message) values (?, ?, ?, ?, ?, ?) using ttl ?"); insertTransactionErrorMessage = session.prepare("insert into trace_tn_error_message" + " (agent_rollup, transaction_type, transaction_name, capture_time, agent_id," + " trace_id, error_message) values (?, ?, ?, ?, ?, ?, ?) using ttl ?"); insertHeader = session.prepare("insert into trace_header (agent_id, trace_id, header)" + " values (?, ?, ?) using ttl ?"); insertEntry = session.prepare("insert into trace_entry (agent_id, trace_id, index_, depth," + " start_offset_nanos, duration_nanos, active, message, detail," + " location_stack_trace, error) values (?, ?, ?, ?, ?, ?, ?, ?," + " ?, ?, ?) using ttl ?"); insertMainThreadProfile = session.prepare("insert into trace_main_thread_profile" + " (agent_id, trace_id, profile) values (?, ?, ?) using ttl ?"); insertAuxThreadProfile = session.prepare("insert into trace_aux_thread_profile" + " (agent_id, trace_id, profile) values (?, ?, ?) using ttl ?"); readOverallSlowPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, error, headline, user, attributes from trace_tt_slow_point" + " where agent_rollup = ? and transaction_type = ? and capture_time > ?" + " and capture_time <= ?"); readTransactionSlowPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, error, headline, user, attributes from trace_tn_slow_point" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?"); readOverallErrorPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, headline, error_message, user, attributes" + " from trace_tt_error_point where agent_rollup = ? and transaction_type = ?" + " and capture_time > ? and capture_time <= ?"); readTransactionErrorPoint = session.prepare("select agent_id, trace_id, capture_time," + " duration_nanos, headline, error_message, user, attributes" + " from trace_tn_error_point where agent_rollup = ? and transaction_type = ?" + " and transaction_name = ? and capture_time > ? and capture_time <= ?"); readOverallErrorMessage = session.prepare("select capture_time, error_message" + " from trace_tt_error_message where agent_rollup = ? and transaction_type = ?" + " and capture_time > ? and capture_time <= ?"); readTransactionErrorMessage = session.prepare("select capture_time, error_message" + " from trace_tn_error_message where agent_rollup = ? and transaction_type = ?" + " and transaction_name = ? and capture_time > ? and capture_time <= ?"); readHeader = session .prepare("select header from trace_header where agent_id = ? and trace_id = ?"); readEntries = session.prepare("select depth, start_offset_nanos, duration_nanos," + " active, message, detail, location_stack_trace, error from" + " trace_entry where agent_id = ? and trace_id = ?"); readMainThreadProfile = session.prepare("select profile from trace_main_thread_profile" + " where agent_id = ? and trace_id = ?"); readAuxThreadProfile = session.prepare("select profile from trace_aux_thread_profile" + " where agent_id = ? and trace_id = ?"); deletePartialOverallSlowPoint = session.prepare("delete from trace_tt_slow_point" + " where agent_rollup = ? and transaction_type = ? and capture_time = ?" + " and agent_id = ? and trace_id = ?"); deletePartialTransactionSlowPoint = session.prepare("delete from trace_tn_slow_point" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time = ? and agent_id = ? and trace_id = ?"); deletePartialOverallSlowCount = session.prepare("delete from trace_tt_slow_count" + " where agent_rollup = ? and transaction_type = ? and capture_time = ?" + " and agent_id = ? and trace_id = ?"); deletePartialTransactionSlowCount = session.prepare("delete from trace_tn_slow_count" + " where agent_rollup = ? and transaction_type = ? and transaction_name = ?" + " and capture_time = ? and agent_id = ? and trace_id = ?"); } @Override public void collect(String agentId, Trace trace) throws Exception { String traceId = trace.getId(); // TODO after roll out agent 0.9.1, no need to read header if !trace.getUpdate() Trace.Header priorHeader = readHeader(agentId, traceId); Trace.Header header = trace.getHeader(); // TEMPORARY UNTIL ROLL OUT AGENT 0.9.1 traceId = traceId.replaceAll("-", ""); traceId = traceId.substring(traceId.length() - 20); traceId = lowerSixBytesHex(header.getStartTime()) + traceId; // END TEMPORARY // TEMPORARY UNTIL ROLL OUT AGENT 0.9.0 if (header.getTransactionType().equals("Servlet")) { header = Trace.Header.newBuilder(header) .setTransactionType("Web") .build(); } // END TEMPORARY // unlike aggregates and gauge values, traces can get written to server rollups immediately List<String> agentRollups = AgentRollups.getAgentRollups(agentId); List<ResultSetFuture> futures = Lists.newArrayList(); int ttl = getTTL(); for (String agentRollup : agentRollups) { List<Trace.Attribute> attributes = header.getAttributeList(); if (header.getSlow()) { BoundStatement boundStatement = insertOverallSlowPoint.bind(); int i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setBool(i++, header.hasError()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setBool(i++, header.hasError()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); if (priorHeader != null) { boundStatement = deletePartialOverallSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialTransactionSlowPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setString(i++, priorHeader.getTransactionName()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialOverallSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); boundStatement = deletePartialTransactionSlowCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, priorHeader.getTransactionType()); boundStatement.setString(i++, priorHeader.getTransactionName()); boundStatement.setTimestamp(i++, new Date(priorHeader.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); futures.add(session.executeAsync(boundStatement)); } } // seems unnecessary to insert error info for partial traces // and this avoids having to clean up partial trace data when trace is complete if (header.hasError() && !header.getPartial()) { BoundStatement boundStatement = insertOverallErrorMessage.bind(); int i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorMessage.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallErrorPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorPoint.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setLong(i++, header.getDurationNanos()); boundStatement.setString(i++, header.getError().getMessage()); boundStatement.setString(i++, Strings.emptyToNull(header.getUser())); if (attributes.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(attributes)); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertOverallErrorCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); boundStatement = insertTransactionErrorCount.bind(); i = 0; boundStatement.setString(i++, agentRollup); boundStatement.setString(i++, header.getTransactionType()); boundStatement.setString(i++, header.getTransactionName()); boundStatement.setTimestamp(i++, new Date(header.getCaptureTime())); boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } for (Trace.Attribute attributeName : attributes) { traceAttributeNameDao.maybeUpdateLastCaptureTime(agentRollup, header.getTransactionType(), attributeName.getName(), futures); } } BoundStatement boundStatement = insertHeader.bind(); int i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(header.toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); for (int entryIndex = 0; entryIndex < trace.getEntryCount(); entryIndex++) { Trace.Entry entry = trace.getEntry(entryIndex); boundStatement = insertEntry.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setInt(i++, entryIndex); boundStatement.setInt(i++, entry.getDepth()); boundStatement.setLong(i++, entry.getStartOffsetNanos()); boundStatement.setLong(i++, entry.getDurationNanos()); boundStatement.setBool(i++, entry.getActive()); boundStatement.setString(i++, entry.getMessage()); List<Trace.DetailEntry> detailEntries = entry.getDetailEntryList(); if (detailEntries.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(detailEntries)); } List<StackTraceElement> location = entry.getLocationStackTraceElementList(); if (location.isEmpty()) { boundStatement.setToNull(i++); } else { boundStatement.setBytes(i++, Messages.toByteBuffer(location)); } if (entry.hasError()) { boundStatement.setBytes(i++, ByteBuffer.wrap(entry.getError().toByteArray())); } else { boundStatement.setToNull(i++); } boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } if (trace.hasMainThreadProfile()) { boundStatement = insertMainThreadProfile.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(trace.getMainThreadProfile().toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } if (trace.hasAuxThreadProfile()) { boundStatement = insertAuxThreadProfile.bind(); i = 0; boundStatement.setString(i++, agentId); boundStatement.setString(i++, traceId); boundStatement.setBytes(i++, ByteBuffer.wrap(trace.getAuxThreadProfile().toByteArray())); boundStatement.setInt(i++, ttl); futures.add(session.executeAsync(boundStatement)); } Futures.allAsList(futures).get(); } @Override public List<String> readTraceAttributeNames(String agentRollup, String transactionType) { return traceAttributeNameDao.getTraceAttributeNames(agentRollup, transactionType); } @Override public Result<TracePoint> readSlowPoints(String agentRollup, TraceQuery query, TracePointFilter filter, int limit) throws IOException { String transactionName = query.transactionName(); if (transactionName == null) { BoundStatement boundStatement = readOverallSlowPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, false); } else { BoundStatement boundStatement = readTransactionSlowPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, false); } } @Override public Result<TracePoint> readErrorPoints(String agentRollup, TraceQuery query, TracePointFilter filter, int limit) throws IOException { String transactionName = query.transactionName(); if (transactionName == null) { BoundStatement boundStatement = readOverallErrorPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, true); } else { BoundStatement boundStatement = readTransactionErrorPoint.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); ResultSet results = session.execute(boundStatement); return processPoints(results, filter, limit, true); } } @Override public long readSlowCount(String agentRollup, TraceQuery query) { String transactionName = query.transactionName(); if (transactionName == null) { ResultSet results = session.execute( "select count(*) from trace_tt_slow_count where agent_rollup = ?" + " and transaction_type = ? and capture_time > ?" + " and capture_time <= ?", agentRollup, query.transactionType(), query.from(), query.to()); return results.one().getLong(0); } else { ResultSet results = session.execute( "select count(*) from trace_tn_slow_count where agent_rollup = ?" + " and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?", agentRollup, query.transactionType(), transactionName, query.from(), query.to()); return results.one().getLong(0); } } @Override public long readErrorCount(String agentRollup, TraceQuery query) { String transactionName = query.transactionName(); if (transactionName == null) { ResultSet results = session.execute( "select count(*) from trace_tt_error_count where agent_rollup = ?" + " and transaction_type = ? and capture_time > ?" + " and capture_time <= ?", agentRollup, query.transactionType(), query.from(), query.to()); return results.one().getLong(0); } else { ResultSet results = session.execute( "select count(*) from trace_tn_error_count where agent_rollup = ?" + " and transaction_type = ? and transaction_name = ?" + " and capture_time > ? and capture_time <= ?", agentRollup, query.transactionType(), transactionName, query.from(), query.to()); return results.one().getLong(0); } } @Override public ErrorMessageResult readErrorMessages(String agentRollup, TraceQuery query, ErrorMessageFilter filter, long resolutionMillis, int limit) throws Exception { BoundStatement boundStatement; String transactionName = query.transactionName(); if (transactionName == null) { boundStatement = readOverallErrorMessage.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setTimestamp(2, new Date(query.from())); boundStatement.setTimestamp(3, new Date(query.to())); } else { boundStatement = readTransactionErrorMessage.bind(); boundStatement.setString(0, agentRollup); boundStatement.setString(1, query.transactionType()); boundStatement.setString(2, transactionName); boundStatement.setTimestamp(3, new Date(query.from())); boundStatement.setTimestamp(4, new Date(query.to())); } ResultSet results = session.execute(boundStatement); // rows are already in order by captureTime, so saving sort step by using linked hash map Map<Long, MutableLong> pointCounts = Maps.newLinkedHashMap(); Map<String, MutableLong> messageCounts = Maps.newHashMap(); for (Row row : results) { long captureTime = checkNotNull(row.getTimestamp(0)).getTime(); String errorMessage = checkNotNull(row.getString(1)); if (!matches(filter, errorMessage)) { continue; } long rollupCaptureTime = Utils.getRollupCaptureTime(captureTime, resolutionMillis); pointCounts.computeIfAbsent(rollupCaptureTime, k -> new MutableLong()).increment(); messageCounts.computeIfAbsent(errorMessage, k -> new MutableLong()).increment(); } List<ErrorMessagePoint> points = pointCounts.entrySet().stream() .map(e -> ImmutableErrorMessagePoint.of(e.getKey(), e.getValue().value)) .sorted(Comparator.comparingLong(ErrorMessagePoint::captureTime)) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<ErrorMessagePoint>toList()); List<ErrorMessageCount> counts = messageCounts.entrySet().stream() .map(e -> ImmutableErrorMessageCount.of(e.getKey(), e.getValue().value)) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<ErrorMessageCount>toList()); if (counts.size() <= limit) { return ImmutableErrorMessageResult.builder() .addAllPoints(points) .counts(new Result<>(counts, false)) .build(); } else { return ImmutableErrorMessageResult.builder() .addAllPoints(points) .counts(new Result<>(counts.subList(0, limit), true)) .build(); } } @Override public @Nullable HeaderPlus readHeaderPlus(String agentId, String traceId) throws InvalidProtocolBufferException { Trace.Header header = readHeader(agentId, traceId); if (header == null) { return null; } Existence entriesExistence = header.getEntryCount() == 0 ? Existence.NO : Existence.YES; Existence profileExistence = header.getMainThreadProfileSampleCount() == 0 && header.getAuxThreadProfileSampleCount() == 0 ? Existence.NO : Existence.YES; return ImmutableHeaderPlus.of(header, entriesExistence, profileExistence); } @Override public List<Trace.Entry> readEntries(String agentId, String traceId) throws IOException { BoundStatement boundStatement = readEntries.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); List<Trace.Entry> entries = Lists.newArrayList(); while (!results.isExhausted()) { Row row = results.one(); int i = 0; Trace.Entry.Builder entry = Trace.Entry.newBuilder() .setDepth(row.getInt(i++)) .setStartOffsetNanos(row.getLong(i++)) .setDurationNanos(row.getLong(i++)) .setActive(row.getBool(i++)) .setMessage(Strings.nullToEmpty(row.getString(i++))); ByteBuffer detailBytes = row.getBytes(i++); if (detailBytes != null) { entry.addAllDetailEntry( Messages.parseDelimitedFrom(detailBytes, Trace.DetailEntry.parser())); } ByteBuffer locationBytes = row.getBytes(i++); if (locationBytes != null) { entry.addAllLocationStackTraceElement(Messages.parseDelimitedFrom(locationBytes, Proto.StackTraceElement.parser())); } ByteBuffer errorBytes = row.getBytes(i++); if (errorBytes != null) { entry.setError(Trace.Error.parseFrom(ByteString.copyFrom(errorBytes))); } entries.add(entry.build()); } return entries; } @Override public @Nullable Profile readMainThreadProfile(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readMainThreadProfile.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Profile.parseFrom(ByteString.copyFrom(bytes)); } @Override public @Nullable Profile readAuxThreadProfile(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readAuxThreadProfile.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Profile.parseFrom(ByteString.copyFrom(bytes)); } private @Nullable Trace.Header readHeader(String agentId, String traceId) throws InvalidProtocolBufferException { BoundStatement boundStatement = readHeader.bind(); boundStatement.setString(0, agentId); boundStatement.setString(1, traceId); ResultSet results = session.execute(boundStatement); Row row = results.one(); if (row == null) { return null; } ByteBuffer bytes = checkNotNull(row.getBytes(0)); return Trace.Header.parseFrom(ByteString.copyFrom(bytes)); } private int getTTL() { return Ints.saturatedCast( HOURS.toSeconds(configRepository.getStorageConfig().traceExpirationHours())); } private static Result<TracePoint> processPoints(ResultSet results, TracePointFilter filter, int limit, boolean errorPoints) throws IOException { List<TracePoint> tracePoints = Lists.newArrayList(); for (Row row : results) { int i = 0; String agentId = checkNotNull(row.getString(i++)); String traceId = checkNotNull(row.getString(i++)); long captureTime = checkNotNull(row.getTimestamp(i++)).getTime(); long durationNanos = row.getLong(i++); boolean error = errorPoints ? true : row.getBool(i++); // headline is always non-null, except for old data prior to when headline column added String headline = Strings.nullToEmpty(row.getString(i++)); // error points are defined by having an error message, so safe to checkNotNull String errorMessage = errorPoints ? checkNotNull(row.getString(i++)) : ""; String user = Strings.nullToEmpty(row.getString(i++)); ByteBuffer attributeBytes = row.getBytes(i++); List<Trace.Attribute> attrs = Messages.parseDelimitedFrom(attributeBytes, Trace.Attribute.parser()); Map<String, List<String>> attributes = attrs.stream().collect( Collectors.toMap(Trace.Attribute::getName, Trace.Attribute::getValueList)); if (filter.matchesDuration(durationNanos) && filter.matchesHeadline(headline) && filter.matchesError(errorMessage) && filter.matchesUser(user) && filter.matchesAttributes(attributes)) { tracePoints.add(ImmutableTracePoint.builder() .agentId(agentId) .traceId(traceId) .captureTime(captureTime) .durationNanos(durationNanos) .error(error) .build()); } } // remove duplicates (partially stored traces) since there is (small) window between updated // insert (with new capture time) and the delete of prior insert (with prior capture time) Set<TraceKey> traceKeys = Sets.newHashSet(); ListIterator<TracePoint> i = tracePoints.listIterator(tracePoints.size()); while (i.hasPrevious()) { TracePoint trace = i.previous(); TraceKey traceKey = ImmutableTraceKey.of(trace.agentId(), trace.traceId()); if (!traceKeys.add(traceKey)) { i.remove(); } } // apply limit and re-sort if needed if (tracePoints.size() > limit) { tracePoints = tracePoints.stream() .sorted(Comparator.comparingLong(TracePoint::durationNanos).reversed()) .limit(limit) .sorted(Comparator.comparingLong(TracePoint::captureTime)) // explicit type on this line is needed for Checker Framework // see https://github.com/typetools/checker-framework/issues/531 .collect(Collectors.<TracePoint>toList()); return new Result<>(tracePoints, true); } else { return new Result<>(tracePoints, false); } } private static boolean matches(ErrorMessageFilter filter, String errorMessage) { String upper = errorMessage.toUpperCase(Locale.ENGLISH); for (String include : filter.includes()) { if (!upper.contains(include.toUpperCase(Locale.ENGLISH))) { return false; } } for (String exclude : filter.excludes()) { if (upper.contains(exclude.toUpperCase(Locale.ENGLISH))) { return false; } } return true; } private static String lowerSixBytesHex(long startTime) { long mask = 1L << 48; return Long.toHexString(mask | (startTime & (mask - 1))).substring(1); } @Value.Immutable @Styles.AllParameters interface TraceKey { String agentId(); String traceId(); } private static class MutableLong { private long value; private void increment() { value++; } } }
Fix ordering of error messages
server/src/main/java/org/glowroot/server/storage/TraceDao.java
Fix ordering of error messages
Java
apache-2.0
b5995c93977369a771cca887274d27268c8d7aee
0
pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript,pcingola/BigDataScript
package org.bds.run; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.bds.Bds; import org.bds.BdsParseArgs; import org.bds.Config; import org.bds.compile.BdsCompiler; import org.bds.compile.CompilerMessages; import org.bds.executioner.Executioner; import org.bds.executioner.Executioners; import org.bds.executioner.Executioners.ExecutionerType; import org.bds.lang.BdsNodeFactory; import org.bds.lang.ProgramUnit; import org.bds.lang.nativeFunctions.NativeLibraryFunctions; import org.bds.lang.nativeMethods.string.NativeLibraryString; import org.bds.lang.statement.FunctionDeclaration; import org.bds.lang.statement.Statement; import org.bds.lang.statement.VarDeclaration; import org.bds.lang.type.Types; import org.bds.scope.GlobalScope; import org.bds.symbol.GlobalSymbolTable; import org.bds.task.TaskDependecies; import org.bds.util.Timer; /** * Run a bds program * * @author pcingola */ public class BdsRun { public static boolean USE_VM = true; // Use VM public enum BdsAction { RUN, RUN_CHECKPOINT, ASSEMBLY, COMPILE, INFO_CHECKPOINT, TEST, CHECK_PID_REGEX } boolean debug; // debug mode boolean log; // Log everything (keep STDOUT, SDTERR and ExitCode files) boolean stackCheck; // Check stack size when thread finishes runnig (should be zero) boolean verbose; // Verbose mode int exitValue; String chekcpointRestoreFile; // Restore file String programFileName; // Program file name Config config; BdsAction bdsAction; BdsThread bdsThread; ProgramUnit programUnit; // Program (parsed nodes) List<String> programArgs; // Command line arguments for BigDataScript program public BdsRun() { bdsAction = BdsAction.RUN; programArgs = new ArrayList<>(); } public void addArg(String arg) { programArgs.add(arg); } /** * Print assembly code to STDOUT */ int assembly() { // Compile, abort on errors if (!compile()) return 1; try { System.out.println(programUnit.toAsm()); } catch (Throwable t) { if (verbose) t.printStackTrace(); return 1; } return 0; } /** * Check 'pidRegex' */ public void checkPidRegex() { // PID regex matcher String pidPatternStr = config.getPidRegex(""); if (pidPatternStr.isEmpty()) { System.err.println("Cannot find 'pidRegex' entry in config file."); System.exit(1); } Executioner executioner = Executioners.getInstance().get(ExecutionerType.CLUSTER); // Show pattern System.out.println("Matching pidRegex '" + pidPatternStr + "'"); // Read STDIN and check pattern try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String pid = executioner.parsePidLine(line); System.out.println("Input line:\t'" + line + "'\tMatched: '" + pid + "'"); } } catch (IOException e) { e.printStackTrace(); } executioner.kill(); // Kill executioner } /** * Compile program * @return True if compiled OK */ public boolean compile() { if (debug) Timer.showStdErr("Parsing"); BdsCompiler compiler = new BdsCompiler(programFileName); programUnit = compiler.compile(); // Show errors and warnings, if any if ((programUnit == null) && !CompilerMessages.get().isEmpty()) { System.err.println("Compiler messages:\n" + CompilerMessages.get()); } return programUnit != null; } public BdsAction getBdsAction() { return bdsAction; } public BdsThread getBdsThread() { return bdsThread; } public List<String> getProgramArgs() { return programArgs; } public ProgramUnit getProgramUnit() { return programUnit; } /** * Show information from a checkpoint file */ int infoCheckpoint() { // Load checkpoint file // TODO: LOAD FROM CHECKLPOINT !!!!!!!!!!!!! // for (BdsThread bdsThread : bdsThreads) // bdsThread.print(); return 0; } /** * Initialize before running or type-checking */ void initialize() { Types.reset(); // Reset node factory BdsNodeFactory.reset(); // Startup message if (log || debug) Timer.showStdErr(Bds.VERSION); // Global scope GlobalSymbolTable.reset(); GlobalScope.reset(); GlobalScope.get().initilaize(config); // Libraries initilaizeLibraries(); } /** * Initialize standard libraries */ void initilaizeLibraries() { if (debug) log("Initialize standard libraries."); // Native functions NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions(); if (debug) log("Native library:\n" + nativeLibraryFunctions); // Native library: String NativeLibraryString nativeLibraryString = new NativeLibraryString(); if (debug) log("Native library:\n" + nativeLibraryString); } void log(String msg) { Timer.showStdErr(getClass().getSimpleName() + ": " + msg); } /** * Run program */ public int run() { // Initialize initialize(); Executioners executioners = Executioners.getInstance(config); TaskDependecies.reset(); //--- // Run //--- switch (bdsAction) { case ASSEMBLY: exitValue = assembly(); break; case COMPILE: exitValue = compile() ? 0 : 1; break; case RUN_CHECKPOINT: exitValue = runCheckpoint(); break; case INFO_CHECKPOINT: exitValue = infoCheckpoint(); break; case TEST: exitValue = runTests(); break; case CHECK_PID_REGEX: checkPidRegex(); exitValue = 0; break; default: exitValue = runCompile(); // BdsCompiler & run } if (debug) Timer.showStdErr("Finished. Exit code: " + exitValue); //--- // Kill all executioners //--- for (Executioner executioner : executioners.getAll()) executioner.kill(); config.kill(); // Kill 'tail' and 'monitor' threads return exitValue; } /** * Restore from checkpoint and run */ int runCheckpoint() { // Load checkpoint file // TODO: REMOVE BdsSerializer // BdsSerializer bdsSerializer = new BdsSerializer(chekcpointRestoreFile, config); // List<BdsThread> bdsThreads = bdsSerializer.load(); BdsThread bdsThreadRoot; try { ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(chekcpointRestoreFile))); bdsThreadRoot = (BdsThread) in.readObject(); in.close(); } catch (Exception e) { throw new RuntimeException("Error while serializing to file '" + chekcpointRestoreFile + "'", e); } // Set main thread's programUnit running scope (mostly for debugging and test cases) // ProgramUnit's scope it the one before 'global' // BdsThread mainThread = bdsThreads.get(0); BdsThread mainThread = bdsThreadRoot; programUnit = mainThread.getProgramUnit(); // Set state and recover tasks List<BdsThread> bdsThreads = bdsThreadRoot.getBdsThreads(); bdsThreads.add(bdsThreadRoot); for (BdsThread bdsThread : bdsThreads) { if (bdsThread.isFinished()) { // Thread finished before serialization: Nothing to do } else { bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks } } // All set, run main thread return runThread(mainThread); } /** * BdsCompiler and run */ int runCompile() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Show script's automatic help message if (bdsParseArgs.isShowHelp()) { if (debug) Timer.showStdErr("Showing automaic 'help'"); HelpCreator hc = new HelpCreator(programUnit); System.out.println(hc); return 0; } if (USE_VM) { // USING VM throw new RuntimeException("UNIMPLEMENTED!!!!!!!!"); } else { // TODO: OLD STYLE // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) { Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); Timer.showStdErr("Running"); } int exitCode = runThread(bdsThread); } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); return exitCode; } /** * BdsCompiler and run */ int runTests() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (debug) Timer.showStdErr("Running tests"); ProgramUnit pu = bdsThread.getProgramUnit(); return runTests(pu); } /** * For each "test*()" function in ProgramUnit, create a thread * that executes the function's body */ int runTests(ProgramUnit progUnit) { // We need to execute all variable declarations in order to be able to use global vairables in 'test*()' functions" List<VarDeclaration> varDecls = programUnit.varDeclarations(false); List<FunctionDeclaration> testFuncs = progUnit.testsFunctions(); int exitCode = 0; int testOk = 0, testError = 0; for (FunctionDeclaration testFunc : testFuncs) { System.out.println(""); // Run each function int exitValTest = runTests(progUnit, testFunc, varDecls); // Show test result if (exitValTest == 0) { Timer.show("Test '" + testFunc.getFunctionName() + "': OK"); testOk++; } else { Timer.show("Test '" + testFunc.getFunctionName() + "': FAIL"); exitCode = 1; testError++; } } // Show results System.out.println(""); Timer.show("Totals"// + "\n OK : " + testOk // + "\n ERROR : " + testError // ); return exitCode; } /** * Run a single test function, return exit code */ int runTests(ProgramUnit progUnit, FunctionDeclaration testFunc, List<VarDeclaration> varDecls) { List<Statement> statements = new ArrayList<>(); // Add all variable declarations for (VarDeclaration varDecl : varDecls) statements.add(varDecl); // Note: We execute the function's body (not the function declaration) statements.add(testFunc.getStatement()); // Create a program unit having all variable declarations and the test function's statements ProgramUnit puTest = new ProgramUnit(progUnit, null); puTest.setStatements(statements.toArray(new Statement[0])); BdsThread bdsTestThread = new BdsThread(puTest, config); int exitValTest = runThread(bdsTestThread); return exitValTest; } /** * Run a thread */ int runThread(BdsThread bdsThread) { this.bdsThread = bdsThread; if (bdsThread.isFinished()) return 0; bdsThread.start(); try { bdsThread.join(); } catch (InterruptedException e) { // Nothing to do? // May be checkpoint? return 1; } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); // OK, we are done return bdsThread.getExitValue(); } public void setBdsAction(BdsAction bdsAction) { this.bdsAction = bdsAction; } public void setChekcpointRestoreFile(String chekcpointRestoreFile) { this.chekcpointRestoreFile = chekcpointRestoreFile; } public void setConfig(Config config) { this.config = config; } public void setDebug(boolean debug) { this.debug = debug; } public void setLog(boolean log) { this.log = log; } public void setProgramArgs(ArrayList<String> programArgs) { this.programArgs = programArgs; } public void setProgramFileName(String programFileName) { this.programFileName = programFileName; } public void setProgramUnit(ProgramUnit programUnit) { this.programUnit = programUnit; } public void setStackCheck(boolean stackCheck) { this.stackCheck = stackCheck; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
src/org/bds/run/BdsRun.java
package org.bds.run; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.bds.Bds; import org.bds.BdsParseArgs; import org.bds.Config; import org.bds.compile.BdsCompiler; import org.bds.compile.CompilerMessages; import org.bds.executioner.Executioner; import org.bds.executioner.Executioners; import org.bds.executioner.Executioners.ExecutionerType; import org.bds.lang.BdsNodeFactory; import org.bds.lang.ProgramUnit; import org.bds.lang.nativeFunctions.NativeLibraryFunctions; import org.bds.lang.nativeMethods.string.NativeLibraryString; import org.bds.lang.statement.FunctionDeclaration; import org.bds.lang.statement.Statement; import org.bds.lang.statement.VarDeclaration; import org.bds.lang.type.Types; import org.bds.scope.GlobalScope; import org.bds.symbol.GlobalSymbolTable; import org.bds.task.TaskDependecies; import org.bds.util.Timer; /** * Run a bds program * * @author pcingola */ public class BdsRun { public static boolean USE_VM = true; // Use VM public enum BdsAction { RUN, RUN_CHECKPOINT, ASSEMBLY, COMPILE, INFO_CHECKPOINT, TEST, CHECK_PID_REGEX } boolean debug; // debug mode boolean log; // Log everything (keep STDOUT, SDTERR and ExitCode files) boolean stackCheck; // Check stack size when thread finishes runnig (should be zero) boolean verbose; // Verbose mode int exitValue; String chekcpointRestoreFile; // Restore file String programFileName; // Program file name Config config; BdsAction bdsAction; BdsThread bdsThread; ProgramUnit programUnit; // Program (parsed nodes) List<String> programArgs; // Command line arguments for BigDataScript program public BdsRun() { bdsAction = BdsAction.RUN; programArgs = new ArrayList<>(); } public void addArg(String arg) { programArgs.add(arg); } /** * Print assembly code to STDOUT */ int assembly() { // Compile, abort on errors if (!compile()) return 1; try { System.out.println(programUnit.toAsm()); } catch (Throwable t) { if (verbose) t.printStackTrace(); return 1; } return 0; } /** * Check 'pidRegex' */ public void checkPidRegex() { // PID regex matcher String pidPatternStr = config.getPidRegex(""); if (pidPatternStr.isEmpty()) { System.err.println("Cannot find 'pidRegex' entry in config file."); System.exit(1); } Executioner executioner = Executioners.getInstance().get(ExecutionerType.CLUSTER); // Show pattern System.out.println("Matching pidRegex '" + pidPatternStr + "'"); // Read STDIN and check pattern try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = in.readLine()) != null) { String pid = executioner.parsePidLine(line); System.out.println("Input line:\t'" + line + "'\tMatched: '" + pid + "'"); } } catch (IOException e) { e.printStackTrace(); } executioner.kill(); // Kill executioner } /** * Compile program * @return True if compiled OK */ public boolean compile() { if (debug) Timer.showStdErr("Parsing"); BdsCompiler compiler = new BdsCompiler(programFileName); programUnit = compiler.compile(); // Show errors and warnings, if any if ((programUnit == null) && !CompilerMessages.get().isEmpty()) { System.err.println("Compiler messages:\n" + CompilerMessages.get()); } return programUnit != null; } public BdsAction getBdsAction() { return bdsAction; } public BdsThread getBdsThread() { return bdsThread; } public List<String> getProgramArgs() { return programArgs; } public ProgramUnit getProgramUnit() { return programUnit; } /** * Show information from a checkpoint file */ int infoCheckpoint() { // Load checkpoint file // TODO: LOAD FROM CHECKLPOINT !!!!!!!!!!!!! // for (BdsThread bdsThread : bdsThreads) // bdsThread.print(); return 0; } /** * Initialize before running or type-checking */ void initialize() { Types.reset(); // Reset node factory BdsNodeFactory.reset(); // Startup message if (log || debug) Timer.showStdErr(Bds.VERSION); // Global scope GlobalSymbolTable.reset(); GlobalScope.reset(); GlobalScope.get().initilaize(config); // Libraries initilaizeLibraries(); } /** * Initialize standard libraries */ void initilaizeLibraries() { if (debug) log("Initialize standard libraries."); // Native functions NativeLibraryFunctions nativeLibraryFunctions = new NativeLibraryFunctions(); if (debug) log("Native library:\n" + nativeLibraryFunctions); // Native library: String NativeLibraryString nativeLibraryString = new NativeLibraryString(); if (debug) log("Native library:\n" + nativeLibraryString); } void log(String msg) { Timer.showStdErr(getClass().getSimpleName() + ": " + msg); } /** * Run program */ public int run() { // Initialize initialize(); Executioners executioners = Executioners.getInstance(config); TaskDependecies.reset(); //--- // Run //--- switch (bdsAction) { case ASSEMBLY: exitValue = assembly(); break; case COMPILE: exitValue = compile() ? 0 : 1; break; case RUN_CHECKPOINT: exitValue = runCheckpoint(); break; case INFO_CHECKPOINT: exitValue = infoCheckpoint(); break; case TEST: exitValue = runTests(); break; case CHECK_PID_REGEX: checkPidRegex(); exitValue = 0; break; default: exitValue = runCompile(); // BdsCompiler & run } if (debug) Timer.showStdErr("Finished. Exit code: " + exitValue); //--- // Kill all executioners //--- for (Executioner executioner : executioners.getAll()) executioner.kill(); config.kill(); // Kill 'tail' and 'monitor' threads return exitValue; } /** * Restore from checkpoint and run */ int runCheckpoint() { // Load checkpoint file // TODO: REMOVE BdsSerializer // BdsSerializer bdsSerializer = new BdsSerializer(chekcpointRestoreFile, config); // List<BdsThread> bdsThreads = bdsSerializer.load(); BdsThread bdsThreadRoot; try { ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(new FileInputStream(chekcpointRestoreFile))); bdsThreadRoot = (BdsThread) in.readObject(); in.close(); } catch (Exception e) { throw new RuntimeException("Error while serializing to file '" + chekcpointRestoreFile + "'", e); } // Set main thread's programUnit running scope (mostly for debugging and test cases) // ProgramUnit's scope it the one before 'global' // BdsThread mainThread = bdsThreads.get(0); BdsThread mainThread = bdsThreadRoot; programUnit = mainThread.getProgramUnit(); // Set state and recover tasks List<BdsThread> bdsThreads = bdsThreadRoot.getBdsThreads(); bdsThreads.add(bdsThreadRoot); for (BdsThread bdsThread : bdsThreads) { if (bdsThread.isFinished()) { // Thread finished before serialization: Nothing to do } else { bdsThread.setRunState(RunState.CHECKPOINT_RECOVER); // Set run state to recovery bdsThread.restoreUnserializedTasks(); // Re-execute or add tasks } } // All set, run main thread return runThread(mainThread); } /** * BdsCompiler and run */ int runCompile() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Show script's automatic help message if (bdsParseArgs.isShowHelp()) { if (debug) Timer.showStdErr("Showing automaic 'help'"); HelpCreator hc = new HelpCreator(programUnit); System.out.println(hc); return 0; } // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) { Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); Timer.showStdErr("Running"); } int exitCode = runThread(bdsThread); // Check stack if (stackCheck) bdsThread.sanityCheckStack(); return exitCode; } /** * BdsCompiler and run */ int runTests() { // Compile, abort on errors if (!compile()) return 1; if (debug) Timer.showStdErr("Initializing"); BdsParseArgs bdsParseArgs = new BdsParseArgs(programUnit, programArgs); bdsParseArgs.setDebug(debug); bdsParseArgs.parse(); // Run the program BdsThread bdsThread = new BdsThread(programUnit, config); if (debug) Timer.showStdErr("Process ID: " + bdsThread.getBdsThreadId()); if (debug) Timer.showStdErr("Running tests"); ProgramUnit pu = bdsThread.getProgramUnit(); return runTests(pu); } /** * For each "test*()" function in ProgramUnit, create a thread * that executes the function's body */ int runTests(ProgramUnit progUnit) { // We need to execute all variable declarations in order to be able to use global vairables in 'test*()' functions" List<VarDeclaration> varDecls = programUnit.varDeclarations(false); List<FunctionDeclaration> testFuncs = progUnit.testsFunctions(); int exitCode = 0; int testOk = 0, testError = 0; for (FunctionDeclaration testFunc : testFuncs) { System.out.println(""); // Run each function int exitValTest = runTests(progUnit, testFunc, varDecls); // Show test result if (exitValTest == 0) { Timer.show("Test '" + testFunc.getFunctionName() + "': OK"); testOk++; } else { Timer.show("Test '" + testFunc.getFunctionName() + "': FAIL"); exitCode = 1; testError++; } } // Show results System.out.println(""); Timer.show("Totals"// + "\n OK : " + testOk // + "\n ERROR : " + testError // ); return exitCode; } /** * Run a single test function, return exit code */ int runTests(ProgramUnit progUnit, FunctionDeclaration testFunc, List<VarDeclaration> varDecls) { List<Statement> statements = new ArrayList<>(); // Add all variable declarations for (VarDeclaration varDecl : varDecls) statements.add(varDecl); // Note: We execute the function's body (not the function declaration) statements.add(testFunc.getStatement()); // Create a program unit having all variable declarations and the test function's statements ProgramUnit puTest = new ProgramUnit(progUnit, null); puTest.setStatements(statements.toArray(new Statement[0])); BdsThread bdsTestThread = new BdsThread(puTest, config); int exitValTest = runThread(bdsTestThread); return exitValTest; } /** * Run a thread */ int runThread(BdsThread bdsThread) { this.bdsThread = bdsThread; if (bdsThread.isFinished()) return 0; bdsThread.start(); try { bdsThread.join(); } catch (InterruptedException e) { // Nothing to do? // May be checkpoint? return 1; } // Check stack if (stackCheck) bdsThread.sanityCheckStack(); // OK, we are done return bdsThread.getExitValue(); } public void setBdsAction(BdsAction bdsAction) { this.bdsAction = bdsAction; } public void setChekcpointRestoreFile(String chekcpointRestoreFile) { this.chekcpointRestoreFile = chekcpointRestoreFile; } public void setConfig(Config config) { this.config = config; } public void setDebug(boolean debug) { this.debug = debug; } public void setLog(boolean log) { this.log = log; } public void setProgramArgs(ArrayList<String> programArgs) { this.programArgs = programArgs; } public void setProgramFileName(String programFileName) { this.programFileName = programFileName; } public void setProgramUnit(ProgramUnit programUnit) { this.programUnit = programUnit; } public void setStackCheck(boolean stackCheck) { this.stackCheck = stackCheck; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
Project updated
src/org/bds/run/BdsRun.java
Project updated
Java
apache-2.0
a23149ba632831e6feb1978832a5917c3d46b75b
0
atoulme/xmlrpc
package org.apache.xmlrpc; /* * The Apache Software License, Version 1.1 * * * Copyright(c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation(http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "XML-RPC" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.EmptyStackException; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; /** * A multithreaded, reusable XML-RPC server object. The name may be misleading * because this does not open any server sockets. Instead it is fed by passing * an XML-RPC input stream to the execute method. If you want to open a * HTTP listener, use the WebServer class instead. * * @author <a href="mailto:[email protected]">Hannes Wallnoefer</a> * @author <a href="mailto:[email protected]">Daniel Rall</a> * @version $Id$ */ public class XmlRpcServer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Hashtable handlers; private Stack pool; private int workers; /** * Construct a new XML-RPC server. You have to register handlers * to make it do something useful. */ public XmlRpcServer() { handlers = new Hashtable(); pool = new Stack(); workers = 0; } /** * Register a handler object with this name. Methods of this * objects will be callable over XML-RPC as * "handlername.methodname". For more information about XML-RPC * handlers see the <a href="../index.html#1a">main documentation * page</a>. * * @param handlername The name to identify the handler by. * @param handler The handler itself. */ public void addHandler(String handlername, Object handler) { if (handler instanceof XmlRpcHandler || handler instanceof AuthenticatedXmlRpcHandler) { handlers.put(handlername, handler); } else if (handler != null) { handlers.put(handlername, new Invoker(handler)); } } /** * Remove a handler object that was previously registered with * this server. * * @param handlername The name identifying the handler to remove. */ public void removeHandler(String handlername) { handlers.remove(handlername); } /** * Parse the request and execute the handler method, if one is * found. Returns the result as XML. The calling Java code * doesn't need to know whether the call was successful or not * since this is all packed into the response. */ public byte[] execute(InputStream is) { return execute(is, null, null); } /** * Parse the request and execute the handler method, if one is * found. If the invoked handler is AuthenticatedXmlRpcHandler, * use the credentials to authenticate the user. */ public byte[] execute(InputStream is, String user, String password) { Worker worker = getWorker(); byte[] retval = worker.execute(is, user, password); pool.push(worker); return retval; } /** * * @return */ private final Worker getWorker() { try { return(Worker) pool.pop(); } catch(EmptyStackException x) { int maxThreads = XmlRpc.getMaxThreads(); if (workers < maxThreads) { workers += 1; if (workers >= maxThreads * .95) { System.err.println("95% of XML-RPC server threads in use"); } return new Worker(); } throw new RuntimeException("System overload"); } } /** * Performs streaming, parsing, and handler execution. * Implementation is not thread-safe. */ class Worker extends XmlRpc { private Vector inParams; private ByteArrayOutputStream buffer; private XmlWriter writer; /** * Creates a new instance. */ protected Worker() { inParams = new Vector(); buffer = new ByteArrayOutputStream(); } /** * Given a request for the server, generates a response. */ public byte[] execute(InputStream is, String user, String password) { try { // Do the work return executeInternal(is, user, password); } finally { // Release most of our resources buffer.reset(); inParams.removeAllElements(); } } /** * * @param is * @param user * @param password * @return */ private byte[] executeInternal(InputStream is, String user, String password) { byte[] result; long now = 0; if (XmlRpc.debug) { now = System.currentTimeMillis(); } try { parse(is); if (XmlRpc.debug) { System.err.println("method name: " + methodName); System.err.println("inparams: " + inParams); } // check for errors from the XML parser if (errorLevel > NONE) { throw new Exception(errorMsg); } Object handler = null; String handlerName = null; int dot = methodName.lastIndexOf('.'); if (dot > -1) { handlerName = methodName.substring(0, dot); handler = handlers.get(handlerName); if (handler != null) { methodName = methodName.substring(dot + 1); } } if (handler == null) { handler = handlers.get("$default"); } if (handler == null) { if (dot > -1) { throw new Exception("RPC handler object \"" + handlerName + "\" not found and no default " + "handler registered."); } else { throw new Exception("RPC handler object not found for \"" + methodName + "\": no default handler registered."); } } Object outParam; if (handler instanceof AuthenticatedXmlRpcHandler) { outParam =((AuthenticatedXmlRpcHandler) handler) .execute(methodName, inParams, user, password); } else { outParam =((XmlRpcHandler) handler) .execute(methodName, inParams); } if (XmlRpc.debug) { System.err.println("outparam = " + outParam); } writer = new XmlWriter(buffer); writeResponse(outParam, writer); writer.flush(); result = buffer.toByteArray(); } catch(Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } // Ensure that if there is anything in the buffer, it // is cleared before continuing with the writing of exceptions. // It is possible that something is in the buffer // if there were an exception during the writeResponse() // call above. buffer.reset(); writer = null; try { writer = new XmlWriter(buffer); } catch(UnsupportedEncodingException encx) { System.err.println("XmlRpcServer attempted to use " + "unsupported encoding: " + encx); // NOTE: If we weren't already using the default // encoding, we could try it here. } catch(IOException iox) { System.err.println("XmlRpcServer experienced I/O error " + "writing error response: " + iox); } String message = x.toString(); // Retrieve XmlRpcException error code(if possible). int code = x instanceof XmlRpcException ? ((XmlRpcException) x).code : 0; try { writeError(code, message, writer); writer.flush(); } catch(Exception e) { // Unlikely to occur, as we just sent a struct // with an int and a string. System.err.println("Unable to send error response to " + "client: " + e); } // If we were able to create a XmlWriter, we should // have a response. if (writer != null) { result = buffer.toByteArray(); } else { result = EMPTY_BYTE_ARRAY; } } finally { if (writer != null) { try { writer.close(); } catch(IOException iox) { // This is non-fatal, but worth logging a // warning for. System.err.println("Exception closing output stream: " + iox); } } } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " millis in request"); } return result; } /** * Called when an object to be added to the argument list has * been parsed. */ void objectParsed(Object what) { inParams.addElement(what); } /** * Writes an XML-RPC response to the XML writer. */ void writeResponse(Object param, XmlWriter writer) throws XmlRpcException, IOException { writer.startElement("methodResponse"); // if (param == null) param = ""; // workaround for Frontier bug writer.startElement("params"); writer.startElement("param"); writer.writeObject(param); writer.endElement("param"); writer.endElement("params"); writer.endElement("methodResponse"); } /** * Writes an XML-RPC error response to the XML writer. */ void writeError(int code, String message, XmlWriter writer) throws XmlRpcException, IOException { // System.err.println("error: "+message); Hashtable h = new Hashtable(); h.put("faultCode", new Integer(code)); h.put("faultString", message); writer.startElement("methodResponse"); writer.startElement("fault"); writer.writeObject(h); writer.endElement("fault"); writer.endElement("methodResponse"); } } // end of inner class Worker } // XmlRpcServer /** * Introspects handlers using Java Reflection to call methods matching * a XML-RPC call. */ class Invoker implements XmlRpcHandler { private Object invokeTarget; private Class targetClass; public Invoker(Object target) { invokeTarget = target; targetClass = (invokeTarget instanceof Class) ? (Class) invokeTarget : invokeTarget.getClass(); if (XmlRpc.debug) { System.err.println("Target object is " + targetClass); } } /** * main method, sucht methode in object, wenn gefunden dann aufrufen. */ public Object execute(String methodName, Vector params) throws Exception { // Array mit Classtype bilden, ObjectAry mit Values bilden Class[] argClasses = null; Object[] argValues = null; if (params != null) { argClasses = new Class[params.size()]; argValues = new Object[params.size()]; for (int i = 0; i < params.size(); i++) { argValues[i] = params.elementAt(i); if (argValues[i] instanceof Integer) { argClasses[i] = Integer.TYPE; } else if (argValues[i] instanceof Double) { argClasses[i] = Double.TYPE; } else if (argValues[i] instanceof Boolean) { argClasses[i] = Boolean.TYPE; } else { argClasses[i] = argValues[i].getClass(); } } } // Methode da ? Method method = null; if (XmlRpc.debug) { System.err.println("Searching for method: " + methodName); for (int i = 0; i < argClasses.length; i++) { System.err.println("Parameter " + i + ": " + argClasses[i] + " = " + argValues[i]); } } try { method = targetClass.getMethod(methodName, argClasses); } // Wenn nicht da dann entsprechende Exception returnen catch(NoSuchMethodException nsm_e) { throw nsm_e; } catch(SecurityException s_e) { throw s_e; } // Our policy is to make all public methods callable except // the ones defined in java.lang.Object. if (method.getDeclaringClass() == Object.class) { throw new XmlRpcException(0, "Invoker can't call methods " + "defined in java.lang.Object"); } // invoke Object returnValue = null; try { returnValue = method.invoke(invokeTarget, argValues); } catch(IllegalAccessException iacc_e) { throw iacc_e; } catch(IllegalArgumentException iarg_e) { throw iarg_e; } catch(InvocationTargetException it_e) { if (XmlRpc.debug) { it_e.getTargetException().printStackTrace(); } // check whether the thrown exception is XmlRpcException Throwable t = it_e.getTargetException(); if (t instanceof XmlRpcException) { throw (XmlRpcException) t; } // It is some other exception throw new Exception(t.toString()); } if (returnValue == null && method.getReturnType() == Void.TYPE) { // Not supported by the spec. throw new IllegalArgumentException ("void return types for handler methods not supported"); } return returnValue; } }
src/java/org/apache/xmlrpc/XmlRpcServer.java
package org.apache.xmlrpc; /* * The Apache Software License, Version 1.1 * * * Copyright(c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation(http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "XML-RPC" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.EmptyStackException; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; /** * A multithreaded, reusable XML-RPC server object. The name may be misleading * because this does not open any server sockets. Instead it is fed by passing * an XML-RPC input stream to the execute method. If you want to open a * HTTP listener, use the WebServer class instead. * * @author <a href="mailto:[email protected]">Hannes Wallnoefer</a> * @author <a href="mailto:[email protected]">Daniel Rall</a> * @version $Id$ */ public class XmlRpcServer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private Hashtable handlers; private Stack pool; private int workers; /** * Construct a new XML-RPC server. You have to register handlers * to make it do something useful. */ public XmlRpcServer() { handlers = new Hashtable(); pool = new Stack(); workers = 0; } /** * Register a handler object with this name. Methods of this * objects will be callable over XML-RPC as * "handlername.methodname". For more information about XML-RPC * handlers see the <a href="../index.html#1a">main documentation * page</a>. * * @param handlername The name to identify the handler by. * @param handler The handler itself. */ public void addHandler(String handlername, Object handler) { if (handler instanceof XmlRpcHandler || handler instanceof AuthenticatedXmlRpcHandler) { handlers.put(handlername, handler); } else if (handler != null) { handlers.put(handlername, new Invoker(handler)); } } /** * Remove a handler object that was previously registered with * this server. * * @param handlername The name identifying the handler to remove. */ public void removeHandler(String handlername) { handlers.remove(handlername); } /** * Parse the request and execute the handler method, if one is * found. Returns the result as XML. The calling Java code * doesn't need to know whether the call was successful or not * since this is all packed into the response. */ public byte[] execute(InputStream is) { return execute(is, null, null); } /** * Parse the request and execute the handler method, if one is * found. If the invoked handler is AuthenticatedXmlRpcHandler, * use the credentials to authenticate the user. */ public byte[] execute(InputStream is, String user, String password) { Worker worker = getWorker(); byte[] retval = worker.execute(is, user, password); pool.push(worker); return retval; } /** * * @return */ private final Worker getWorker() { try { return(Worker) pool.pop(); } catch(EmptyStackException x) { int maxThreads = XmlRpc.getMaxThreads(); if (workers < maxThreads) { workers += 1; if (workers >= maxThreads * .95) { System.err.println("95% of XML-RPC server threads in use"); } return new Worker(); } throw new RuntimeException("System overload"); } } /** * Performs streaming, parsing, and handler execution. * Implementation is not thread-safe. */ class Worker extends XmlRpc { private Vector inParams; private ByteArrayOutputStream buffer; private XmlWriter writer; /** * Creates a new instance. */ protected Worker() { inParams = new Vector(); buffer = new ByteArrayOutputStream(); } /** * Given a request for the server, generates a response. */ public byte[] execute(InputStream is, String user, String password) { try { // Do the work return executeInternal(is, user, password); } finally { // Release most of our resources buffer.reset(); inParams.removeAllElements(); } } /** * * @param is * @param user * @param password * @return */ private byte[] executeInternal(InputStream is, String user, String password) { byte[] result; long now = 0; if (XmlRpc.debug) { now = System.currentTimeMillis(); } try { parse(is); if (XmlRpc.debug) { System.err.println("method name: " + methodName); System.err.println("inparams: " + inParams); } // check for errors from the XML parser if (errorLevel > NONE) { throw new Exception(errorMsg); } Object handler = null; String handlerName = null; int dot = methodName.lastIndexOf('.'); if (dot > -1) { handlerName = methodName.substring(0, dot); handler = handlers.get(handlerName); if (handler != null) { methodName = methodName.substring(dot + 1); } } if (handler == null) { handler = handlers.get("$default"); } if (handler == null) { if (dot > -1) { throw new Exception("RPC handler object \"" + handlerName + "\" not found and no default " + "handler registered."); } else { throw new Exception("RPC handler object not found for \"" + methodName + "\": no default handler registered."); } } Object outParam; if (handler instanceof AuthenticatedXmlRpcHandler) { outParam =((AuthenticatedXmlRpcHandler) handler) .execute(methodName, inParams, user, password); } else { outParam =((XmlRpcHandler) handler) .execute(methodName, inParams); } if (XmlRpc.debug) { System.err.println("outparam = " + outParam); } writer = new XmlWriter(buffer); writeResponse(outParam, writer); writer.flush(); result = buffer.toByteArray(); } catch(Exception x) { if (XmlRpc.debug) { x.printStackTrace(); } // Ensure that if there is anything in the buffer, it // is cleared before continuing with the writing of exceptions. // It is possible that something is in the buffer // if there were an exception during the writeResponse() // call above. buffer.reset(); writer = null; try { writer = new XmlWriter(buffer); } catch(UnsupportedEncodingException encx) { System.err.println("XmlRpcServer attempted to use " + "unsupported encoding: " + encx); // NOTE: If we weren't already using the default // encoding, we could try it here. } catch(IOException iox) { System.err.println("XmlRpcServer experienced I/O error " + "writing error response: " + iox); } String message = x.toString(); // Retrieve XmlRpcException error code(if possible). int code = x instanceof XmlRpcException ? ((XmlRpcException) x).code : 0; try { writeError(code, message, writer); writer.flush(); } catch(Exception e) { // Unlikely to occur, as we just sent a struct // with an int and a string. System.err.println("Unable to send error response to " + "client: " + e); } // If we were able to create a XmlWriter, we should // have a response. if (writer != null) { result = buffer.toByteArray(); } else { result = EMPTY_BYTE_ARRAY; } } finally { if (writer != null) { try { writer.close(); } catch(IOException iox) { // This is non-fatal, but worth logging a // warning for. System.err.println("Exception closing output stream: " + iox); } } } if (XmlRpc.debug) { System.err.println("Spent " + (System.currentTimeMillis() - now) + " millis in request"); } return result; } /** * Called when an object to be added to the argument list has * been parsed. */ void objectParsed(Object what) { inParams.addElement(what); } /** * Writes an XML-RPC response to the XML writer. */ void writeResponse(Object param, XmlWriter writer) throws XmlRpcException, IOException { writer.startElement("methodResponse"); // if (param == null) param = ""; // workaround for Frontier bug writer.startElement("params"); writer.startElement("param"); writer.writeObject(param); writer.endElement("param"); writer.endElement("params"); writer.endElement("methodResponse"); } /** * Writes an XML-RPC error response to the XML writer. */ void writeError(int code, String message, XmlWriter writer) throws XmlRpcException, IOException { // System.err.println("error: "+message); Hashtable h = new Hashtable(); h.put("faultCode", new Integer(code)); h.put("faultString", message); writer.startElement("methodResponse"); writer.startElement("fault"); writer.writeObject(h); writer.endElement("fault"); writer.endElement("methodResponse"); } } // end of inner class Worker } // XmlRpcServer /** * Introspects handlers using Java Reflection to call methods matching * a XML-RPC call. */ class Invoker implements XmlRpcHandler { private Object invokeTarget; private Class targetClass; public Invoker(Object target) { invokeTarget = target; targetClass = (invokeTarget instanceof Class) ? (Class) invokeTarget : invokeTarget.getClass(); if (XmlRpc.debug) { System.err.println("Target object is " + targetClass); } } /** * main method, sucht methode in object, wenn gefunden dann aufrufen. */ public Object execute(String methodName, Vector params) throws Exception { // Array mit Classtype bilden, ObjectAry mit Values bilden Class[] argClasses = null; Object[] argValues = null; if (params != null) { argClasses = new Class[params.size()]; argValues = new Object[params.size()]; for (int i = 0; i < params.size(); i++) { argValues[i] = params.elementAt(i); if (argValues[i] instanceof Integer) { argClasses[i] = Integer.TYPE; } else if (argValues[i] instanceof Double) { argClasses[i] = Double.TYPE; } else if (argValues[i] instanceof Boolean) { argClasses[i] = Boolean.TYPE; } else { argClasses[i] = argValues[i].getClass(); } } } // Methode da ? Method method = null; if (XmlRpc.debug) { System.err.println("Searching for method: " + methodName); for (int i = 0; i < argClasses.length; i++) { System.err.println("Parameter " + i + ": " + argClasses[i] + " = " + argValues[i]); } } try { method = targetClass.getMethod(methodName, argClasses); } // Wenn nicht da dann entsprechende Exception returnen catch(NoSuchMethodException nsm_e) { throw nsm_e; } catch(SecurityException s_e) { throw s_e; } // Our policy is to make all public methods callable except // the ones defined in java.lang.Object. if (method.getDeclaringClass() == Object.class) { throw new XmlRpcException(0, "Invoker can't call methods " + "defined in java.lang.Object"); } // invoke Object returnValue = null; try { returnValue = method.invoke(invokeTarget, argValues); } catch(IllegalAccessException iacc_e) { throw iacc_e; } catch(IllegalArgumentException iarg_e) { throw iarg_e; } catch(InvocationTargetException it_e) { if (XmlRpc.debug) { it_e.getTargetException().printStackTrace(); } // check whether the thrown exception is XmlRpcException Throwable t = it_e.getTargetException(); if (t instanceof XmlRpcException) { throw (XmlRpcException) t; } // It is some other exception throw new Exception(t.toString()); } return returnValue; } }
Invoker.execute(): Added check for unsupported void return type on handler methods. The need for better error reporting for this snafu was pointed out on the user list by Dejan Bosanace <[email protected]>.
src/java/org/apache/xmlrpc/XmlRpcServer.java
Invoker.execute(): Added check for unsupported void return type on handler methods. The need for better error reporting for this snafu was pointed out on the user list by Dejan Bosanace <[email protected]>.
Java
apache-2.0
96c7b50e75cff5c890793be71d26a380c9ebb15a
0
gocd/gocd,ketan/gocd,gocd/gocd,GaneshSPatil/gocd,marques-work/gocd,GaneshSPatil/gocd,ketan/gocd,GaneshSPatil/gocd,Skarlso/gocd,marques-work/gocd,gocd/gocd,marques-work/gocd,ketan/gocd,Skarlso/gocd,Skarlso/gocd,GaneshSPatil/gocd,Skarlso/gocd,gocd/gocd,gocd/gocd,gocd/gocd,marques-work/gocd,marques-work/gocd,ketan/gocd,marques-work/gocd,GaneshSPatil/gocd,Skarlso/gocd,ketan/gocd,GaneshSPatil/gocd,Skarlso/gocd,ketan/gocd
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.agent; import com.google.gson.Gson; import com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClient; import com.thoughtworks.go.config.DefaultAgentRegistry; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.JobResult; import com.thoughtworks.go.domain.JobState; import com.thoughtworks.go.remote.AgentInstruction; import com.thoughtworks.go.remote.BuildRepositoryRemote; import com.thoughtworks.go.remote.Serialization; import com.thoughtworks.go.remote.request.*; import com.thoughtworks.go.remote.work.Work; import com.thoughtworks.go.server.service.AgentRuntimeInfo; import com.thoughtworks.go.util.URLService; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; 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.List; import static com.thoughtworks.go.CurrentGoCDVersion.docsUrl; import static com.thoughtworks.go.agent.ResponseHelpers.readBodyAsString; import static com.thoughtworks.go.agent.ResponseHelpers.readBodyAsStringOrElse; import static java.lang.String.format; @Component public class RemotingClient implements BuildRepositoryRemote { private static final Logger LOG = LoggerFactory.getLogger(RemotingClient.class); private static final String UUID_HEADER = "X-Agent-GUID"; private static final String AUTH_HEADER = "Authorization"; private static final Gson GSON = Serialization.instance(); private final GoAgentServerHttpClient client; private final DefaultAgentRegistry agent; private final URLService urls; @Autowired public RemotingClient(GoAgentServerHttpClient client, DefaultAgentRegistry agent, URLService urls) { this.client = client; this.agent = agent; this.urls = urls; } @Override public AgentInstruction ping(AgentRuntimeInfo info) { return GSON.fromJson(post("ping", new PingRequest(info)), AgentInstruction.class); } @Override public Work getWork(AgentRuntimeInfo info) { return GSON.fromJson(post("get_work", new GetWorkRequest(info)), Work.class); } @Override public void reportCurrentStatus(AgentRuntimeInfo info, JobIdentifier jobId, JobState state) { post("report_current_status", new ReportCurrentStatusRequest(info, jobId, state)); } @Override public void reportCompleting(AgentRuntimeInfo info, JobIdentifier jobId, JobResult result) { post("report_completing", new ReportCompleteStatusRequest(info, jobId, result)); } @Override public void reportCompleted(AgentRuntimeInfo info, JobIdentifier jobId, JobResult result) { post("report_completed", new ReportCompleteStatusRequest(info, jobId, result)); } @Override public boolean isIgnored(AgentRuntimeInfo info, JobIdentifier jobId) { // Boolean.parseBoolean is JSON compatible for this specific case, but probably faster/simpler than Gson return Boolean.parseBoolean(post("is_ignored", new IsIgnoredRequest(info, jobId))); } @Override public String getCookie(AgentRuntimeInfo info) { return GSON.fromJson(post("get_cookie", new GetCookieRequest(info)), String.class); } private String post(final String action, final AgentRequest payload) { try { try (CloseableHttpResponse response = client.execute( injectCredentials( postRequestFor(action, payload) ))) { validateResponse(response, action); return readBodyAsString(response); } } catch (IOException e) { throw new RuntimeException(e); } } private HttpRequestBase injectCredentials(final HttpRequestBase request) { request.setHeader(UUID_HEADER, agent.uuid()); request.setHeader(AUTH_HEADER, agent.token()); return request; } private void validateResponse(final HttpResponse response, final String action) throws IOException { final StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 500) { logFailure(response, action); throw new ClientProtocolException( format("The server returned an error with status code %d (%s); please check the server logs for the corresponding error.", status.getStatusCode(), status.getReasonPhrase()) ); } if (status.getStatusCode() >= 400) { logFailure(response, action); throw new ClientProtocolException(String.join("\n - ", List.of( format("The server returned status code %d. Possible reasons include:", status.getStatusCode()), "This agent has been deleted from the configuration", "This agent is pending approval", "There is possibly a reverse proxy (or load balancer) that has been misconfigured. See " + docsUrl("/installation/configure-reverse-proxy.html#agents-and-reverse-proxies") + " for details." ))); } if (status.getStatusCode() >= 300) { throw new NoHttpResponseException(format("Did not receive successful HTTP response: status code = %d, status message = [%s]", status.getStatusCode(), status.getReasonPhrase())); } } private HttpRequestBase postRequestFor(String action, AgentRequest payload) { final HttpPost request = new HttpPost(urls.remotingUrlFor(action)); request.addHeader("Accept", "application/vnd.go.cd+json"); request.setEntity(new StringEntity(GSON.toJson(payload), ContentType.APPLICATION_JSON)); return request; } private void logFailure(final HttpResponse response, final String action) { final StatusLine status = response.getStatusLine(); final String body = readBodyAsStringOrElse(response, "<ERROR: UNABLE TO READ RESPONSE BODY>"); LOG.error(format("Server responded to action `%s` with: status[%d %s], body[%s]", action, status.getStatusCode(), status.getReasonPhrase(), body)); } }
agent/src/main/java/com/thoughtworks/go/agent/RemotingClient.java
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.agent; import com.google.gson.Gson; import com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClient; import com.thoughtworks.go.config.DefaultAgentRegistry; import com.thoughtworks.go.domain.JobIdentifier; import com.thoughtworks.go.domain.JobResult; import com.thoughtworks.go.domain.JobState; import com.thoughtworks.go.remote.AgentInstruction; import com.thoughtworks.go.remote.BuildRepositoryRemote; import com.thoughtworks.go.remote.Serialization; import com.thoughtworks.go.remote.request.*; import com.thoughtworks.go.remote.work.Work; import com.thoughtworks.go.server.service.AgentRuntimeInfo; import com.thoughtworks.go.util.URLService; import org.apache.http.HttpResponse; import org.apache.http.NoHttpResponseException; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; 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.List; import static com.thoughtworks.go.CurrentGoCDVersion.docsUrl; import static com.thoughtworks.go.agent.ResponseHelpers.readBodyAsString; import static com.thoughtworks.go.agent.ResponseHelpers.readBodyAsStringOrElse; import static java.lang.String.format; @Component public class RemotingClient implements BuildRepositoryRemote { private static final Logger LOG = LoggerFactory.getLogger(RemotingClient.class); private static final String UUID_HEADER = "X-Agent-GUID"; private static final String AUTH_HEADER = "Authorization"; private static final Gson GSON = Serialization.instance(); private final GoAgentServerHttpClient client; private final DefaultAgentRegistry agent; private final URLService urls; @Autowired public RemotingClient(GoAgentServerHttpClient client, DefaultAgentRegistry agent, URLService urls) { this.client = client; this.agent = agent; this.urls = urls; } @Override public AgentInstruction ping(AgentRuntimeInfo info) { return GSON.fromJson(post("ping", new PingRequest(info)), AgentInstruction.class); } @Override public Work getWork(AgentRuntimeInfo info) { return GSON.fromJson(post("get_work", new GetWorkRequest(info)), Work.class); } @Override public void reportCurrentStatus(AgentRuntimeInfo info, JobIdentifier jobId, JobState state) { post("report_current_status", new ReportCurrentStatusRequest(info, jobId, state)); } @Override public void reportCompleting(AgentRuntimeInfo info, JobIdentifier jobId, JobResult result) { post("report_completing", new ReportCompleteStatusRequest(info, jobId, result)); } @Override public void reportCompleted(AgentRuntimeInfo info, JobIdentifier jobId, JobResult result) { post("report_completed", new ReportCompleteStatusRequest(info, jobId, result)); } @Override public boolean isIgnored(AgentRuntimeInfo info, JobIdentifier jobId) { return Boolean.parseBoolean(post("is_ignored", new IsIgnoredRequest(info, jobId))); } @Override public String getCookie(AgentRuntimeInfo info) { return post("get_cookie", new GetCookieRequest(info)); } private String post(final String action, final AgentRequest payload) { try { try (CloseableHttpResponse response = client.execute( injectCredentials( postRequestFor(action, payload) ))) { validateResponse(response, action); return readBodyAsString(response); } } catch (IOException e) { throw new RuntimeException(e); } } private HttpRequestBase injectCredentials(final HttpRequestBase request) { request.setHeader(UUID_HEADER, agent.uuid()); request.setHeader(AUTH_HEADER, agent.token()); return request; } private void validateResponse(final HttpResponse response, final String action) throws IOException { final StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 500) { logFailure(response, action); throw new ClientProtocolException( format("The server returned an error with status code %d (%s); please check the server logs for the corresponding error.", status.getStatusCode(), status.getReasonPhrase()) ); } if (status.getStatusCode() >= 400) { logFailure(response, action); throw new ClientProtocolException(String.join("\n - ", List.of( format("The server returned status code %d. Possible reasons include:", status.getStatusCode()), "This agent has been deleted from the configuration", "This agent is pending approval", "There is possibly a reverse proxy (or load balancer) that has been misconfigured. See " + docsUrl("/installation/configure-reverse-proxy.html#agents-and-reverse-proxies") + " for details." ))); } if (status.getStatusCode() >= 300) { throw new NoHttpResponseException(format("Did not receive successful HTTP response: status code = %d, status message = [%s]", status.getStatusCode(), status.getReasonPhrase())); } } private HttpRequestBase postRequestFor(String action, AgentRequest payload) { final HttpPost request = new HttpPost(urls.remotingUrlFor(action)); request.setEntity(new StringEntity(GSON.toJson(payload), ContentType.APPLICATION_JSON)); return request; } private void logFailure(final HttpResponse response, final String action) { final StatusLine status = response.getStatusLine(); final String body = readBodyAsStringOrElse(response, "<ERROR: UNABLE TO READ RESPONSE BODY>"); LOG.error(format("Server responded to action `%s` with: status[%d %s], body[%s]", action, status.getStatusCode(), status.getReasonPhrase(), body)); } }
RemotingClient should treat all responses as JSON. Also add version Accept header.
agent/src/main/java/com/thoughtworks/go/agent/RemotingClient.java
RemotingClient should treat all responses as JSON. Also add version Accept header.
Java
apache-2.0
61740330d17d9e375651f941a2eb0091227097a3
0
robovm/robovm-studio,vvv1559/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,signed/intellij-community,caot/intellij-community,petteyg/intellij-community,slisson/intellij-community,semonte/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,holmes/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kool79/intellij-community,wreckJ/intellij-community,samthor/intellij-community,vladmm/intellij-community,petteyg/intellij-community,da1z/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,asedunov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,signed/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,blademainer/intellij-community,dslomov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,robovm/robovm-studio,ryano144/intellij-community,da1z/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,allotria/intellij-community,kdwink/intellij-community,robovm/robovm-studio,samthor/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,caot/intellij-community,caot/intellij-community,orekyuu/intellij-community,semonte/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,adedayo/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,caot/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,supersven/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,caot/intellij-community,kool79/intellij-community,allotria/intellij-community,signed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,consulo/consulo,signed/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,supersven/intellij-community,consulo/consulo,blademainer/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,holmes/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,hurricup/intellij-community,hurricup/intellij-community,kdwink/intellij-community,clumsy/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,petteyg/intellij-community,caot/intellij-community,apixandru/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,izonder/intellij-community,adedayo/intellij-community,apixandru/intellij-community,retomerz/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,slisson/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,apixandru/intellij-community,fnouama/intellij-community,xfournet/intellij-community,FHannes/intellij-community,hurricup/intellij-community,dslomov/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,supersven/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,jagguli/intellij-community,fnouama/intellij-community,supersven/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,allotria/intellij-community,fitermay/intellij-community,signed/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,izonder/intellij-community,ahb0327/intellij-community,signed/intellij-community,kool79/intellij-community,wreckJ/intellij-community,samthor/intellij-community,petteyg/intellij-community,kool79/intellij-community,ibinti/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,caot/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,xfournet/intellij-community,ibinti/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,signed/intellij-community,slisson/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,caot/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,adedayo/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ryano144/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ernestp/consulo,asedunov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,holmes/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,jexp/idea2,wreckJ/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,consulo/consulo,izonder/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,supersven/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fitermay/intellij-community,fnouama/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,jexp/idea2,MER-GROUP/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,jexp/idea2,ivan-fedorov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,dslomov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,youdonghai/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,consulo/consulo,youdonghai/intellij-community,diorcety/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,signed/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,nicolargo/intellij-community,jexp/idea2,holmes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,joewalnes/idea-community,amith01994/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,jexp/idea2,kool79/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,kool79/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,da1z/intellij-community,clumsy/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,da1z/intellij-community,kdwink/intellij-community,fitermay/intellij-community,robovm/robovm-studio,holmes/intellij-community,vladmm/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,signed/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,orekyuu/intellij-community,caot/intellij-community,izonder/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,jexp/idea2,tmpgit/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,retomerz/intellij-community,ryano144/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,jagguli/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,retomerz/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,consulo/consulo,salguarnieri/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,jagguli/intellij-community,jexp/idea2,orekyuu/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,slisson/intellij-community,slisson/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,slisson/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,slisson/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ryano144/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,holmes/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,kool79/intellij-community,semonte/intellij-community,retomerz/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ernestp/consulo,amith01994/intellij-community,ryano144/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,da1z/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,da1z/intellij-community,allotria/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,da1z/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,signed/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,vvv1559/intellij-community,samthor/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,slisson/intellij-community,kdwink/intellij-community,dslomov/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,joewalnes/idea-community,ernestp/consulo,kool79/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,jagguli/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,hurricup/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ernestp/consulo,samthor/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,jexp/idea2,akosyakov/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,diorcety/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NonNls; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.UTFDataFormatException; public class IOUtil { private static final int STRING_HEADER_SIZE = 1; private static final int STRING_LENGTH_THRESHOLD = 255; @NonNls private static final String LONGER_THAN_64K_MARKER = "LONGER_THAN_64K"; private IOUtil() {} public static String readString(DataInput stream) throws IOException { int length = stream.readInt(); if (length == -1) return null; char[] chars = new char[length]; byte[] bytes = new byte[length*2]; stream.readFully(bytes); for (int i = 0, i2 = 0; i < length; i++, i2+=2) { chars[i] = (char)((bytes[i2] << 8) + (bytes[i2 + 1] & 0xFF)); } return new String(chars); } public static void writeString(String s, DataOutput stream) throws IOException { if (s == null) { stream.writeInt(-1); return; } char[] chars = s.toCharArray(); byte[] bytes = new byte[chars.length * 2]; stream.writeInt(chars.length); for (int i = 0, i2 = 0; i < chars.length; i++, i2 += 2) { char aChar = chars[i]; bytes[i2] = (byte)((aChar >>> 8) & 0xFF); bytes[i2 + 1] = (byte)((aChar) & 0xFF); } stream.write(bytes); } public static void writeUTFTruncated(final DataOutput stream, final String text) throws IOException { if (text.length() > 65535) { stream.writeUTF(text.substring(0, 65535)); } else { stream.writeUTF(text); } } public static byte[] allocReadWriteUTFBuffer() { return new byte[STRING_LENGTH_THRESHOLD + STRING_HEADER_SIZE]; } public static void writeUTFFast(final byte[] buffer, final DataOutput storage, @NotNull final String value) throws IOException { int len = value.length(); if (len < STRING_LENGTH_THRESHOLD && isAscii(value)) { buffer[0] = (byte)len; for (int i = 0; i < len; i++) { buffer[i + STRING_HEADER_SIZE] = (byte)value.charAt(i); } storage.write(buffer, 0, len + STRING_HEADER_SIZE); } else { storage.writeByte((byte)0xFF); try { storage.writeUTF(value); } catch (UTFDataFormatException e) { storage.writeUTF(LONGER_THAN_64K_MARKER); writeString(value, storage); } } } public static String readUTFFast(final byte[] buffer, final DataInput storage) throws IOException { int len = 0xFF & (int)storage.readByte(); if (len == 0xFF) { String result = storage.readUTF(); if (LONGER_THAN_64K_MARKER.equals(result)) { return readString(storage); } return result; } final char[] chars = new char[len]; storage.readFully(buffer, 0, len); for (int i = 0; i < len; i++) { chars[i] = (char)buffer[i]; } return new String(chars); } static boolean isAscii(final String str) { for (int i = 0; i != str.length(); ++ i) { final char c = str.charAt(i); if (c < 0 || c >= 128) { return false; } } return true; } }
util/src/com/intellij/util/io/IOUtil.java
/* * Copyright 2000-2007 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io; import org.jetbrains.annotations.NonNls; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.UTFDataFormatException; public class IOUtil { private static final int STRING_HEADER_SIZE = 1; private static final int STRING_LENGTH_THRESHOLD = 255; @NonNls private static final String LONGER_THAN_64K_MARKER = "LONGER_THAN_64K"; private IOUtil() {} public static String readString(DataInput stream) throws IOException { int length = stream.readInt(); if (length == -1) return null; char[] chars = new char[length]; byte[] bytes = new byte[length*2]; stream.readFully(bytes); for (int i = 0, i2 = 0; i < length; i++, i2+=2) { chars[i] = (char)((bytes[i2] << 8) + (bytes[i2 + 1] & 0xFF)); } return new String(chars); } public static void writeString(String s, DataOutput stream) throws IOException { if (s == null) { stream.writeInt(-1); return; } char[] chars = s.toCharArray(); byte[] bytes = new byte[chars.length * 2]; stream.writeInt(chars.length); for (int i = 0, i2 = 0; i < chars.length; i++, i2 += 2) { char aChar = chars[i]; bytes[i2] = (byte)((aChar >>> 8) & 0xFF); bytes[i2 + 1] = (byte)((aChar) & 0xFF); } stream.write(bytes); } public static void writeUTFTruncated(final DataOutput stream, final String text) throws IOException { if (text.length() > 65535) { stream.writeUTF(text.substring(0, 65535)); } else { stream.writeUTF(text); } } public static byte[] allocReadWriteUTFBuffer() { return new byte[STRING_LENGTH_THRESHOLD + STRING_HEADER_SIZE]; } public static void writeUTFFast(final byte[] buffer, final DataOutput storage, final String value) throws IOException { int len = value.length(); if (len < STRING_LENGTH_THRESHOLD && isAscii(value)) { buffer[0] = (byte)len; for (int i = 0; i < len; i++) { buffer[i + STRING_HEADER_SIZE] = (byte)value.charAt(i); } storage.write(buffer, 0, len + STRING_HEADER_SIZE); } else { storage.writeByte((byte)0xFF); try { storage.writeUTF(value); } catch (UTFDataFormatException e) { storage.writeUTF(LONGER_THAN_64K_MARKER); writeString(value, storage); } } } public static String readUTFFast(final byte[] buffer, final DataInput storage) throws IOException { int len = 0xFF & (int)storage.readByte(); if (len == 0xFF) { String result = storage.readUTF(); if (LONGER_THAN_64K_MARKER.equals(result)) { return readString(storage); } return result; } final char[] chars = new char[len]; storage.readFully(buffer, 0, len); for (int i = 0; i < len; i++) { chars[i] = (char)buffer[i]; } return new String(chars); } static boolean isAscii(final String str) { for (int i = 0; i != str.length(); ++ i) { final char c = str.charAt(i); if (c < 0 || c >= 128) { return false; } } return true; } }
some assertions
util/src/com/intellij/util/io/IOUtil.java
some assertions
Java
apache-2.0
7e57cfd1caa6713e19449b9d033f138128df70c5
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModel; import com.yahoo.collections.Pair; import com.yahoo.component.Version; import com.yahoo.config.ConfigInstance; import com.yahoo.config.ConfigInstance.Builder; import com.yahoo.config.ConfigurationRuntimeException; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.ApplicationFile; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.application.api.ValidationId; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.model.ApplicationConfigProducerRoot; import com.yahoo.config.model.ConfigModelRegistry; import com.yahoo.config.model.ConfigModelRepo; import com.yahoo.config.model.NullConfigModelRegistry; import com.yahoo.config.model.api.*; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.model.producer.AbstractConfigProducerRoot; import com.yahoo.config.model.producer.UserConfigRepo; import com.yahoo.config.provision.AllocatedHosts; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.container.QrConfig; import com.yahoo.path.Path; import com.yahoo.schema.LargeRankingExpressions; import com.yahoo.schema.OnnxModel; import com.yahoo.schema.RankProfile; import com.yahoo.schema.RankProfileRegistry; import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RankProfileList; import com.yahoo.schema.document.SDField; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.ConfigPayloadBuilder; import com.yahoo.vespa.config.GenericConfig.GenericConfigBuilder; import com.yahoo.vespa.model.admin.Admin; import com.yahoo.vespa.model.builder.VespaModelBuilder; import com.yahoo.vespa.model.builder.xml.dom.VespaDomBuilder; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.vespa.model.content.Content; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.filedistribution.FileDistributionConfigProducer; import com.yahoo.vespa.model.filedistribution.FileReferencesRepository; import com.yahoo.vespa.model.ml.ConvertedModel; import com.yahoo.vespa.model.ml.ModelName; import com.yahoo.vespa.model.ml.OnnxModelInfo; import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.search.DocumentDatabase; import com.yahoo.vespa.model.search.SearchCluster; import com.yahoo.vespa.model.utils.internal.ReflectionUtil; import org.xml.sax.SAXException; import java.io.IOException; import java.lang.reflect.Constructor; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.yahoo.config.codegen.ConfiggenUtil.createClassName; import static com.yahoo.text.StringUtilities.quote; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toUnmodifiableMap; /** * <p> * The root ConfigProducer node for all Vespa systems (there is currently only one). * The main class for building the Vespa model. * <p> * The vespa model starts in an unfrozen state, where children can be added freely, * but no structure dependent information can be used. * When frozen, structure dependent information (such as config id) are * made available, but no additional config producers can be added. * * @author gjoranv */ public final class VespaModel extends AbstractConfigProducerRoot implements Model { public static final Logger log = Logger.getLogger(VespaModel.class.getName()); private final Version version; private final Version wantedNodeVersion; private final ConfigModelRepo configModelRepo = new ConfigModelRepo(); private final AllocatedHosts allocatedHosts; /** The config id for the root config producer */ public static final String ROOT_CONFIGID = ""; private final ApplicationConfigProducerRoot root; private final ApplicationPackage applicationPackage; /** The global rank profiles of this model */ private final RankProfileList rankProfileList; /** The validation overrides of this. This is never null. */ private final ValidationOverrides validationOverrides; private final FileReferencesRepository fileReferencesRepository; private final Provisioned provisioned; /** Creates a Vespa Model from internal model types only */ public VespaModel(ApplicationPackage app) throws IOException, SAXException { this(app, new NullConfigModelRegistry()); } /** Creates a Vespa Model from internal model types only */ public VespaModel(DeployState deployState) throws IOException, SAXException { this(new NullConfigModelRegistry(), deployState); } /** * Constructs vespa model using config given in app * * @param app the application to create a model from * @param configModelRegistry a registry of config model "main" classes which may be used * to instantiate config models */ public VespaModel(ApplicationPackage app, ConfigModelRegistry configModelRegistry) throws IOException, SAXException { this(configModelRegistry, new DeployState.Builder().applicationPackage(app).build()); } /** * Constructs vespa model using config given in app * * @param configModelRegistry a registry of config model "main" classes which may be used * to instantiate config models * @param deployState the global deploy state to use for this model. */ public VespaModel(ConfigModelRegistry configModelRegistry, DeployState deployState) throws IOException, SAXException { this(configModelRegistry, deployState, true); } private VespaModel(ConfigModelRegistry configModelRegistry, DeployState deployState, boolean complete) throws IOException, SAXException { super("vespamodel"); version = deployState.getVespaVersion(); wantedNodeVersion = deployState.getWantedNodeVespaVersion(); fileReferencesRepository = new FileReferencesRepository(deployState.getFileRegistry()); validationOverrides = deployState.validationOverrides(); applicationPackage = deployState.getApplicationPackage(); provisioned = deployState.provisioned(); VespaModelBuilder builder = new VespaDomBuilder(); root = builder.getRoot(VespaModel.ROOT_CONFIGID, deployState, this); createGlobalRankProfiles(deployState); rankProfileList = new RankProfileList(null, // null search -> global new LargeRankingExpressions(deployState.getFileRegistry()), AttributeFields.empty, deployState); HostSystem hostSystem = root.hostSystem(); if (complete) { // create a completed, frozen model root.useFeatureFlags(deployState.getProperties().featureFlags()); configModelRepo.readConfigModels(deployState, this, builder, root, new VespaConfigModelRegistry(configModelRegistry)); setupRouting(deployState); getAdmin().addPerHostServices(hostSystem.getHosts(), deployState); freezeModelTopology(); root.prepare(configModelRepo); configModelRepo.prepareConfigModels(deployState); validateWrapExceptions(); hostSystem.dumpPortAllocations(); propagateRestartOnDeploy(); } // else: create a model with no services instantiated (no-op) // must be done last this.allocatedHosts = AllocatedHosts.withHosts(hostSystem.getHostSpecs()); } @Override public Map<String, Set<String>> documentTypesByCluster() { return getContentClusters().entrySet().stream() .collect(toMap(Map.Entry::getKey, cluster -> cluster.getValue().getDocumentDefinitions().keySet())); } @Override public Map<String, Set<String>> indexedDocumentTypesByCluster() { return getContentClusters().entrySet().stream() .collect(toUnmodifiableMap(Map.Entry::getKey, cluster -> documentTypesWithIndex(cluster.getValue()))); } private static Set<String> documentTypesWithIndex(ContentCluster content) { Set<String> typesWithIndexMode = content.getSearch().getDocumentTypesWithIndexedCluster().stream() .map(type -> type.getFullName().getName()) .collect(Collectors.toCollection(LinkedHashSet::new)); Set<String> typesWithIndexedFields = content.getSearch().getIndexed() == null ? Set.of() : content.getSearch().getIndexed().getDocumentDbs().stream() .filter(database -> database.getDerivedConfiguration() .getSchema() .allConcreteFields() .stream().anyMatch(SDField::doesIndexing)) .map(DocumentDatabase::getSchemaName) .collect(Collectors.toCollection(LinkedHashSet::new)); return typesWithIndexMode.stream().filter(typesWithIndexedFields::contains) .collect(Collectors.toCollection(LinkedHashSet::new)); } private void propagateRestartOnDeploy() { if (applicationPackage.getMetaData().isInternalRedeploy()) return; // Propagate application config setting of restartOnDeploy to cluster deferChangesUntilRestart for (ApplicationContainerCluster containerCluster : getContainerClusters().values()) { QrConfig config = getConfig(QrConfig.class, containerCluster.getConfigId()); if (config.restartOnDeploy()) containerCluster.setDeferChangesUntilRestart(true); } } /** Returns the application package owning this */ public ApplicationPackage applicationPackage() { return applicationPackage; } /** Creates a mutable model with no services instantiated */ public static VespaModel createIncomplete(DeployState deployState) throws IOException, SAXException { return new VespaModel(new NullConfigModelRegistry(), deployState, false); } private void validateWrapExceptions() { try { validate(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error while validating model:", e); } } /** * Creates a rank profile not attached to any search definition, for each imported model in the application package, * and adds it to the given rank profile registry. */ private void createGlobalRankProfiles(DeployState deployState) { var importedModels = deployState.getImportedModels().all(); DeployLogger deployLogger = deployState.getDeployLogger(); RankProfileRegistry rankProfileRegistry = deployState.rankProfileRegistry(); QueryProfiles queryProfiles = deployState.getQueryProfiles(); List <Future<ConvertedModel>> futureModels = new ArrayList<>(); if ( ! importedModels.isEmpty()) { // models/ directory is available for (ImportedMlModel model : importedModels) { // Due to automatic naming not guaranteeing unique names, there must be a 1-1 between OnnxModels and global RankProfiles. RankProfile profile = new RankProfile(model.name(), null, applicationPackage, deployLogger, rankProfileRegistry); addOnnxModelInfoFromSource(model, profile); rankProfileRegistry.add(profile); futureModels.add(deployState.getExecutor().submit(() -> { ConvertedModel convertedModel = ConvertedModel.fromSource(applicationPackage, new ModelName(model.name()), model.name(), profile, queryProfiles.getRegistry(), model); convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); return convertedModel; })); } } else { // generated and stored model information may be available instead ApplicationFile generatedModelsDir = applicationPackage.getFile(ApplicationPackage.MODELS_GENERATED_REPLICATED_DIR); for (ApplicationFile generatedModelDir : generatedModelsDir.listFiles()) { String modelName = generatedModelDir.getPath().last(); if (modelName.contains(".")) continue; // Name space: Not a global profile // Due to automatic naming not guaranteeing unique names, there must be a 1-1 between OnnxModels and global RankProfiles. RankProfile profile = new RankProfile(modelName, null, applicationPackage, deployLogger, rankProfileRegistry); addOnnxModelInfoFromStore(modelName, profile); rankProfileRegistry.add(profile); futureModels.add(deployState.getExecutor().submit(() -> { ConvertedModel convertedModel = ConvertedModel.fromStore(applicationPackage, new ModelName(modelName), modelName, profile); convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); return convertedModel; })); } } for (var futureConvertedModel : futureModels) { try { futureConvertedModel.get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } new Processing().processRankProfiles(deployLogger, rankProfileRegistry, queryProfiles, true, false); } private void addOnnxModelInfoFromSource(ImportedMlModel model, RankProfile profile) { if (model.modelType() == ImportedMlModel.ModelType.ONNX) { String path = model.source(); String applicationPath = this.applicationPackage.getFileReference(Path.fromString("")).toString(); if (path.startsWith(applicationPath)) { path = path.substring(applicationPath.length() + 1); } addOnnxModelInfo(model.name(), path, profile); } } private void addOnnxModelInfoFromStore(String modelName, RankProfile profile) { String path = ApplicationPackage.MODELS_DIR.append(modelName + ".onnx").toString(); addOnnxModelInfo(modelName, path, profile); } private void addOnnxModelInfo(String name, String path, RankProfile profile) { boolean modelExists = OnnxModelInfo.modelExists(path, this.applicationPackage); if ( ! modelExists) { path = ApplicationPackage.MODELS_DIR.append(path).toString(); modelExists = OnnxModelInfo.modelExists(path, this.applicationPackage); } if (modelExists) { OnnxModelInfo onnxModelInfo = OnnxModelInfo.load(path, this.applicationPackage); if (onnxModelInfo.getModelPath() != null) { OnnxModel onnxModel = new OnnxModel(name, onnxModelInfo.getModelPath()); onnxModel.setModelInfo(onnxModelInfo); profile.add(onnxModel); } } } /** Returns the global rank profiles as a rank profile list */ public RankProfileList rankProfileList() { return rankProfileList; } private void setupRouting(DeployState deployState) { root.setupRouting(deployState, this, configModelRepo); } /** Returns the one and only HostSystem of this VespaModel */ public HostSystem hostSystem() { return root.hostSystem(); } /** Return a collection of all hostnames used in this application */ @Override public Set<HostInfo> getHosts() { return hostSystem().getHosts().stream() .map(HostResource::getHostInfo) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<FileReference> fileReferences() { return fileReferencesRepository.allFileReferences(); } /** Returns this models Vespa instance */ public ApplicationConfigProducerRoot getVespa() { return root; } @Override public boolean allowModelVersionMismatch(Instant now) { return validationOverrides.allows(ValidationId.configModelVersionMismatch, now) || validationOverrides.allows(ValidationId.skipOldConfigModels, now); // implies this } @Override public boolean skipOldConfigModels(Instant now) { return validationOverrides.allows(ValidationId.skipOldConfigModels, now); } @Override public Version version() { return version; } @Override public Version wantedNodeVersion() { return wantedNodeVersion; } /** * Resolves config of the given type and config id, by first instantiating the correct {@link com.yahoo.config.ConfigInstance.Builder}, * calling {@link #getConfig(com.yahoo.config.ConfigInstance.Builder, String)}. The default values used will be those of the config * types in the model. * * @param clazz the type of config * @param configId the config id * @return a config instance of the given type */ @Override public <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> clazz, String configId) { try { ConfigInstance.Builder builder = newBuilder(clazz); getConfig(builder, configId); return newConfigInstance(clazz, builder); } catch (Exception e) { throw new RuntimeException(e); } } /** * Populates an instance of configClass with config produced by configProducer. */ public static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> configClass, ConfigProducer configProducer) { try { Builder builder = newBuilder(configClass); populateConfigBuilder(builder, configProducer); return newConfigInstance(configClass, builder); } catch (Exception e) { throw new RuntimeException("Failed getting config for class " + configClass.getName(), e); } } private static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE newConfigInstance(Class<CONFIGTYPE> configClass, Builder builder) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { Constructor<CONFIGTYPE> constructor = configClass.getConstructor(builder.getClass()); return constructor.newInstance(builder); } private static Builder newBuilder(Class<? extends ConfigInstance> configClass) throws ReflectiveOperationException { Class<?> builderClazz = configClass.getClassLoader().loadClass(configClass.getName() + "$Builder"); return (Builder)builderClazz.getDeclaredConstructor().newInstance(); } /** * Throw if the config id does not exist in the model. * * @param configId a config id */ private void checkId(String configId) { if ( ! id2producer.containsKey(configId)) { log.log(Level.FINE, () -> "Invalid config id: " + configId); } } /** * Resolves config for a given config id and populates the given builder with the config. * * @param builder a configinstance builder * @param configId the config id for the config client * @return the builder if a producer was found, and it did apply config, null otherwise */ @Override public ConfigInstance.Builder getConfig(ConfigInstance.Builder builder, String configId) { checkId(configId); Optional<ConfigProducer> configProducer = getConfigProducer(configId); if (configProducer.isEmpty()) return null; populateConfigBuilder(builder, configProducer.get()); return builder; } private static void populateConfigBuilder(Builder builder, ConfigProducer configProducer) { boolean found = configProducer.cascadeConfig(builder); boolean foundOverride = configProducer.addUserConfig(builder); log.log(Level.FINE, () -> "Trying to get config for " + builder.getClass().getDeclaringClass().getName() + " for config id " + quote(configProducer.getConfigId()) + ", found=" + found + ", foundOverride=" + foundOverride); } /** * Resolve config for a given key and config definition * * @param configKey the key to resolve. * @param targetDef the config definition to use for the schema * @return the resolved config instance */ @Override public ConfigInstance.Builder getConfigInstance(ConfigKey<?> configKey, com.yahoo.vespa.config.buildergen.ConfigDefinition targetDef) { Objects.requireNonNull(targetDef, "config definition cannot be null"); return resolveToBuilder(configKey); } /** * Resolves the given config key into a correctly typed ConfigBuilder * and fills in the config from this model. * * @return A new config builder with config from this model filled in,. */ private ConfigInstance.Builder resolveToBuilder(ConfigKey<?> key) { ConfigInstance.Builder builder = createBuilder(new ConfigDefinitionKey(key)); getConfig(builder, key.getConfigId()); return builder; } @Override public Set<ConfigKey<?>> allConfigsProduced() { Set<ConfigKey<?>> keySet = new LinkedHashSet<>(); for (ConfigProducer producer : id2producer().values()) { keySet.addAll(configsProduced(producer)); } return keySet; } private ConfigInstance.Builder createBuilder(ConfigDefinitionKey key) { String className = createClassName(key.getName()); Class<?> clazz; Pair<String, ClassLoader> fullClassNameAndLoader = getClassLoaderForProducer(key, className); String fullClassName = fullClassNameAndLoader.getFirst(); ClassLoader classLoader = fullClassNameAndLoader.getSecond(); final String builderName = fullClassName + "$Builder"; if (classLoader == null) { classLoader = getClass().getClassLoader(); log.log(Level.FINE, () -> "No producer found to get classloader from for " + fullClassName + ". Using default"); } try { clazz = classLoader.loadClass(builderName); } catch (ClassNotFoundException e) { log.log(Level.FINE, () -> "Tried to load " + builderName + ", not found, trying with generic builder"); return new GenericConfigBuilder(key, new ConfigPayloadBuilder()); } Object i; try { i = clazz.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new ConfigurationRuntimeException(e); } if (!(i instanceof ConfigInstance.Builder)) { throw new ConfigurationRuntimeException(fullClassName + " is not a ConfigInstance.Builder, can not produce config for the name '" + key.getName() + "'."); } return (ConfigInstance.Builder) i; } /** * Takes a candidate class name and tries to find a config producer for that class in the model. First, an * attempt is made with the given full class name, and if unsuccessful, then with 'com.yahoo.' prefixed to it. * Returns the full class name and the class loader that a producer was found for. If no producer was found, * returns the full class name with prefix, and null for the class loader. */ private Pair<String, ClassLoader> getClassLoaderForProducer(ConfigDefinitionKey key, String shortClassName) { // TODO: Stop supporting fullClassNameWithComYahoo below, should not be used String fullClassNameWithComYahoo = "com.yahoo." + key.getNamespace() + "." + shortClassName; String fullClassNameWithoutPrefix = key.getNamespace() + "." + shortClassName; String producerSuffix = "$Producer"; ClassLoader loader = getConfigClassLoader(fullClassNameWithoutPrefix + producerSuffix); if (loader != null) return new Pair<>(fullClassNameWithoutPrefix, loader); return new Pair<>(fullClassNameWithComYahoo, getConfigClassLoader(fullClassNameWithComYahoo + producerSuffix)); } /** * The set of all config ids present * @return set of config ids */ public Set<String> allConfigIds() { return id2producer.keySet(); } @Override public AllocatedHosts allocatedHosts() { return allocatedHosts; } private static Set<ConfigKey<?>> configsProduced(ConfigProducer cp) { Set<ConfigKey<?>> ret = ReflectionUtil.getAllConfigsProduced(cp.getClass(), cp.getConfigId()); UserConfigRepo userConfigs = cp.getUserConfigs(); for (ConfigDefinitionKey userKey : userConfigs.configsProduced()) { ret.add(new ConfigKey<>(userKey.getName(), cp.getConfigId(), userKey.getNamespace())); } return ret; } /** * @return an unmodifiable copy of the set of configIds in this VespaModel. */ public Set<String> getConfigIds() { return Collections.unmodifiableSet(id2producer.keySet()); } /** * Returns the admin component of the vespamodel. * * @return Admin */ public Admin getAdmin() { return root.getAdmin(); } /** * Adds the descendant (at any depth level), so it can be looked up * on configId in the Map. * * @param configId the id to register with, not necessarily equal to descendant.getConfigId(). * @param descendant The configProducer descendant to add */ public void addDescendant(String configId, AbstractConfigProducer<?> descendant) { if (id2producer.containsKey(configId)) { throw new RuntimeException ("Config ID '" + configId + "' cannot be reserved by an instance of class '" + descendant.getClass().getName() + "' since it is already used by an instance of class '" + id2producer.get(configId).getClass().getName() + "'. (This is commonly caused by service/node index " + "collisions in the config.)"); } id2producer.put(configId, descendant); } public List<SearchCluster> getSearchClusters() { return Content.getSearchClusters(configModelRepo()); } /** Returns a map of content clusters by ID */ public Map<String, ContentCluster> getContentClusters() { Map<String, ContentCluster> clusters = new LinkedHashMap<>(); for (Content model : configModelRepo.getModels(Content.class)) { clusters.put(model.getId(), model.getCluster()); } return Collections.unmodifiableMap(clusters); } /** Returns a map of container clusters by ID */ public Map<String, ApplicationContainerCluster> getContainerClusters() { Map<String, ApplicationContainerCluster> clusters = new LinkedHashMap<>(); for (ContainerModel model : configModelRepo.getModels(ContainerModel.class)) { if (model.getCluster() instanceof ApplicationContainerCluster) { clusters.put(model.getId(), (ApplicationContainerCluster) model.getCluster()); } } return Collections.unmodifiableMap(clusters); } /** Returns the routing config model. This might be null. */ public Routing getRouting() { return configModelRepo.getRouting(); } public FileDistributionConfigProducer getFileDistributionConfigProducer() { return root.getFileDistributionConfigProducer(); } /** Returns an unmodifiable view of the mapping of config id to {@link ConfigProducer} */ public Map<String, ConfigProducer> id2producer() { return Collections.unmodifiableMap(id2producer); } /** Returns this root's model repository */ public ConfigModelRepo configModelRepo() { return configModelRepo; } /** If provisioning through the node repo, returns the provision requests issued during build of this */ public Provisioned provisioned() { return provisioned; } /** Returns the id of all clusters in this */ public Set<ClusterSpec.Id> allClusters() { return hostSystem().getHosts().stream() .map(HostResource::spec) .filter(spec -> spec.membership().isPresent()) .map(spec -> spec.membership().get().cluster().id()) .collect(Collectors.toCollection(LinkedHashSet::new)); } @Override public Set<ApplicationClusterInfo> applicationClusterInfo() { return Set.copyOf(getContainerClusters().values()); } }
config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModel; import com.yahoo.collections.Pair; import com.yahoo.component.Version; import com.yahoo.config.ConfigInstance; import com.yahoo.config.ConfigInstance.Builder; import com.yahoo.config.ConfigurationRuntimeException; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.ApplicationFile; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.application.api.ValidationId; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.model.ApplicationConfigProducerRoot; import com.yahoo.config.model.ConfigModelRegistry; import com.yahoo.config.model.ConfigModelRepo; import com.yahoo.config.model.NullConfigModelRegistry; import com.yahoo.config.model.api.*; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.model.producer.AbstractConfigProducerRoot; import com.yahoo.config.model.producer.UserConfigRepo; import com.yahoo.config.provision.AllocatedHosts; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.container.QrConfig; import com.yahoo.path.Path; import com.yahoo.schema.LargeRankingExpressions; import com.yahoo.schema.OnnxModel; import com.yahoo.schema.RankProfile; import com.yahoo.schema.RankProfileRegistry; import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RankProfileList; import com.yahoo.schema.document.SDField; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.ConfigPayloadBuilder; import com.yahoo.vespa.config.GenericConfig.GenericConfigBuilder; import com.yahoo.vespa.model.admin.Admin; import com.yahoo.vespa.model.builder.VespaModelBuilder; import com.yahoo.vespa.model.builder.xml.dom.VespaDomBuilder; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.vespa.model.content.Content; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.filedistribution.FileDistributionConfigProducer; import com.yahoo.vespa.model.filedistribution.FileReferencesRepository; import com.yahoo.vespa.model.ml.ConvertedModel; import com.yahoo.vespa.model.ml.ModelName; import com.yahoo.vespa.model.ml.OnnxModelInfo; import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.search.DocumentDatabase; import com.yahoo.vespa.model.search.SearchCluster; import com.yahoo.vespa.model.utils.internal.ReflectionUtil; import org.xml.sax.SAXException; import java.io.IOException; import java.lang.reflect.Constructor; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import static com.yahoo.config.codegen.ConfiggenUtil.createClassName; import static com.yahoo.text.StringUtilities.quote; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toUnmodifiableMap; /** * <p> * The root ConfigProducer node for all Vespa systems (there is currently only one). * The main class for building the Vespa model. * <p> * The vespa model starts in an unfrozen state, where children can be added freely, * but no structure dependent information can be used. * When frozen, structure dependent information (such as config id) are * made available, but no additional config producers can be added. * * @author gjoranv */ public final class VespaModel extends AbstractConfigProducerRoot implements Model { public static final Logger log = Logger.getLogger(VespaModel.class.getName()); private final Version version; private final Version wantedNodeVersion; private final ConfigModelRepo configModelRepo = new ConfigModelRepo(); private final AllocatedHosts allocatedHosts; /** The config id for the root config producer */ public static final String ROOT_CONFIGID = ""; private final ApplicationConfigProducerRoot root; private final ApplicationPackage applicationPackage; /** The global rank profiles of this model */ private final RankProfileList rankProfileList; /** The validation overrides of this. This is never null. */ private final ValidationOverrides validationOverrides; private final FileReferencesRepository fileReferencesRepository; private final Provisioned provisioned; /** Creates a Vespa Model from internal model types only */ public VespaModel(ApplicationPackage app) throws IOException, SAXException { this(app, new NullConfigModelRegistry()); } /** Creates a Vespa Model from internal model types only */ public VespaModel(DeployState deployState) throws IOException, SAXException { this(new NullConfigModelRegistry(), deployState); } /** * Constructs vespa model using config given in app * * @param app the application to create a model from * @param configModelRegistry a registry of config model "main" classes which may be used * to instantiate config models */ public VespaModel(ApplicationPackage app, ConfigModelRegistry configModelRegistry) throws IOException, SAXException { this(configModelRegistry, new DeployState.Builder().applicationPackage(app).build()); } /** * Constructs vespa model using config given in app * * @param configModelRegistry a registry of config model "main" classes which may be used * to instantiate config models * @param deployState the global deploy state to use for this model. */ public VespaModel(ConfigModelRegistry configModelRegistry, DeployState deployState) throws IOException, SAXException { this(configModelRegistry, deployState, true); } private VespaModel(ConfigModelRegistry configModelRegistry, DeployState deployState, boolean complete) throws IOException, SAXException { super("vespamodel"); version = deployState.getVespaVersion(); wantedNodeVersion = deployState.getWantedNodeVespaVersion(); fileReferencesRepository = new FileReferencesRepository(deployState.getFileRegistry()); validationOverrides = deployState.validationOverrides(); applicationPackage = deployState.getApplicationPackage(); provisioned = deployState.provisioned(); VespaModelBuilder builder = new VespaDomBuilder(); root = builder.getRoot(VespaModel.ROOT_CONFIGID, deployState, this); createGlobalRankProfiles(deployState); rankProfileList = new RankProfileList(null, // null search -> global new LargeRankingExpressions(deployState.getFileRegistry()), AttributeFields.empty, deployState); HostSystem hostSystem = root.hostSystem(); if (complete) { // create a completed, frozen model root.useFeatureFlags(deployState.getProperties().featureFlags()); configModelRepo.readConfigModels(deployState, this, builder, root, new VespaConfigModelRegistry(configModelRegistry)); setupRouting(deployState); getAdmin().addPerHostServices(hostSystem.getHosts(), deployState); freezeModelTopology(); root.prepare(configModelRepo); configModelRepo.prepareConfigModels(deployState); validateWrapExceptions(); hostSystem.dumpPortAllocations(); propagateRestartOnDeploy(); } // else: create a model with no services instantiated (no-op) // must be done last this.allocatedHosts = AllocatedHosts.withHosts(hostSystem.getHostSpecs()); } @Override public Map<String, Set<String>> documentTypesByCluster() { return getContentClusters().entrySet().stream() .collect(toMap(Map.Entry::getKey, cluster -> cluster.getValue().getDocumentDefinitions().keySet())); } @Override public Map<String, Set<String>> indexedDocumentTypesByCluster() { return getContentClusters().entrySet().stream() .collect(toUnmodifiableMap(Map.Entry::getKey, cluster -> documentTypesWithIndex(cluster.getValue()))); } private static Set<String> documentTypesWithIndex(ContentCluster content) { Set<String> typesWithIndexMode = content.getSearch().getDocumentTypesWithIndexedCluster().stream() .map(type -> type.getFullName().getName()) .collect(Collectors.toCollection(LinkedHashSet::new)); Set<String> typesWithIndexedFields = content.getSearch().getIndexed() == null ? Set.of() : content.getSearch().getIndexed().getDocumentDbs().stream() .filter(database -> database.getDerivedConfiguration() .getSchema() .allConcreteFields() .stream().anyMatch(SDField::doesIndexing)) .map(DocumentDatabase::getSchemaName) .collect(Collectors.toCollection(LinkedHashSet::new)); return typesWithIndexMode.stream().filter(typesWithIndexedFields::contains) .collect(Collectors.toCollection(LinkedHashSet::new)); } private void propagateRestartOnDeploy() { if (applicationPackage.getMetaData().isInternalRedeploy()) return; // Propagate application config setting of restartOnDeploy to cluster deferChangesUntilRestart for (ApplicationContainerCluster containerCluster : getContainerClusters().values()) { QrConfig config = getConfig(QrConfig.class, containerCluster.getConfigId()); if (config.restartOnDeploy()) containerCluster.setDeferChangesUntilRestart(true); } } /** Returns the application package owning this */ public ApplicationPackage applicationPackage() { return applicationPackage; } /** Creates a mutable model with no services instantiated */ public static VespaModel createIncomplete(DeployState deployState) throws IOException, SAXException { return new VespaModel(new NullConfigModelRegistry(), deployState, false); } private void validateWrapExceptions() { try { validate(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error while validating model:", e); } } /** * Creates a rank profile not attached to any search definition, for each imported model in the application package, * and adds it to the given rank profile registry. */ private void createGlobalRankProfiles(DeployState deployState) { var importedModels = deployState.getImportedModels().all(); DeployLogger deployLogger = deployState.getDeployLogger(); RankProfileRegistry rankProfileRegistry = deployState.rankProfileRegistry(); QueryProfiles queryProfiles = deployState.getQueryProfiles(); List <Future<ConvertedModel>> futureModels = new ArrayList<>(); if ( ! importedModels.isEmpty()) { // models/ directory is available for (ImportedMlModel model : importedModels) { // Due to automatic naming not guaranteeing unique names, there must be a 1-1 between OnnxModels and global RankProfiles. RankProfile profile = new RankProfile(model.name(), null, applicationPackage, deployLogger, rankProfileRegistry); addOnnxModelInfoFromSource(model, profile); rankProfileRegistry.add(profile); futureModels.add(deployState.getExecutor().submit(() -> { ConvertedModel convertedModel = ConvertedModel.fromSource(applicationPackage, new ModelName(model.name()), model.name(), profile, queryProfiles.getRegistry(), model); convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); return convertedModel; })); } } else { // generated and stored model information may be available instead ApplicationFile generatedModelsDir = applicationPackage.getFile(ApplicationPackage.MODELS_GENERATED_REPLICATED_DIR); for (ApplicationFile generatedModelDir : generatedModelsDir.listFiles()) { String modelName = generatedModelDir.getPath().last(); if (modelName.contains(".")) continue; // Name space: Not a global profile // Due to automatic naming not guaranteeing unique names, there must be a 1-1 between OnnxModels and global RankProfiles. RankProfile profile = new RankProfile(modelName, null, applicationPackage, deployLogger, rankProfileRegistry); addOnnxModelInfoFromStore(modelName, profile); rankProfileRegistry.add(profile); futureModels.add(deployState.getExecutor().submit(() -> { ConvertedModel convertedModel = ConvertedModel.fromStore(applicationPackage, new ModelName(modelName), modelName, profile); convertedModel.expressions().values().forEach(f -> profile.addFunction(f, false)); return convertedModel; })); } } for (var futureConvertedModel : futureModels) { try { futureConvertedModel.get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } } new Processing().processRankProfiles(deployLogger, rankProfileRegistry, queryProfiles, true, false); } private void addOnnxModelInfoFromSource(ImportedMlModel model, RankProfile profile) { if (model.modelType() == ImportedMlModel.ModelType.ONNX) { String path = model.source(); String applicationPath = this.applicationPackage.getFileReference(Path.fromString("")).toString(); if (path.startsWith(applicationPath)) { path = path.substring(applicationPath.length() + 1); } addOnnxModelInfo(model.name(), path, profile); } } private void addOnnxModelInfoFromStore(String modelName, RankProfile profile) { String path = ApplicationPackage.MODELS_DIR.append(modelName + ".onnx").toString(); addOnnxModelInfo(modelName, path, profile); } private void addOnnxModelInfo(String name, String path, RankProfile profile) { boolean modelExists = OnnxModelInfo.modelExists(path, this.applicationPackage); if ( ! modelExists) { path = ApplicationPackage.MODELS_DIR.append(path).toString(); modelExists = OnnxModelInfo.modelExists(path, this.applicationPackage); } if (modelExists) { OnnxModelInfo onnxModelInfo = OnnxModelInfo.load(path, this.applicationPackage); if (onnxModelInfo.getModelPath() != null) { OnnxModel onnxModel = new OnnxModel(name, onnxModelInfo.getModelPath()); onnxModel.setModelInfo(onnxModelInfo); profile.add(onnxModel); } } } /** Returns the global rank profiles as a rank profile list */ public RankProfileList rankProfileList() { return rankProfileList; } private void setupRouting(DeployState deployState) { root.setupRouting(deployState, this, configModelRepo); } /** Returns the one and only HostSystem of this VespaModel */ public HostSystem hostSystem() { return root.hostSystem(); } /** Return a collection of all hostnames used in this application */ @Override public Set<HostInfo> getHosts() { return hostSystem().getHosts().stream() .map(HostResource::getHostInfo) .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<FileReference> fileReferences() { return fileReferencesRepository.allFileReferences(); } /** Returns this models Vespa instance */ public ApplicationConfigProducerRoot getVespa() { return root; } @Override public boolean allowModelVersionMismatch(Instant now) { return validationOverrides.allows(ValidationId.configModelVersionMismatch, now) || validationOverrides.allows(ValidationId.skipOldConfigModels, now); // implies this } @Override public boolean skipOldConfigModels(Instant now) { return validationOverrides.allows(ValidationId.skipOldConfigModels, now); } @Override public Version version() { return version; } @Override public Version wantedNodeVersion() { return wantedNodeVersion; } /** * Resolves config of the given type and config id, by first instantiating the correct {@link com.yahoo.config.ConfigInstance.Builder}, * calling {@link #getConfig(com.yahoo.config.ConfigInstance.Builder, String)}. The default values used will be those of the config * types in the model. * * @param clazz the type of config * @param configId the config id * @return a config instance of the given type */ @Override public <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> clazz, String configId) { try { ConfigInstance.Builder builder = newBuilder(clazz); getConfig(builder, configId); return newConfigInstance(clazz, builder); } catch (Exception e) { throw new RuntimeException(e); } } /** * Populates an instance of configClass with config produced by configProducer. */ public static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> configClass, ConfigProducer configProducer) { try { Builder builder = newBuilder(configClass); populateConfigBuilder(builder, configProducer); return newConfigInstance(configClass, builder); } catch (Exception e) { throw new RuntimeException("Failed getting config for class " + configClass.getName(), e); } } private static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE newConfigInstance(Class<CONFIGTYPE> configClass, Builder builder) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { Constructor<CONFIGTYPE> constructor = configClass.getConstructor(builder.getClass()); return constructor.newInstance(builder); } private static Builder newBuilder(Class<? extends ConfigInstance> configClass) throws ReflectiveOperationException { Class<?> builderClazz = configClass.getClassLoader().loadClass(configClass.getName() + "$Builder"); return (Builder)builderClazz.getDeclaredConstructor().newInstance(); } /** * Throw if the config id does not exist in the model. * * @param configId a config id */ private void checkId(String configId) { if ( ! id2producer.containsKey(configId)) { log.log(Level.FINE, () -> "Invalid config id: " + configId); } } /** * Resolves config for a given config id and populates the given builder with the config. * * @param builder a configinstance builder * @param configId the config id for the config client * @return the builder if a producer was found, and it did apply config, null otherwise */ @Override public ConfigInstance.Builder getConfig(ConfigInstance.Builder builder, String configId) { checkId(configId); Optional<ConfigProducer> configProducer = getConfigProducer(configId); if (configProducer.isEmpty()) return null; populateConfigBuilder(builder, configProducer.get()); return builder; } private static void populateConfigBuilder(Builder builder, ConfigProducer configProducer) { boolean found = configProducer.cascadeConfig(builder); boolean foundOverride = configProducer.addUserConfig(builder); log.log(Level.FINE, () -> "Trying to get config for " + builder.getClass().getDeclaringClass().getName() + " for config id " + quote(configProducer.getConfigId()) + ", found=" + found + ", foundOverride=" + foundOverride); } /** * Resolve config for a given key and config definition * * @param configKey the key to resolve. * @param targetDef the config definition to use for the schema * @return the resolved config instance */ @Override public ConfigInstance.Builder getConfigInstance(ConfigKey<?> configKey, com.yahoo.vespa.config.buildergen.ConfigDefinition targetDef) { Objects.requireNonNull(targetDef, "config definition cannot be null"); return resolveToBuilder(configKey); } /** * Resolves the given config key into a correctly typed ConfigBuilder * and fills in the config from this model. * * @return A new config builder with config from this model filled in,. */ private ConfigInstance.Builder resolveToBuilder(ConfigKey<?> key) { ConfigInstance.Builder builder = createBuilder(new ConfigDefinitionKey(key)); getConfig(builder, key.getConfigId()); return builder; } @Override public Set<ConfigKey<?>> allConfigsProduced() { Set<ConfigKey<?>> keySet = new LinkedHashSet<>(); for (ConfigProducer producer : id2producer().values()) { keySet.addAll(configsProduced(producer)); } return keySet; } private ConfigInstance.Builder createBuilder(ConfigDefinitionKey key) { String className = createClassName(key.getName()); Class<?> clazz; Pair<String, ClassLoader> fullClassNameAndLoader = getClassLoaderForProducer(key, className); String fullClassName = fullClassNameAndLoader.getFirst(); ClassLoader classLoader = fullClassNameAndLoader.getSecond(); final String builderName = fullClassName + "$Builder"; if (classLoader == null) { classLoader = getClass().getClassLoader(); log.log(Level.FINE, () -> "No producer found to get classloader from for " + fullClassName + ". Using default"); } try { clazz = classLoader.loadClass(builderName); } catch (ClassNotFoundException e) { log.log(Level.FINE, () -> "Tried to load " + builderName + ", not found, trying with generic builder"); return new GenericConfigBuilder(key, new ConfigPayloadBuilder()); } Object i; try { i = clazz.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { throw new ConfigurationRuntimeException(e); } if (!(i instanceof ConfigInstance.Builder)) { throw new ConfigurationRuntimeException(fullClassName + " is not a ConfigInstance.Builder, can not produce config for the name '" + key.getName() + "'."); } return (ConfigInstance.Builder) i; } /** * Takes a candidate class name and tries to find a config producer for that class in the model. First, an * attempt is made with the given full class name, and if unsuccessful, then with 'com.yahoo.' prefixed to it. * Returns the full class name and the class loader that a producer was found for. If no producer was found, * returns the full class name with prefix, and null for the class loader. */ private Pair<String, ClassLoader> getClassLoaderForProducer(ConfigDefinitionKey key, String shortClassName) { // TODO: Stop supporting fullClassNameWithComYahoo below, should not be used String fullClassNameWithComYahoo = "com.yahoo" + key.getNamespace() + "." + shortClassName; String fullClassNameWithoutPrefix = key.getNamespace() + "." + shortClassName; String producerSuffix = "$Producer"; ClassLoader loader = getConfigClassLoader(fullClassNameWithoutPrefix + producerSuffix); if (loader != null) return new Pair<>(fullClassNameWithoutPrefix, loader); return new Pair<>(fullClassNameWithComYahoo, getConfigClassLoader(fullClassNameWithComYahoo + producerSuffix)); } /** * The set of all config ids present * @return set of config ids */ public Set<String> allConfigIds() { return id2producer.keySet(); } @Override public AllocatedHosts allocatedHosts() { return allocatedHosts; } private static Set<ConfigKey<?>> configsProduced(ConfigProducer cp) { Set<ConfigKey<?>> ret = ReflectionUtil.getAllConfigsProduced(cp.getClass(), cp.getConfigId()); UserConfigRepo userConfigs = cp.getUserConfigs(); for (ConfigDefinitionKey userKey : userConfigs.configsProduced()) { ret.add(new ConfigKey<>(userKey.getName(), cp.getConfigId(), userKey.getNamespace())); } return ret; } /** * @return an unmodifiable copy of the set of configIds in this VespaModel. */ public Set<String> getConfigIds() { return Collections.unmodifiableSet(id2producer.keySet()); } /** * Returns the admin component of the vespamodel. * * @return Admin */ public Admin getAdmin() { return root.getAdmin(); } /** * Adds the descendant (at any depth level), so it can be looked up * on configId in the Map. * * @param configId the id to register with, not necessarily equal to descendant.getConfigId(). * @param descendant The configProducer descendant to add */ public void addDescendant(String configId, AbstractConfigProducer<?> descendant) { if (id2producer.containsKey(configId)) { throw new RuntimeException ("Config ID '" + configId + "' cannot be reserved by an instance of class '" + descendant.getClass().getName() + "' since it is already used by an instance of class '" + id2producer.get(configId).getClass().getName() + "'. (This is commonly caused by service/node index " + "collisions in the config.)"); } id2producer.put(configId, descendant); } public List<SearchCluster> getSearchClusters() { return Content.getSearchClusters(configModelRepo()); } /** Returns a map of content clusters by ID */ public Map<String, ContentCluster> getContentClusters() { Map<String, ContentCluster> clusters = new LinkedHashMap<>(); for (Content model : configModelRepo.getModels(Content.class)) { clusters.put(model.getId(), model.getCluster()); } return Collections.unmodifiableMap(clusters); } /** Returns a map of container clusters by ID */ public Map<String, ApplicationContainerCluster> getContainerClusters() { Map<String, ApplicationContainerCluster> clusters = new LinkedHashMap<>(); for (ContainerModel model : configModelRepo.getModels(ContainerModel.class)) { if (model.getCluster() instanceof ApplicationContainerCluster) { clusters.put(model.getId(), (ApplicationContainerCluster) model.getCluster()); } } return Collections.unmodifiableMap(clusters); } /** Returns the routing config model. This might be null. */ public Routing getRouting() { return configModelRepo.getRouting(); } public FileDistributionConfigProducer getFileDistributionConfigProducer() { return root.getFileDistributionConfigProducer(); } /** Returns an unmodifiable view of the mapping of config id to {@link ConfigProducer} */ public Map<String, ConfigProducer> id2producer() { return Collections.unmodifiableMap(id2producer); } /** Returns this root's model repository */ public ConfigModelRepo configModelRepo() { return configModelRepo; } /** If provisioning through the node repo, returns the provision requests issued during build of this */ public Provisioned provisioned() { return provisioned; } /** Returns the id of all clusters in this */ public Set<ClusterSpec.Id> allClusters() { return hostSystem().getHosts().stream() .map(HostResource::spec) .filter(spec -> spec.membership().isPresent()) .map(spec -> spec.membership().get().cluster().id()) .collect(Collectors.toCollection(LinkedHashSet::new)); } @Override public Set<ApplicationClusterInfo> applicationClusterInfo() { return Set.copyOf(getContainerClusters().values()); } }
Add back . that got lost
config-model/src/main/java/com/yahoo/vespa/model/VespaModel.java
Add back . that got lost
Java
apache-2.0
7d02a688a6b22b3d796986fcdbdbe5d70db6034c
0
argius/Stew4
package net.argius.stew; import java.io.*; import java.sql.*; import java.util.*; import javax.script.*; import net.argius.stew.io.*; import net.argius.stew.ui.*; /** * Command Processor. */ final class CommandProcessor { private static Logger log = Logger.getLogger(CommandProcessor.class); private static ResourceManager res = ResourceManager.getInstance(Command.class); private static final String HYPHEN_E = "-e"; private final Environment env; private final OutputProcessor op; CommandProcessor(Environment env) { this.env = env; this.op = env.getOutputProcessor(); } /** * Invokes this command. * @param parameterString * @return whether this application continues or not * @throws CommandException */ boolean invoke(String parameterString) throws CommandException { Parameter p = new Parameter(parameterString); if (parameterString.replaceFirst("^\\s+", "").startsWith(HYPHEN_E)) { final int offset = parameterString.indexOf(HYPHEN_E) + 2; for (String s : parameterString.substring(offset).split(HYPHEN_E)) { op.output(" >> " + s); if (!invoke(s)) { outputMessage("w.exit-not-available-in-sequencial-command"); } } return true; } final String commandName = p.at(0); try { return invoke(commandName, new Parameter(parameterString)); } catch (UsageException ex) { outputMessage("e.usage", commandName, ex.getMessage()); } catch (DynamicLoadingException ex) { log.error(ex); outputMessage("e.not-found", commandName); } catch (CommandException ex) { log.error(ex); Throwable cause = ex.getCause(); String message = (cause == null) ? ex.getMessage() : cause.getMessage(); outputMessage("e.command", message); } catch (IOException ex) { log.error(ex); outputMessage("e.command", ex.getMessage()); } catch (SQLException ex) { log.error(ex); SQLException parent = ex; while (true) { SQLException sqle = parent.getNextException(); if (sqle == null || sqle == parent) { break; } log.error(sqle, "------ SQLException.getNextException ------"); parent = sqle; } outputMessage("e.database", ex.getMessage()); } catch (UnsupportedOperationException ex) { log.warn(ex); outputMessage("e.unsupported", ex.getMessage()); } catch (RuntimeException ex) { log.error(ex); outputMessage("e.runtime", ex.getMessage()); } catch (Throwable th) { log.fatal(th); outputMessage("e.fatal", th.getMessage()); } try { Connection conn = env.getCurrentConnection(); if (conn != null) { boolean isClosed = conn.isClosed(); if (isClosed) { log.info("connection is already closed"); disconnect(); } } } catch (SQLException ex) { log.warn(ex); } return true; } private boolean invoke(String commandName, Parameter p) throws IOException, SQLException { assert commandName != null; // do nothing if blank if (commandName.length() == 0) { return true; } // exit if (commandName.equalsIgnoreCase("exit")) { disconnect(); outputMessage("i.exit"); return false; } // connect if (commandName.equalsIgnoreCase("connect") || commandName.equalsIgnoreCase("-c")) { connect(p); return true; } // from file if (commandName.equals("-f")) { final File file = Path.resolve(env.getCurrentDirectory(), p.at(1)); final String abspath = file.getAbsolutePath(); if (log.isDebugEnabled()) { log.debug("absolute path = [%s]", abspath); } if (!file.isFile()) { outputMessage("e.file-not-exists", abspath); throw new UsageException(res.get("usage.-f")); } log.debug("-f %s", file.getAbsolutePath()); invoke(String.format("%s%s", Command.readFileAsString(file), p.after(2))); return true; } // script if (commandName.equals("-s")) { if (!p.has(1)) { throw new UsageException(res.get("usage.-s")); } final String p1 = p.at(1); if (p1.equals(".")) { env.initializeScriptContext(); outputMessage("i.script-context-initialized"); return true; } final File file; if (p1.contains(".")) { // by extension file = Path.resolve(env.getCurrentDirectory(), p1); if (!file.exists() || !file.isFile()) { outputMessage("e.file-not-exists", p1); return true; } log.debug("script file: %s", file.getAbsolutePath()); } else { // by name file = null; log.debug("script name: %s", p1); } ScriptEngine engine = (file == null) ? new ScriptEngineManager().getEngineByName(p1) : new ScriptEngineManager().getEngineByExtension(Path.getExtension(file)); if (engine == null) { outputMessage("e.unsupported", p1); return true; } engine.setContext(env.getScriptContext()); engine.put("connection", env.getCurrentConnection()); engine.put("conn", env.getCurrentConnection()); engine.put("patameter", p); engine.put("p", p); engine.put("outputProcessor", op); engine.put("op", op); try { if (file == null) { engine.put(ScriptEngine.FILENAME, null); engine.eval(p.after(2)); } else { engine.put(ScriptEngine.FILENAME, file.getAbsolutePath()); Reader r = new FileReader(file); try { engine.eval(r); } finally { r.close(); } } } catch (Exception ex) { throw new CommandException(ex); } return true; } // alias AliasMap aliasMap = env.getAliasMap(); if (commandName.equalsIgnoreCase("alias") || commandName.equalsIgnoreCase("unalias")) { aliasMap.reload(); if (commandName.equalsIgnoreCase("alias")) { if (p.has(2)) { final String keyword = p.at(1); if (isUsableKeywordForAlias(keyword)) { outputMessage("w.unusable-keyword-for-alias", keyword); return true; } aliasMap.setValue(keyword, p.after(2)); aliasMap.save(); } else if (p.has(1)) { final String keyword = p.at(1); if (isUsableKeywordForAlias(keyword)) { outputMessage("w.unusable-keyword-for-alias", keyword); return true; } if (aliasMap.containsKey(keyword)) { outputMessage("i.dump-alias", keyword, aliasMap.getValue(keyword)); } } else { if (aliasMap.isEmpty()) { outputMessage("i.noalias"); } else { for (final String key : new TreeSet<String>(aliasMap.keys())) { outputMessage("i.dump-alias", key, aliasMap.getValue(key)); } } } } else if (commandName.equalsIgnoreCase("unalias")) { if (p.has(1)) { aliasMap.remove(p.at(1)); aliasMap.save(); } else { throw new UsageException(res.get("usage.unalias")); } } return true; } else if (aliasMap.containsKey(commandName)) { final String command = aliasMap.expand(commandName, p); op.output(" >> " + command); invoke(command); return true; } // cd if (commandName.equalsIgnoreCase("cd")) { if (!p.has(1)) { throw new UsageException(res.get("usage.cd")); } File olddir = env.getCurrentDirectory(); final String path = p.at(1); final File dir = new File(path); final File newdir = ((dir.isAbsolute()) ? dir : new File(olddir, path)).getCanonicalFile(); if (!newdir.isDirectory()) { outputMessage("e.dir-not-exists", newdir); return true; } env.setCurrentDirectory(newdir); outputMessage("i.directory-changed", olddir.getAbsolutePath(), newdir.getAbsolutePath()); return true; } // at if (commandName.equals("@")) { final String currentDirectory = env.getCurrentDirectory().getAbsolutePath(); final String systemDirectory = Bootstrap.getSystemDirectory().getAbsolutePath(); op.output(String.format("current dir : %s", currentDirectory)); op.output(String.format("system dir : %s", systemDirectory)); return true; } // report - if (commandName.equals("-")) { return invoke("report -"); } // runtime informations if (commandName.equals("?")) { if (p.has(1)) { for (final String k : p.asArray()) { if (k.equals("?")) { continue; } final String s = System.getProperties().containsKey(k) ? String.format("[%s]", System.getProperty(k)) : "undefined"; op.output(String.format("%s=%s", k, s)); } } else { op.output(String.format("JRE : %s %s", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"))); op.output(String.format("OS : %s (osver=%s)", System.getProperty("os.name"), System.getProperty("os.version"))); op.output(String.format("Locale : %s", Locale.getDefault())); } return true; } // connection Connection conn = env.getCurrentConnection(); if (conn == null) { outputMessage("e.not-connect"); } else if (commandName.equalsIgnoreCase("disconnect") || commandName.equalsIgnoreCase("-d")) { disconnect(); outputMessage("i.disconnected"); } else if (commandName.equalsIgnoreCase("commit")) { conn.commit(); outputMessage("i.committed"); } else if (commandName.equalsIgnoreCase("rollback")) { conn.rollback(); outputMessage("i.rollbacked"); } else { executeDynamicCommand(commandName, conn, p); } return true; } private static boolean isUsableKeywordForAlias(String keyword) { return keyword != null && keyword.matches("(?i)-.*|exit|alias|unalias"); } private void connect(Parameter p) throws SQLException { log.info("connect start"); disconnect(); final String id = p.at(1); Connector connector; if (!p.has(1)) { connector = AnonymousConnector.getConnector(id, p.at(2), p.at(3)); } else if (id.indexOf('@') >= 0) { connector = AnonymousConnector.getConnector(id); } else { connector = env.getConnectorMap().getConnector(id); } if (connector != null) { env.establishConnection(connector); } else { outputMessage("e.no-connector", id); } log.info("connect end"); } private void disconnect() { log.debug("disconnect start"); try { env.releaseConnection(); } catch (SQLException ex) { outputMessage("w.connection-closed-abnormally"); } log.debug("disconnect end"); } private void executeDynamicCommand(String commandName, Connection conn, Parameter p) { assert commandName != null && !commandName.contains(" "); final String fqcn; if (commandName.indexOf('.') > 0) { fqcn = commandName; } else { fqcn = "net.argius.stew.command." + commandName.substring(0, 1).toUpperCase() + commandName.substring(1).toLowerCase(); } Class<? extends Command> c; try { c = DynamicLoader.loadClass(fqcn); } catch (DynamicLoadingException ex) { c = Command.isSelect(p.asString()) ? Select.class : UpdateAndOthers.class; } Command command = DynamicLoader.newInstance(c); try { Connector connector = env.getCurrentConnector(); if (connector.isReadOnly() && !command.isReadOnly()) { outputMessage("e.readonly"); return; } command.setEnvironment(env); log.info("command: %s start", command); log.debug(p); command.initialize(); command.execute(conn, p); } finally { command.close(); } log.info("command: %s end", command); } /** * Outputs message. * @param id message-id (resource) * @param args * @throws CommandException */ void outputMessage(String id, Object... args) throws CommandException { op.output(res.get(id, args)); } /** * SQL statement command. */ abstract static class RawSQL extends Command { @Override public final void execute(Connection conn, Parameter parameter) throws CommandException { final String rawString = parameter.asString(); try { Statement stmt = prepareStatement(conn, rawString); try { execute(stmt, rawString); } finally { stmt.close(); } } catch (SQLException ex) { throw new CommandException(ex); } } protected abstract void execute(Statement stmt, String sql) throws SQLException; } /** * Select statement command. */ static final class Select extends RawSQL { public Select() { // empty } @Override public boolean isReadOnly() { return true; } @Override public void execute(Statement stmt, String rawString) throws SQLException { final long startTime = System.currentTimeMillis(); ResultSet rs = executeQuery(stmt, rawString); try { outputMessage("i.response-time", (System.currentTimeMillis() - startTime) / 1000f); ResultSetReference ref = new ResultSetReference(rs, rawString); output(ref); outputMessage("i.selected", ref.getRecordCount()); } finally { rs.close(); } } } /** * Update statement (contains all SQL excepted a Select SQL) command. */ static final class UpdateAndOthers extends RawSQL { public UpdateAndOthers() { // empty } @Override public boolean isReadOnly() { return false; } @Override protected void execute(Statement stmt, String sql) throws SQLException { final int updatedCount = executeUpdate(stmt, sql); final String msgId; if (sql.matches("(?i)\\s*UPDATE.*")) { msgId = "i.updated"; } else if (sql.matches("(?i)\\\\s*INSERT.*")) { msgId = "i.inserted"; } else if (sql.matches("(?i)\\\\s*DELETE.*")) { msgId = "i.deleted"; } else { msgId = "i.proceeded"; } outputMessage(msgId, updatedCount); } } }
src/net/argius/stew/CommandProcessor.java
package net.argius.stew; import java.io.*; import java.sql.*; import java.util.*; import javax.script.*; import net.argius.stew.io.*; import net.argius.stew.ui.*; /** * Command Processor. */ final class CommandProcessor { private static Logger log = Logger.getLogger(CommandProcessor.class); private static ResourceManager res = ResourceManager.getInstance(Command.class); private static final String HYPHEN_E = "-e"; private final Environment env; private final OutputProcessor op; CommandProcessor(Environment env) { this.env = env; this.op = env.getOutputProcessor(); } /** * Invokes this command. * @param parameterString * @return whether this application continues or not * @throws CommandException */ boolean invoke(String parameterString) throws CommandException { Parameter p = new Parameter(parameterString); if (parameterString.replaceFirst("^\\s+", "").startsWith(HYPHEN_E)) { final int offset = parameterString.indexOf(HYPHEN_E) + 2; for (String s : parameterString.substring(offset).split(HYPHEN_E)) { op.output(" >> " + s); if (!invoke(s)) { outputMessage("w.exit-not-available-in-sequencial-command"); } } return true; } final String commandName = p.at(0); try { return invoke(commandName, new Parameter(parameterString)); } catch (UsageException ex) { outputMessage("e.usage", commandName, ex.getMessage()); } catch (DynamicLoadingException ex) { log.error(ex); outputMessage("e.not-found", commandName); } catch (CommandException ex) { log.error(ex); Throwable cause = ex.getCause(); String message = (cause == null) ? ex.getMessage() : cause.getMessage(); outputMessage("e.command", message); } catch (IOException ex) { log.error(ex); outputMessage("e.command", ex.getMessage()); } catch (SQLException ex) { log.error(ex); SQLException parent = ex; while (true) { SQLException sqle = parent.getNextException(); if (sqle == null || sqle == parent) { break; } log.error(sqle, "------ SQLException.getNextException ------"); parent = sqle; } outputMessage("e.database", ex.getMessage()); } catch (UnsupportedOperationException ex) { log.warn(ex); outputMessage("e.unsupported", ex.getMessage()); } catch (RuntimeException ex) { log.error(ex); outputMessage("e.runtime", ex.getMessage()); } catch (Throwable th) { log.fatal(th); outputMessage("e.fatal", th.getMessage()); } try { Connection conn = env.getCurrentConnection(); if (conn != null) { boolean isClosed = conn.isClosed(); if (isClosed) { log.info("connection is already closed"); disconnect(); } } } catch (SQLException ex) { log.warn(ex); } return true; } private boolean invoke(String commandName, Parameter p) throws IOException, SQLException { assert commandName != null; // do nothing if blank if (commandName.length() == 0) { return true; } // exit if (commandName.equalsIgnoreCase("exit")) { disconnect(); outputMessage("i.exit"); return false; } // connect if (commandName.equalsIgnoreCase("connect") || commandName.equalsIgnoreCase("-c")) { connect(p); return true; } // from file if (commandName.equals("-f")) { final File file = Path.resolve(env.getCurrentDirectory(), p.at(1)); if (!file.isFile()) { throw new UsageException(res.get("usage.-f")); } log.debug("-f %s", file.getAbsolutePath()); invoke(String.format("%s%s", Command.readFileAsString(file), p.after(2))); return true; } // script if (commandName.equals("-s")) { if (!p.has(1)) { throw new UsageException(res.get("usage.-s")); } final String p1 = p.at(1); if (p1.equals(".")) { env.initializeScriptContext(); outputMessage("i.script-context-initialized"); return true; } final File file; if (p1.contains(".")) { // by extension file = Path.resolve(env.getCurrentDirectory(), p1); if (!file.exists() || !file.isFile()) { outputMessage("e.file-not-exists", p1); return true; } log.debug("script file: %s", file.getAbsolutePath()); } else { // by name file = null; log.debug("script name: %s", p1); } ScriptEngine engine = (file == null) ? new ScriptEngineManager().getEngineByName(p1) : new ScriptEngineManager().getEngineByExtension(Path.getExtension(file)); if (engine == null) { outputMessage("e.unsupported", p1); return true; } engine.setContext(env.getScriptContext()); engine.put("connection", env.getCurrentConnection()); engine.put("conn", env.getCurrentConnection()); engine.put("patameter", p); engine.put("p", p); engine.put("outputProcessor", op); engine.put("op", op); try { if (file == null) { engine.put(ScriptEngine.FILENAME, null); engine.eval(p.after(2)); } else { engine.put(ScriptEngine.FILENAME, file.getAbsolutePath()); Reader r = new FileReader(file); try { engine.eval(r); } finally { r.close(); } } } catch (Exception ex) { throw new CommandException(ex); } return true; } // alias AliasMap aliasMap = env.getAliasMap(); if (commandName.equalsIgnoreCase("alias") || commandName.equalsIgnoreCase("unalias")) { aliasMap.reload(); if (commandName.equalsIgnoreCase("alias")) { if (p.has(2)) { final String keyword = p.at(1); if (isUsableKeywordForAlias(keyword)) { outputMessage("w.unusable-keyword-for-alias", keyword); return true; } aliasMap.setValue(keyword, p.after(2)); aliasMap.save(); } else if (p.has(1)) { final String keyword = p.at(1); if (isUsableKeywordForAlias(keyword)) { outputMessage("w.unusable-keyword-for-alias", keyword); return true; } if (aliasMap.containsKey(keyword)) { outputMessage("i.dump-alias", keyword, aliasMap.getValue(keyword)); } } else { if (aliasMap.isEmpty()) { outputMessage("i.noalias"); } else { for (final String key : new TreeSet<String>(aliasMap.keys())) { outputMessage("i.dump-alias", key, aliasMap.getValue(key)); } } } } else if (commandName.equalsIgnoreCase("unalias")) { if (p.has(1)) { aliasMap.remove(p.at(1)); aliasMap.save(); } else { throw new UsageException(res.get("usage.unalias")); } } return true; } else if (aliasMap.containsKey(commandName)) { final String command = aliasMap.expand(commandName, p); op.output(" >> " + command); invoke(command); return true; } // cd if (commandName.equalsIgnoreCase("cd")) { if (!p.has(1)) { throw new UsageException(res.get("usage.cd")); } File olddir = env.getCurrentDirectory(); final String path = p.at(1); final File dir = new File(path); final File newdir = ((dir.isAbsolute()) ? dir : new File(olddir, path)).getCanonicalFile(); if (!newdir.isDirectory()) { outputMessage("e.dir-not-exists", newdir); return true; } env.setCurrentDirectory(newdir); outputMessage("i.directory-changed", olddir.getAbsolutePath(), newdir.getAbsolutePath()); return true; } // at if (commandName.equals("@")) { final String currentDirectory = env.getCurrentDirectory().getAbsolutePath(); final String systemDirectory = Bootstrap.getSystemDirectory().getAbsolutePath(); op.output(String.format("current dir : %s", currentDirectory)); op.output(String.format("system dir : %s", systemDirectory)); return true; } // report - if (commandName.equals("-")) { return invoke("report -"); } // runtime informations if (commandName.equals("?")) { if (p.has(1)) { for (final String k : p.asArray()) { if (k.equals("?")) { continue; } final String s = System.getProperties().containsKey(k) ? String.format("[%s]", System.getProperty(k)) : "undefined"; op.output(String.format("%s=%s", k, s)); } } else { op.output(String.format("JRE : %s %s", System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"))); op.output(String.format("OS : %s (osver=%s)", System.getProperty("os.name"), System.getProperty("os.version"))); op.output(String.format("Locale : %s", Locale.getDefault())); } return true; } // connection Connection conn = env.getCurrentConnection(); if (conn == null) { outputMessage("e.not-connect"); } else if (commandName.equalsIgnoreCase("disconnect") || commandName.equalsIgnoreCase("-d")) { disconnect(); outputMessage("i.disconnected"); } else if (commandName.equalsIgnoreCase("commit")) { conn.commit(); outputMessage("i.committed"); } else if (commandName.equalsIgnoreCase("rollback")) { conn.rollback(); outputMessage("i.rollbacked"); } else { executeDynamicCommand(commandName, conn, p); } return true; } private static boolean isUsableKeywordForAlias(String keyword) { return keyword != null && keyword.matches("(?i)-.*|exit|alias|unalias"); } private void connect(Parameter p) throws SQLException { log.info("connect start"); disconnect(); final String id = p.at(1); Connector connector; if (!p.has(1)) { connector = AnonymousConnector.getConnector(id, p.at(2), p.at(3)); } else if (id.indexOf('@') >= 0) { connector = AnonymousConnector.getConnector(id); } else { connector = env.getConnectorMap().getConnector(id); } if (connector != null) { env.establishConnection(connector); } else { outputMessage("e.no-connector", id); } log.info("connect end"); } private void disconnect() { log.debug("disconnect start"); try { env.releaseConnection(); } catch (SQLException ex) { outputMessage("w.connection-closed-abnormally"); } log.debug("disconnect end"); } private void executeDynamicCommand(String commandName, Connection conn, Parameter p) { assert commandName != null && !commandName.contains(" "); final String fqcn; if (commandName.indexOf('.') > 0) { fqcn = commandName; } else { fqcn = "net.argius.stew.command." + commandName.substring(0, 1).toUpperCase() + commandName.substring(1).toLowerCase(); } Class<? extends Command> c; try { c = DynamicLoader.loadClass(fqcn); } catch (DynamicLoadingException ex) { c = Command.isSelect(p.asString()) ? Select.class : UpdateAndOthers.class; } Command command = DynamicLoader.newInstance(c); try { Connector connector = env.getCurrentConnector(); if (connector.isReadOnly() && !command.isReadOnly()) { outputMessage("e.readonly"); return; } command.setEnvironment(env); log.info("command: %s start", command); log.debug(p); command.initialize(); command.execute(conn, p); } finally { command.close(); } log.info("command: %s end", command); } /** * Outputs message. * @param id message-id (resource) * @param args * @throws CommandException */ void outputMessage(String id, Object... args) throws CommandException { op.output(res.get(id, args)); } /** * SQL statement command. */ abstract static class RawSQL extends Command { @Override public final void execute(Connection conn, Parameter parameter) throws CommandException { final String rawString = parameter.asString(); try { Statement stmt = prepareStatement(conn, rawString); try { execute(stmt, rawString); } finally { stmt.close(); } } catch (SQLException ex) { throw new CommandException(ex); } } protected abstract void execute(Statement stmt, String sql) throws SQLException; } /** * Select statement command. */ static final class Select extends RawSQL { public Select() { // empty } @Override public boolean isReadOnly() { return true; } @Override public void execute(Statement stmt, String rawString) throws SQLException { final long startTime = System.currentTimeMillis(); ResultSet rs = executeQuery(stmt, rawString); try { outputMessage("i.response-time", (System.currentTimeMillis() - startTime) / 1000f); ResultSetReference ref = new ResultSetReference(rs, rawString); output(ref); outputMessage("i.selected", ref.getRecordCount()); } finally { rs.close(); } } } /** * Update statement (contains all SQL excepted a Select SQL) command. */ static final class UpdateAndOthers extends RawSQL { public UpdateAndOthers() { // empty } @Override public boolean isReadOnly() { return false; } @Override protected void execute(Statement stmt, String sql) throws SQLException { final int updatedCount = executeUpdate(stmt, sql); final String msgId; if (sql.matches("(?i)\\s*UPDATE.*")) { msgId = "i.updated"; } else if (sql.matches("(?i)\\\\s*INSERT.*")) { msgId = "i.inserted"; } else if (sql.matches("(?i)\\\\s*DELETE.*")) { msgId = "i.deleted"; } else { msgId = "i.proceeded"; } outputMessage(msgId, updatedCount); } } }
indicate the absolute path when using -f option with a invalid path
src/net/argius/stew/CommandProcessor.java
indicate the absolute path when using -f option with a invalid path
Java
apache-2.0
65d98777900cbaccd9cf1d0b0e808e726a779ed0
0
shutkou/ios-driver,adataylor/ios-driver,shutkou/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,crashlytics/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,darraghgrace/ios-driver,shutkou/ios-driver,adataylor/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,crashlytics/ios-driver,azaytsev/ios-driver,masbog/ios-driver,crashlytics/ios-driver,crashlytics/ios-driver,seem-sky/ios-driver,ios-driver/ios-driver,masbog/ios-driver,adataylor/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,ios-driver/ios-driver,shutkou/ios-driver,darraghgrace/ios-driver,crashlytics/ios-driver,darraghgrace/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,masbog/ios-driver,azaytsev/ios-driver,seem-sky/ios-driver,shutkou/ios-driver
package org.uiautomation.ios.ide.views; import javax.servlet.http.HttpServletResponse; import org.uiautomation.ios.UIAModels.Orientation; import org.uiautomation.ios.communication.IOSDevice; import org.uiautomation.ios.exceptions.IOSAutomationException; import org.uiautomation.ios.ide.model.IDESessionModel; import org.uiautomation.ios.ide.views.positioning.IPadDevicePositioning; public class IDEMainView implements View { private final IDESessionModel model; private final String servletPath; public IDEMainView(IDESessionModel model, String servletPath) { this.model = model; this.servletPath = servletPath; } public void render2(HttpServletResponse response) throws Exception { try { StringBuilder b = new StringBuilder(); b.append("<html>"); b.append("<head>"); b.append(" <link rel='stylesheet' href='" + getResource("ide.css") + "' type='text/css'/>"); b.append("<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>"); b.append("<script type='text/javascript' src='" + getResource("jquery.jstree.js") + "'></script>"); IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(), 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree(); /* * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { * b.append("<script > var offsetX = 49; var offsetY = 143;</script>"); } else { * b.append("<script > var offsetY = " + position.getScreenTop() + "; var offsetX = " + * position.getScreenLeft() + ";</script>"); b.append("<script > var realOffsetY = " + * position.getRealScreenTop() + "; var realOffsetX = " + position.getRealScreenLeft() + * ";</script>"); } */ b.append("<script type='text/javascript' src='" + getResource("ide.js") + "'></script>"); b.append("</head>"); b.append("<body>"); b.append("<html>"); b.append("<div id ='highlight' ></div>"); String suffix = "iPad"; if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { suffix = "iPhone"; } String rotate = "-moz-transform:rotate(" + degree + "deg);"; b.append("<div id='frame' "); b.append("style='" + rotate + "top:" + position.getFrameTop() + "px;" + "left : " + position.getFrameLeft() + "px' >" + "<img src='" + getResource("frame" + suffix + ".png") + " '/></div>"); b.append("<div id='mouseOver' " + "style='left:" + position.getRealScreenLeft() + "px;" + "top:" + position.getRealScreenTop() + "px;" + "width:" + position.getRealScreenWidth() + "px;" + "height :" + position.getRealScreenHeight() + "px ' ></div>"); b.append("<div id='screen' " + "style='" + rotate + "top:" + position.getScreenTop() + "px;" + "left:" + position.getScreenLeft() + "px' >" + "<img src='" + getResource("session/" + model.getSession().getSessionId() + "/screenshot.png") + "' /></div>"); b.append("<div id ='tree' ></div>"); b.append("<div id ='details' class='details" + suffix + "'>details</div>"); b.append("<div id ='actions' class='actions" + suffix + "'>actions"); b.append("<form action='tap' method='GET'>"); b.append("<div id ='reference'></div>"); b.append(" <input type='submit' value='tap'>"); b.append("</form>"); b.append("<form action='debug' method='GET'>"); b.append("X: <input type='text' name='x' >"); b.append("Y: <input type='text' name='y' >"); b.append("<input type='submit' value='debugTap'>"); b.append("</form>"); b.append("</div>"); b.append("</body>"); b.append("</html>"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(b.toString()); } catch (Exception e) { throw new IOSAutomationException(e); } } @Override public void render(HttpServletResponse response) throws Exception { try { StringBuilder b = new StringBuilder(); b.append("<html>"); b.append("<head>"); b.append(" <link rel='stylesheet' href='" + getResource("ide.css") + "' type='text/css'/>"); b.append("<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>"); b.append("<script type='text/javascript' src='" + getResource("jquery.jstree.js") + "'></script>"); /* * IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(), * 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree(); */ IOSDevice device = model.getCapabilities().getDevice(); /* * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { * b.append("<script > var offsetX = 49; var offsetY = 143;</script>"); } else { * b.append("<script > var offsetY = " + position.getScreenTop() + "; var offsetX = " + * position.getScreenLeft() + ";</script>"); b.append("<script > var realOffsetY = " + * position.getRealScreenTop() + "; var realOffsetX = " + position.getRealScreenLeft() + * ";</script>"); } */ b.append("<script type='text/javascript' src='" + getResource("ide.js") + "'></script>"); b.append("</head>"); b.append("<body>"); b.append("<html>"); b.append("<div id='simulator'>"); b.append("<div id ='highlight' ></div>"); b.append("<div id='mouseOver'></div>"); b.append(" <div id='rotationCenter'>"); b.append("<div id='frame'>"); b.append("<img src='" + getFrame(device) + "' />"); b.append(" <div id='screen'>"); b.append(" <img src='" + getScreen(device) + "' />"); b.append("</div>"); b.append("</div>"); b.append("</div>"); b.append("</div>"); b.append("<div id ='tree' ></div>"); b.append("<div id ='details' >details</div>"); b.append("<script >configure('ipad','" + model.getDeviceOrientation() + "');</script>"); b.append("</body>"); b.append("</html>"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(b.toString()); } catch (Exception e) { throw new IOSAutomationException(e); } } private String getScreen(IOSDevice device) { return getResource("session/" + model.getSession().getSessionId() + "/screenshot.png"); } private String getFrame(IOSDevice device) { if (device == IOSDevice.iPhoneSimulator) { return getResource("frameiphone.png"); } else { return getResource("frameipad.png"); } } private String getResource(String name) { String res = servletPath + "/resources/" + name; return res; } }
ide/src/main/java/org/uiautomation/ios/ide/views/IDEMainView.java
package org.uiautomation.ios.ide.views; import javax.servlet.http.HttpServletResponse; import org.uiautomation.ios.UIAModels.Orientation; import org.uiautomation.ios.communication.IOSDevice; import org.uiautomation.ios.exceptions.IOSAutomationException; import org.uiautomation.ios.ide.model.IDESessionModel; import org.uiautomation.ios.ide.views.positioning.IPadDevicePositioning; public class IDEMainView implements View { private final IDESessionModel model; private final String servletPath; public IDEMainView(IDESessionModel model, String servletPath) { this.model = model; this.servletPath = servletPath; } public void render2(HttpServletResponse response) throws Exception { try { StringBuilder b = new StringBuilder(); b.append("<html>"); b.append("<head>"); b.append(" <link rel='stylesheet' href='" + getResource("ide.css") + "' type='text/css'/>"); b.append("<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>"); b.append("<script type='text/javascript' src='" + getResource("jquery.jstree.js") + "'></script>"); IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(), 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree(); /* * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { * b.append("<script > var offsetX = 49; var offsetY = 143;</script>"); } else { * b.append("<script > var offsetY = " + position.getScreenTop() + "; var offsetX = " + * position.getScreenLeft() + ";</script>"); b.append("<script > var realOffsetY = " + * position.getRealScreenTop() + "; var realOffsetX = " + position.getRealScreenLeft() + * ";</script>"); } */ b.append("<script type='text/javascript' src='" + getResource("ide.js") + "'></script>"); b.append("</head>"); b.append("<body>"); b.append("<html>"); b.append("<div id ='highlight' ></div>"); String suffix = "iPad"; if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { suffix = "iPhone"; } String rotate = "-moz-transform:rotate(" + degree + "deg);"; b.append("<div id='frame' "); b.append("style='" + rotate + "top:" + position.getFrameTop() + "px;" + "left : " + position.getFrameLeft() + "px' >" + "<img src='" + getResource("frame" + suffix + ".png") + " '/></div>"); b.append("<div id='mouseOver' " + "style='left:" + position.getRealScreenLeft() + "px;" + "top:" + position.getRealScreenTop() + "px;" + "width:" + position.getRealScreenWidth() + "px;" + "height :" + position.getRealScreenHeight() + "px ' ></div>"); b.append("<div id='screen' " + "style='" + rotate + "top:" + position.getScreenTop() + "px;" + "left:" + position.getScreenLeft() + "px' >" + "<img src='" + getResource("session/" + model.getSession().getSessionId() + "/screenshot.png") + "' /></div>"); b.append("<div id ='tree' ></div>"); b.append("<div id ='details' class='details" + suffix + "'>details</div>"); b.append("<div id ='actions' class='actions" + suffix + "'>actions"); b.append("<form action='tap' method='GET'>"); b.append("<div id ='reference'></div>"); b.append(" <input type='submit' value='tap'>"); b.append("</form>"); b.append("<form action='debug' method='GET'>"); b.append("X: <input type='text' name='x' >"); b.append("Y: <input type='text' name='y' >"); b.append("<input type='submit' value='debugTap'>"); b.append("</form>"); b.append("</div>"); b.append("</body>"); b.append("</html>"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(b.toString()); } catch (Exception e) { throw new IOSAutomationException(e); } } @Override public void render(HttpServletResponse response) throws Exception { try { StringBuilder b = new StringBuilder(); b.append("<html>"); b.append("<head>"); b.append(" <link rel='stylesheet' href='" + getResource("ide.css") + "' type='text/css'/>"); b.append("<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>"); b.append("<script type='text/javascript' src='" + getResource("jquery.jstree.js") + "'></script>"); /* * IPadDevicePositioning position = new IPadDevicePositioning(model.getDeviceOrientation(), * 25, 25); int degree = model.getDeviceOrientation().getRotationInDegree(); */ IOSDevice device = model.getCapabilities().getDevice(); /* * if (model.getCapabilities().getDevice() == IOSDevice.iPhoneSimulator) { * b.append("<script > var offsetX = 49; var offsetY = 143;</script>"); } else { * b.append("<script > var offsetY = " + position.getScreenTop() + "; var offsetX = " + * position.getScreenLeft() + ";</script>"); b.append("<script > var realOffsetY = " + * position.getRealScreenTop() + "; var realOffsetX = " + position.getRealScreenLeft() + * ";</script>"); } */ b.append("<script type='text/javascript' src='" + getResource("ide.js") + "'></script>"); b.append("</head>"); b.append("<body>"); b.append("<html>"); b.append("<div id='simulator'>"); b.append("<div id='mouseOver'></div>"); b.append("<div id ='highlight' ></div>"); b.append(" <div id='rotationCenter'>"); b.append("<div id='frame'>"); b.append("<img src='" + getFrame(device) + "' />"); b.append(" <div id='screen'>"); b.append(" <img src='" + getScreen(device) + "' />"); b.append("</div>"); b.append("</div>"); b.append("</div>"); b.append("</div>"); b.append("<div id ='tree' ></div>"); b.append("<div id ='details' >details</div>"); b.append("<script >configure('ipad','" + model.getDeviceOrientation() + "');</script>"); b.append("</body>"); b.append("</html>"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); response.getWriter().print(b.toString()); } catch (Exception e) { throw new IOSAutomationException(e); } } private String getScreen(IOSDevice device) { return getResource("session/" + model.getSession().getSessionId() + "/screenshot.png"); } private String getFrame(IOSDevice device) { if (device == IOSDevice.iPhoneSimulator) { return getResource("frameiphone.png"); } else { return getResource("frameipad.png"); } } private String getResource(String name) { String res = servletPath + "/resources/" + name; return res; } }
formatting
ide/src/main/java/org/uiautomation/ios/ide/views/IDEMainView.java
formatting
Java
apache-2.0
e09c80742ce3c42180513314eb63f178005f07ac
0
intruxxer/twitter4j,matsumo/twitter4j,eunamong/twitter4j,xfxf123444/twitter4j,qingsong-xu/twitter4j,kaosmos/twitter4j,savethejets/twitter4j,tylermac/twitter4j,takke/twitter4j,mumei/twitter4j,afeiluo/twitter4j,lamorin/Twitter4J,intruxxer/twitter4j,savethejets/twitter4j,osamuaoki/twitter4j,DellayHaroun/twitter4j,krallus/twitter4j,fabienfleureau/twitter4j,HubSpot/twitter4j,david8zhang/twitter4j,thedevd/twitter4j,ColinZang/twitter4j,u2i/twitter4j,fabianormatias/twitter4j,yusuke/twitter4j,mumei/twitter4j,matsumo/twitter4j,lithiumtech/twitter4j-pub,thedevd/twitter4j,eunamong/twitter4j,ColinZang/twitter4j,tylermac/twitter4j,osamuaoki/twitter4j,yusuke/twitter4j,lamorin/Twitter4J,fabianormatias/twitter4j,HasanAliKaraca/twitter4j,kaosmos/twitter4j,HubSpot/twitter4j,xfxf123444/twitter4j,fabienfleureau/twitter4j,qingsong-xu/twitter4j,u2i/twitter4j,takke/twitter4j,david8zhang/twitter4j,DellayHaroun/twitter4j,lithiumtech/twitter4j-pub,afeiluo/twitter4j,krallus/twitter4j,HasanAliKaraca/twitter4j
package twitter4j; import twitter4j.http.HttpClient; import twitter4j.http.PostParameter; import twitter4j.http.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * A java reporesentation of the <a href="http://twitter.com/help/api">Twitter API</a> */ public class Twitter implements java.io.Serializable { HttpClient http = null; private String baseURL = "http://twitter.com/"; private String source = "Twitter4J"; private boolean usePostForcibly = false; private static final long serialVersionUID = 4346156413282535531L; private static final int MAX_COUNT = 200; public Twitter() { http = new HttpClient(); setRequestHeader("X-Twitter-Client", "Twitter4J"); setRequestHeader("X-Twitter-Client-Version", "1.1.3"); setRequestHeader("X-Twitter-Client-URL", "http://yusuke.homeip.net/twitter4j/en/twitter4j-1.1.3.xml"); format.setTimeZone(TimeZone.getTimeZone("GMT")); } public Twitter(String baseURL) { this(); this.baseURL = baseURL; } public Twitter(String id, String password) { this(); setUserId(id); setPassword(password); } public Twitter(String id, String password, String baseURL) { this(id, password); this.baseURL = baseURL; } /** * Sets the base URL * * @param baseURL String the base URL */ public void setBaseURL(String baseURL) { this.baseURL = baseURL; } /** * Returns the base URL * * @return the base URL */ public String getBaseURL() { return this.baseURL; } /** * Sets the userid * * @param userId new userid */ public void setUserId(String userId) { http.setUserId(userId); } /** * Returns authenticating userid * * @return userid */ public String getUserId() { return http.getUserId(); } /** * Sets the password * * @param password new password */ public void setPassword(String password) { http.setPassword(password); } /** * Returns authenticating password * * @return password */ public String getPassword() { return http.getPassword(); } /** * Sets the source parameter that will be passed by updating methods * See below for details. * Twitter API Wiki > How do I get “from [my_application]” appended to updates sent from my API application? * http://apiwiki.twitter.com/REST+API+Documentation * * @param source the new source */ public void setSource(String source) { this.source = source; } /** * Returns the source * * @return source */ public String getSource() { return this.source; } /** * sets the request header name/value combination * see Twitter Fan Wiki for detail. * http://twitter.pbwiki.com/API-Docs#RequestHeaders * * @param name the name of the request header * @param value the value of the request header */ public void setRequestHeader(String name, String value) { http.setRequestHeader(name, value); } /** * set true to force using POST method communicating to the server * * @param forceUsePost if true POST method will be used forcibly */ public void forceUsePost(boolean forceUsePost) { this.usePostForcibly = forceUsePost; } /** * @return true if POST is used forcibly */ public boolean isUsePostForced() { return this.usePostForcibly; } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, boolean authenticate) throws TwitterException { return get(url, null, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, String name1, String value1, boolean authenticate) throws TwitterException { return get(url, new PostParameter[]{new PostParameter(name1, value1)}, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @param name2 the name of the second parameter * @param value2 the value of the second parameter * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws TwitterException { return get(url, new PostParameter[]{new PostParameter(name1, value1), new PostParameter(name2, value2)}, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param params the request parameters * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, PostParameter[] params, boolean authenticate) throws TwitterException { if (usePostForcibly) { if (null == params) { return http.post(url, new PostParameter[0], authenticate); } else { return http.post(url, params, authenticate); } } else { if (null != params && params.length > 0) { url += "?" + HttpClient.encodeParameters(params); } return http.get(url, authenticate); } } /* Status Methods */ /** * Returns the 20 most recent statuses from non-protected users who have set a custom user icon. * * @return list of statuses of the Public Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getPublicTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/public_timeline.xml", false). asDocument(), this); } /** * Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. * * @param sinceID returns only public statuses with an ID greater than (that is, more recent than) the specified ID * @return the 20 most recent statuses * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getPublicTimeline(int sinceID) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/public_timeline.xml", "since_id", String.valueOf(sinceID), false). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends. * It's also possible to request another user's friends_timeline via the id parameter below. * * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", true). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user. * * @param page the number of page * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimelineByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", true).asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @param page the number of page * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimelineByPage(String id, int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user. * * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(String id, Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the user Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, int count, Date since) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "since", format.format(since), "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, int count) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(int count, Date since) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline.xml", "since", format.format(since), "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline.xml", true). asDocument(), this); } /** * Returns a single status, specified by the id parameter. The status's author will be returned inline. * * @param id the numerical ID of the status you're trying to retrieve * @return a single status * @throws TwitterException when Twitter service or network is unavailable * @deprecated Use show(long id) instead. */ public synchronized Status show(int id) throws TwitterException { return new Status(get(baseURL + "statuses/show/" + id + ".xml", false).asDocument().getDocumentElement(), this); } /** * Returns a single status, specified by the id parameter. The status's author will be returned inline. * * @param id the numerical ID of the status you're trying to retrieve * @return a single status * @throws TwitterException when Twitter service or network is unavailable * @since 1.1.1 */ public synchronized Status show(long id) throws TwitterException { return new Status(get(baseURL + "statuses/show/" + id + ".xml", false).asDocument().getDocumentElement(), this); } /** * Updates the user's status. * The text will be trimed if the length of the text is exceeding 160 characters. * * @param status the text of your status update * @return the latest status * @throws TwitterException when Twitter service or network is unavailable */ public Status update(String status) throws TwitterException { if (status.length() > 160) { status = status.substring(0, 160); } return new Status(http.post(baseURL + "statuses/update.xml", new PostParameter[]{new PostParameter("status", status), new PostParameter("source", source)}, true).asDocument().getDocumentElement(), this); } /** * Returns the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected. * * @return the 20 most recent replies * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getReplies() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/replies.xml", true).asDocument(), this); } /** * Returns the most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected. * * @param page the number of page * @return the 20 most recent replies * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getRepliesByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/replies.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. * * @param statusId The ID of the status to destroy. * @return the deleted status * @throws TwitterException when Twitter service or network is unavailable * @since 1.0.5 */ public Status destroyStatus(long statusId) throws TwitterException { return new Status(http.post(baseURL + "statuses/destroy/" + statusId + ".xml", new PostParameter[0], true).asDocument().getDocumentElement(), this); } /* User Methods */ /** * Returns the specified user's friends, each with current status inline. * * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", true).asDocument(), this); } /** * Returns the specified user's friends, each with current status inline. * * @param page number of page * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the user's friends, each with current status inline. * * @param id the ID or screen name of the user for whom to request a list of friends * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(String id) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "id", id, true).asDocument(), this); } /** * Returns the user's friends, each with current status inline. * * @param id the ID or screen name of the user for whom to request a list of friends * @param page the number of page * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(String id, int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "id", id, "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFollowers() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers.xml", true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param page Retrieves the next 100 followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param id The ID or screen name of the user for whom to request a list of followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(String id) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers/" + id + ".xml", true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param id The ID or screen name of the user for whom to request a list of followers. * @param page Retrieves the next 100 followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(String id, int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers/" + id + ".xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns a list of the users currently featured on the site with their current statuses inline. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFeatured() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/featured.xml", true).asDocument(), this); } /** * Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences. * * @param id the ID or screen name of the user for whom to request the detail * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized UserWithStatus getUserDetail(String id) throws TwitterException { return new UserWithStatus(get(baseURL + "users/show/" + id + ".xml", true).asDocument().getDocumentElement(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages() throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param page the number of page * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessagesByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param sinceId int * @return list of direct messages * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages(int sinceId) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "since_id", String.valueOf(sinceId), true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date * @return list of direct messages * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages(Date since) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages() throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", new PostParameter[0], true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages(Date since) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @param sinceId returns only sent direct messages with an ID greater than (that is, more recent than) the specified ID * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages(int sinceId) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", "since_id", String.valueOf(sinceId), true).asDocument(), this); } /** * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below. * The text will be trimed if the length of the text is exceeding 140 characters. * * @param id the ID or screen name of the user to whom send the direct message * @param text String * @return DirectMessage * @throws TwitterException when Twitter service or network is unavailable */ public synchronized DirectMessage sendDirectMessage(String id, String text) throws TwitterException { if (text.length() > 160) { text = text.substring(0, 160); } return new DirectMessage(http.post(baseURL + "direct_messages/new.xml", new PostParameter[]{new PostParameter("user", id), new PostParameter("text", text)}, true). asDocument().getDocumentElement(), this); } /** * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message. * * @param id the ID of the direct message to destroy * @return the deleted direct message * @throws TwitterException when Twitter service or network is unavailable */ public synchronized DirectMessage deleteDirectMessage(int id) throws TwitterException { return new DirectMessage(http.post(baseURL + "direct_messages/destroy/" + id + ".xml", new PostParameter[0], true).asDocument().getDocumentElement(), this); } /** * Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user to be befriended * @return the befriended user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User create(String id) throws TwitterException { return new User(http.post(baseURL + "friendships/create/" + id + ".xml", new PostParameter[0], true). asDocument().getDocumentElement(), this); } /** * Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user for whom to request a list of friends * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User destroy(String id) throws TwitterException { return new User(http.post(baseURL + "friendships/destroy/" + id + ".xml", new PostParameter[0], true). asDocument().getDocumentElement(), this); } /** * Returns true if authentication was successful. Use this method to test if supplied user credentials are valid with minimal overhead. * * @return success */ public synchronized boolean verifyCredentials() { try { return get(baseURL + "account/verify_credentials.xml", true).getStatusCode() == 200; } catch (TwitterException te) { return false; } } /** * Update the location * * @param location the current location of the user * @return the updated user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User updateLocation(String location) throws TwitterException { return new User(http.post(baseURL + "account/update_location.xml", new PostParameter[]{new PostParameter("location", location)}, true). asDocument().getDocumentElement(), this); } /** * Returns the remaining number of API requests available to the requesting user before the API limit is reached for the current hour. Calls to rate_limit_status do not count against the rate limit. If authentication credentials are provided, the rate limit status for the authenticating user is returned. Otherwise, the rate limit status for the requester's IP address is returned.<br> * See <a href="http://apiwiki.twitter.com/REST%20API%20Documentation#ratelimitstatus">Twitter REST API Documentation &gt; Account Methods &gt; rate_limit_status</a> for detail. * * @return the rate limit status * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.4 */ public synchronized RateLimitStatus rateLimitStatus() throws TwitterException { return new RateLimitStatus(http.get(baseURL + "account/rate_limit_status.xml", null != getUserId() && null != getPassword()). asDocument().getDocumentElement()); } public final static Device IM = new Device("im"); public final static Device SMS = new Device("sms"); public final static Device NONE = new Device("none"); static class Device { final String DEVICE; public Device(String device) { DEVICE = device; } } /** * Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable IM or SMS updates. * * @param device new Delivery device. Must be one of: IM, SMS, NONE. * @return the updated user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User updateDeliverlyDevice(Device device) throws TwitterException { return new User(http.post(baseURL + "account/update_delivery_device.xml", new PostParameter[]{new PostParameter("device", device.DEVICE)}, true). asDocument().getDocumentElement(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites() throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites.xml", new PostParameter[0], true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param page the number of page * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(int page) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites.xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites/" + id + ".xml", new PostParameter[0], true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @param page the number of page * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(String id, int page) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites/" + id + ".xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. * * @param id the ID of the status to favorite * @return Status * @throws TwitterException when Twitter service or network is unavailable */ public synchronized Status createFavorite(long id) throws TwitterException { return new Status(http.post(baseURL + "favorites/create/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. * * @param id the ID of the status to un-favorite * @return Status * @throws TwitterException when Twitter service or network is unavailable */ public synchronized Status destroyFavorite(long id) throws TwitterException { return new Status(http.post(baseURL + "favorites/destroy/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * * @param id String * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User follow(String id) throws TwitterException { return new User(http.post(baseURL + "notifications/follow/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * * @param id String * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User leave(String id) throws TwitterException { return new User(http.post(baseURL + "notifications/leave/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /* Block Methods */ /** * Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful. * * @param id the ID or screen_name of the user to block * @return the blocked user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User block(String id) throws TwitterException { return new User(http.post(baseURL + "blocks/create/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful. * * @param id the ID or screen_name of the user to block * @return the unblocked user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User unblock(String id) throws TwitterException { return new User(http.post(baseURL + "blocks/destroy/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /* Help Methods */ /* test New as of April 29th, 2008! Returns the string "ok" in the requested format with a 200 OK HTTP status code. URL:http://twitter.com/help/test.format Formats: xml, json */ /** * Returns the string "ok" in the requested format with a 200 OK HTTP status code. * * @return true if the API is working * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized boolean test() throws TwitterException { return -1 != get(baseURL + "help/test.xml", false). asString().indexOf("ok"); } /** * Returns extended information of the authenticated user. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.<br> * The call Twitter.getAuthenticatedUser() is equivalent to the call:<br> * twitter.getUserDetail(twitter.getUserId()); * * @return UserWithStatus * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.3 */ public synchronized UserWithStatus getAuthenticatedUser() throws TwitterException { if(null == getUserId()){ throw new IllegalStateException("User Id not specified."); } return getUserDetail(getUserId()); } /* downtime_schedule New as of April 29th, 2008! Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format. URL:http://twitter.com/help/downtime_schedule.format Formats: xml, json */ /** * Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format. * * @return the schedule * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized String getDowntimeSchedule() throws TwitterException { return get(baseURL + "help/downtime_schedule.xml", false).asString(); } private SimpleDateFormat format = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH); public void setRetryCount(int retryCount) { http.setRetryCount(retryCount); } public void setRetryIntervalSecs(int retryIntervalSecs) { http.setRetryIntervalSecs(retryIntervalSecs); } @Override public int hashCode() { return http.hashCode() + this.baseURL.hashCode() + http.hashCode(); } @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } if (obj instanceof Twitter) { Twitter that = (Twitter) obj; return this.http.equals(that.http) && this.baseURL.equals(that.baseURL) && this.http.equals(that.http); } return false; } @Override public String toString() { return "Twitter{" + "http=" + http + ", baseURL='" + baseURL + '\'' + ", source='" + source + '\'' + ", usePostForcibly=" + usePostForcibly + ", format=" + format + '}'; } }
src/main/java/twitter4j/Twitter.java
package twitter4j; import twitter4j.http.HttpClient; import twitter4j.http.PostParameter; import twitter4j.http.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * A java reporesentation of the <a href="http://twitter.com/help/api">Twitter API</a> */ public class Twitter implements java.io.Serializable { HttpClient http = null; private String baseURL = "http://twitter.com/"; private String source = "Twitter4J"; private boolean usePostForcibly = false; private static final long serialVersionUID = 4346156413282535531L; private static final int MAX_COUNT = 200; public Twitter() { http = new HttpClient(); setRequestHeader("X-Twitter-Client", "Twitter4J"); setRequestHeader("X-Twitter-Client-Version", "1.1.3"); setRequestHeader("X-Twitter-Client-URL", "http://yusuke.homeip.net/twitter4j/en/twitter4j-1.1.3.xml"); format.setTimeZone(TimeZone.getTimeZone("GMT")); } public Twitter(String baseURL) { this(); this.baseURL = baseURL; } public Twitter(String id, String password) { this(); setUserId(id); setPassword(password); } public Twitter(String id, String password, String baseURL) { this(id, password); this.baseURL = baseURL; } /** * Sets the base URL * * @param baseURL String the base URL */ public void setBaseURL(String baseURL) { this.baseURL = baseURL; } /** * Returns the base URL * * @return the base URL */ public String getBaseURL() { return this.baseURL; } /** * Sets the userid * * @param userId new userid */ public void setUserId(String userId) { http.setUserId(userId); } /** * Returns authenticating userid * * @return userid */ public String getUserId() { return http.getUserId(); } /** * Sets the password * * @param password new password */ public void setPassword(String password) { http.setPassword(password); } /** * Returns authenticating password * * @return password */ public String getPassword() { return http.getPassword(); } /** * Sets the source parameter that will be passed by updating methods * See below for details. * Twitter API Wiki > How do I get “from [my_application]” appended to updates sent from my API application? * http://apiwiki.twitter.com/REST+API+Documentation * * @param source the new source */ public void setSource(String source) { this.source = source; } /** * Returns the source * * @return source */ public String getSource() { return this.source; } /** * sets the request header name/value combination * see Twitter Fan Wiki for detail. * http://twitter.pbwiki.com/API-Docs#RequestHeaders * * @param name the name of the request header * @param value the value of the request header */ public void setRequestHeader(String name, String value) { http.setRequestHeader(name, value); } /** * set true to force using POST method communicating to the server * * @param forceUsePost if true POST method will be used forcibly */ public void forceUsePost(boolean forceUsePost) { this.usePostForcibly = forceUsePost; } /** * @return true if POST is used forcibly */ public boolean isUsePostForced() { return this.usePostForcibly; } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, boolean authenticate) throws TwitterException { return get(url, null, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param authenticate if true, the request will be sent with BASIC authentication header * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, String name1, String value1, boolean authenticate) throws TwitterException { return get(url, new PostParameter[]{new PostParameter(name1, value1)}, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param name1 the name of the first parameter * @param value1 the value of the first parameter * @param name2 the name of the second parameter * @param value2 the value of the second parameter * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws TwitterException { return get(url, new PostParameter[]{new PostParameter(name1, value1), new PostParameter(name2, value2)}, authenticate); } /** * issues an HTTP GET request. POST method will be used instead in case forceUsePost is set true. * * @param url the request url * @param params the request parameters * @param authenticate if true, the request will be sent with BASIC authentication header * @return the response * @throws TwitterException when Twitter service or network is unavailable */ private Response get(String url, PostParameter[] params, boolean authenticate) throws TwitterException { if (usePostForcibly) { if (null == params) { return http.post(url, new PostParameter[0], authenticate); } else { return http.post(url, params, authenticate); } } else { if (null != params && params.length > 0) { url += "?" + HttpClient.encodeParameters(params); } return http.get(url, authenticate); } } /* Status Methods */ /** * Returns the 20 most recent statuses from non-protected users who have set a custom user icon. * * @return list of statuses of the Public Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getPublicTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/public_timeline.xml", false). asDocument(), this); } /** * Returns only public statuses with an ID greater than (that is, more recent than) the specified ID. * * @param sinceID returns only public statuses with an ID greater than (that is, more recent than) the specified ID * @return the 20 most recent statuses * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getPublicTimeline(int sinceID) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/public_timeline.xml", "since_id", String.valueOf(sinceID), false). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends. * It's also possible to request another user's friends_timeline via the id parameter below. * * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", true). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user. * * @param page the number of page * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimelineByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", true).asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @param page the number of page * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimelineByPage(String id, int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the 20 most recent statuses posted in the last 24 hours from the authenticating user. * * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the friends_timeline * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the Friends Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getFriendsTimeline(String id, Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/friends_timeline/" + id + ".xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return list of the user Timeline * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, int count, Date since) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "since", format.format(since), "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, Date since) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "since", format.format(since), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id, int count) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * * @param count specifies the number of statuses to retrieve. May not be greater than 200 for performance purposes * @param since narrows the returned results to just those statuses created after the specified HTTP-formatted date * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(int count, Date since) throws TwitterException { if (MAX_COUNT < count) { throw new IllegalArgumentException("count may not be greater than " + MAX_COUNT + " for performance purposes."); } return Status.constructStatuses(get(baseURL + "statuses/user_timeline.xml", "since", format.format(since), "count", String.valueOf(count), true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the specified userid. * * @param id specifies the ID or screen name of the user for whom to return the user_timeline * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline/" + id + ".xml", true).asDocument(), this); } /** * Returns the most recent statuses posted in the last 24 hours from the authenticating user. * * @return the 20 most recent statuses posted in the last 24 hours from the user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getUserTimeline() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/user_timeline.xml", true). asDocument(), this); } /** * Returns a single status, specified by the id parameter. The status's author will be returned inline. * * @param id the numerical ID of the status you're trying to retrieve * @return a single status * @throws TwitterException when Twitter service or network is unavailable * @deprecated Use show(long id) instead. */ public synchronized Status show(int id) throws TwitterException { return new Status(get(baseURL + "statuses/show/" + id + ".xml", false).asDocument().getDocumentElement(), this); } /** * Returns a single status, specified by the id parameter. The status's author will be returned inline. * * @param id the numerical ID of the status you're trying to retrieve * @return a single status * @throws TwitterException when Twitter service or network is unavailable * @since 1.1.1 */ public synchronized Status show(long id) throws TwitterException { return new Status(get(baseURL + "statuses/show/" + id + ".xml", false).asDocument().getDocumentElement(), this); } /** * Updates the user's status. * The text will be trimed if the length of the text is exceeding 160 characters. * * @param status the text of your status update * @return the latest status * @throws TwitterException when Twitter service or network is unavailable */ public Status update(String status) throws TwitterException { if (status.length() > 160) { status = status.substring(0, 160); } return new Status(http.post(baseURL + "statuses/update.xml", new PostParameter[]{new PostParameter("status", status), new PostParameter("source", source)}, true).asDocument().getDocumentElement(), this); } /** * Returns the 20 most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected. * * @return the 20 most recent replies * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getReplies() throws TwitterException { return Status.constructStatuses(get(baseURL + "statuses/replies.xml", true).asDocument(), this); } /** * Returns the most recent replies (status updates prefixed with @username) to the authenticating user. Replies are only available to the authenticating user; you can not request a list of replies to another user whether public or protected. * * @param page the number of page * @return the 20 most recent replies * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> getRepliesByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return Status.constructStatuses(get(baseURL + "statuses/replies.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. * * @param statusId The ID of the status to destroy. * @return the deleted status * @throws TwitterException when Twitter service or network is unavailable * @since 1.0.5 */ public Status destroyStatus(long statusId) throws TwitterException { return new Status(http.post(baseURL + "statuses/destroy/" + statusId + ".xml", new PostParameter[0], true).asDocument().getDocumentElement(), this); } /* User Methods */ /** * Returns the specified user's friends, each with current status inline. * * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", true).asDocument(), this); } /** * Returns the specified user's friends, each with current status inline. * * @param page number of page * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the user's friends, each with current status inline. * * @param id the ID or screen name of the user for whom to request a list of friends * @return the list of friends * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(String id) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "id", id, true).asDocument(), this); } /** * Returns the user's friends, each with current status inline. * * @param id the ID or screen name of the user for whom to request a list of friends * @param page the number of page * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFriends(String id, int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/friends.xml", "id", id, "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFollowers() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers.xml", true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param page Retrieves the next 100 followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param id The ID or screen name of the user for whom to request a list of followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(String id) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers/" + id + ".xml", true).asDocument(), this); } /** * Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Twitter (this is going to be changed). * * @param id The ID or screen name of the user for whom to request a list of followers. * @param page Retrieves the next 100 followers. * @return List * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.0 */ public synchronized List<User> getFollowers(String id, int page) throws TwitterException { return User.constructUsers(get(baseURL + "statuses/followers/" + id + ".xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns a list of the users currently featured on the site with their current statuses inline. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<User> getFeatured() throws TwitterException { return User.constructUsers(get(baseURL + "statuses/featured.xml", true).asDocument(), this); } /** * Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences. * * @param id the ID or screen name of the user for whom to request the detail * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized UserWithStatus getUserDetail(String id) throws TwitterException { return new UserWithStatus(get(baseURL + "users/show/" + id + ".xml", true).asDocument().getDocumentElement(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages() throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param page the number of page * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessagesByPage(int page) throws TwitterException { if (page < 1) { throw new IllegalArgumentException("page should be positive integer. passed:" + page); } return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "page", String.valueOf(page), true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param sinceId int * @return list of direct messages * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages(int sinceId) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "since_id", String.valueOf(sinceId), true).asDocument(), this); } /** * Returns a list of the direct messages sent to the authenticating user. * * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date * @return list of direct messages * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getDirectMessages(Date since) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages() throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", new PostParameter[0], true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @param since narrows the resulting list of direct messages to just those sent after the specified HTTP-formatted date * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages(Date since) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", "since", format.format(since), true).asDocument(), this); } /** * Returns a list of the direct messages sent by the authenticating user. * * @param sinceId returns only sent direct messages with an ID greater than (that is, more recent than) the specified ID * @return List * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<DirectMessage> getSentDirectMessages(int sinceId) throws TwitterException { return DirectMessage.constructDirectMessages(get(baseURL + "direct_messages/sent.xml", "since_id", String.valueOf(sinceId), true).asDocument(), this); } /** * Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below. * The text will be trimed if the length of the text is exceeding 140 characters. * * @param id the ID or screen name of the user to whom send the direct message * @param text String * @return DirectMessage * @throws TwitterException when Twitter service or network is unavailable */ public synchronized DirectMessage sendDirectMessage(String id, String text) throws TwitterException { if (text.length() > 160) { text = text.substring(0, 160); } return new DirectMessage(http.post(baseURL + "direct_messages/new.xml", new PostParameter[]{new PostParameter("user", id), new PostParameter("text", text)}, true). asDocument().getDocumentElement(), this); } /** * Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message. * * @param id the ID of the direct message to destroy * @return the deleted direct message * @throws TwitterException when Twitter service or network is unavailable */ public synchronized DirectMessage deleteDirectMessage(int id) throws TwitterException { return new DirectMessage(http.post(baseURL + "direct_messages/destroy/" + id + ".xml", new PostParameter[0], true).asDocument().getDocumentElement(), this); } /** * Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user to be befriended * @return the befriended user * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User create(String id) throws TwitterException { return new User(http.post(baseURL + "friendships/create/" + id + ".xml", new PostParameter[0], true). asDocument().getDocumentElement(), this); } /** * Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. * * @param id the ID or screen name of the user for whom to request a list of friends * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User destroy(String id) throws TwitterException { return new User(http.post(baseURL + "friendships/destroy/" + id + ".xml", new PostParameter[0], true). asDocument().getDocumentElement(), this); } /** * Returns true if authentication was successful. Use this method to test if supplied user credentials are valid with minimal overhead. * * @return success */ public synchronized boolean verifyCredentials() { try { return get(baseURL + "account/verify_credentials.xml", true).getStatusCode() == 200; } catch (TwitterException te) { return false; } } /** * Update the location * * @param location the current location of the user * @return the updated user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User updateLocation(String location) throws TwitterException { return new User(http.post(baseURL + "account/update_location.xml", new PostParameter[]{new PostParameter("location", location)}, true). asDocument().getDocumentElement(), this); } /** * Returns the remaining number of API requests available to the requesting user before the API limit is reached for the current hour. Calls to rate_limit_status do not count against the rate limit. If authentication credentials are provided, the rate limit status for the authenticating user is returned. Otherwise, the rate limit status for the requester's IP address is returned.<br> * See <a href="http://apiwiki.twitter.com/REST%20API%20Documentation#ratelimitstatus">Twitter REST API Documentation &gt; Account Methods &gt; rate_limit_status</a> for detail. * * @return the rate limit status * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.4 */ public synchronized RateLimitStatus rateLimitStatus() throws TwitterException { return new RateLimitStatus(http.get(baseURL + "account/rate_limit_status.xml", null != getUserId() && null != getPassword()). asDocument().getDocumentElement()); } public final static Device IM = new Device("im"); public final static Device SMS = new Device("sms"); public final static Device NONE = new Device("none"); static class Device { final String DEVICE; public Device(String device) { DEVICE = device; } } /** * Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable IM or SMS updates. * * @param device new Delivery device. Must be one of: IM, SMS, NONE. * @return the updated user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User updateDeliverlyDevice(Device device) throws TwitterException { return new User(http.post(baseURL + "account/update_delivery_device", new PostParameter[]{new PostParameter("device", device.DEVICE)}, true). asDocument().getDocumentElement(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites() throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites.xml", new PostParameter[0], true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param page the number of page * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(int page) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites.xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(String id) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites/" + id + ".xml", new PostParameter[0], true). asDocument(), this); } /** * Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format. * * @param id the ID or screen name of the user for whom to request a list of favorite statuses * @param page the number of page * @return List<Status> * @throws TwitterException when Twitter service or network is unavailable */ public synchronized List<Status> favorites(String id, int page) throws TwitterException { return Status.constructStatuses(get(baseURL + "favorites/" + id + ".xml", "page", String.valueOf(page), true). asDocument(), this); } /** * Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful. * * @param id the ID of the status to favorite * @return Status * @throws TwitterException when Twitter service or network is unavailable */ public synchronized Status createFavorite(long id) throws TwitterException { return new Status(http.post(baseURL + "favorites/create/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful. * * @param id the ID of the status to un-favorite * @return Status * @throws TwitterException when Twitter service or network is unavailable */ public synchronized Status destroyFavorite(long id) throws TwitterException { return new Status(http.post(baseURL + "favorites/destroy/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * * @param id String * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User follow(String id) throws TwitterException { return new User(http.post(baseURL + "notifications/follow/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful. * * @param id String * @return User * @throws TwitterException when Twitter service or network is unavailable */ public synchronized User leave(String id) throws TwitterException { return new User(http.post(baseURL + "notifications/leave/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /* Block Methods */ /** * Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful. * * @param id the ID or screen_name of the user to block * @return the blocked user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User block(String id) throws TwitterException { return new User(http.post(baseURL + "blocks/create/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /** * Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful. * * @param id the ID or screen_name of the user to block * @return the unblocked user * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized User unblock(String id) throws TwitterException { return new User(http.post(baseURL + "blocks/destroy/" + id + ".xml", true). asDocument().getDocumentElement(), this); } /* Help Methods */ /* test New as of April 29th, 2008! Returns the string "ok" in the requested format with a 200 OK HTTP status code. URL:http://twitter.com/help/test.format Formats: xml, json */ /** * Returns the string "ok" in the requested format with a 200 OK HTTP status code. * * @return true if the API is working * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized boolean test() throws TwitterException { return -1 != get(baseURL + "help/test.xml", false). asString().indexOf("ok"); } /** * Returns extended information of the authenticated user. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.<br> * The call Twitter.getAuthenticatedUser() is equivalent to the call:<br> * twitter.getUserDetail(twitter.getUserId()); * * @return UserWithStatus * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.1.3 */ public synchronized UserWithStatus getAuthenticatedUser() throws TwitterException { if(null == getUserId()){ throw new IllegalStateException("User Id not specified."); } return getUserDetail(getUserId()); } /* downtime_schedule New as of April 29th, 2008! Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format. URL:http://twitter.com/help/downtime_schedule.format Formats: xml, json */ /** * Returns the same text displayed on http://twitter.com/home when a maintenance window is scheduled, in the requested format. * * @return the schedule * @throws TwitterException when Twitter service or network is unavailable * @since twitter4j 1.0.4 */ public synchronized String getDowntimeSchedule() throws TwitterException { return get(baseURL + "help/downtime_schedule.xml", false).asString(); } private SimpleDateFormat format = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH); public void setRetryCount(int retryCount) { http.setRetryCount(retryCount); } public void setRetryIntervalSecs(int retryIntervalSecs) { http.setRetryIntervalSecs(retryIntervalSecs); } @Override public int hashCode() { return http.hashCode() + this.baseURL.hashCode() + http.hashCode(); } @Override public boolean equals(Object obj) { if (null == obj) { return false; } if (this == obj) { return true; } if (obj instanceof Twitter) { Twitter that = (Twitter) obj; return this.http.equals(that.http) && this.baseURL.equals(that.baseURL) && this.http.equals(that.http); } return false; } @Override public String toString() { return "Twitter{" + "http=" + http + ", baseURL='" + baseURL + '\'' + ", source='" + source + '\'' + ", usePostForcibly=" + usePostForcibly + ", format=" + format + '}'; } }
TFJ-48 support update_delivery_device method git-svn-id: 45a72d8ee61e5c3af5aa32c3525f4dded50a42aa@160 117b7e0d-5933-0410-9d29-ab41bb01d86b
src/main/java/twitter4j/Twitter.java
TFJ-48 support update_delivery_device method
Java
apache-2.0
bd37677dbbf34f2b562927bc286bade3e1230a44
0
apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,tmpgit/intellij-community,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,samthor/intellij-community,kdwink/intellij-community,caot/intellij-community,supersven/intellij-community,dslomov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,signed/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,izonder/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,joewalnes/idea-community,clumsy/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,consulo/consulo,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,consulo/consulo,consulo/consulo,dslomov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,da1z/intellij-community,petteyg/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,consulo/consulo,vvv1559/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,signed/intellij-community,ahb0327/intellij-community,semonte/intellij-community,apixandru/intellij-community,slisson/intellij-community,xfournet/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,slisson/intellij-community,robovm/robovm-studio,samthor/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,signed/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,holmes/intellij-community,da1z/intellij-community,jagguli/intellij-community,kdwink/intellij-community,izonder/intellij-community,dslomov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,blademainer/intellij-community,hurricup/intellij-community,amith01994/intellij-community,allotria/intellij-community,holmes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,asedunov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,amith01994/intellij-community,slisson/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,jagguli/intellij-community,diorcety/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,holmes/intellij-community,adedayo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,semonte/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ryano144/intellij-community,supersven/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,izonder/intellij-community,fitermay/intellij-community,signed/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,blademainer/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ryano144/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,caot/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ernestp/consulo,diorcety/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,holmes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,kool79/intellij-community,robovm/robovm-studio,blademainer/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,izonder/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,allotria/intellij-community,jagguli/intellij-community,allotria/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,joewalnes/idea-community,supersven/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,caot/intellij-community,kdwink/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,joewalnes/idea-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,allotria/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,dslomov/intellij-community,consulo/consulo,vvv1559/intellij-community,orekyuu/intellij-community,da1z/intellij-community,slisson/intellij-community,fnouama/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ernestp/consulo,pwoodworth/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,allotria/intellij-community,signed/intellij-community,amith01994/intellij-community,robovm/robovm-studio,semonte/intellij-community,diorcety/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,clumsy/intellij-community,allotria/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,ernestp/consulo,fitermay/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,supersven/intellij-community,holmes/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,xfournet/intellij-community,kool79/intellij-community,youdonghai/intellij-community,holmes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ernestp/consulo,alphafoobar/intellij-community,xfournet/intellij-community,allotria/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,dslomov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,supersven/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,supersven/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,hurricup/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,signed/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,samthor/intellij-community,suncycheng/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,hurricup/intellij-community,blademainer/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,caot/intellij-community,samthor/intellij-community,xfournet/intellij-community,caot/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,samthor/intellij-community,slisson/intellij-community,consulo/consulo,signed/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,adedayo/intellij-community,ernestp/consulo,ahb0327/intellij-community,allotria/intellij-community,vladmm/intellij-community,fitermay/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fitermay/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,retomerz/intellij-community,slisson/intellij-community,FHannes/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,caot/intellij-community,orekyuu/intellij-community,ernestp/consulo,tmpgit/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,da1z/intellij-community,adedayo/intellij-community,dslomov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,kool79/intellij-community,youdonghai/intellij-community,slisson/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,ibinti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,fnouama/intellij-community,joewalnes/idea-community,clumsy/intellij-community,youdonghai/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,hurricup/intellij-community,izonder/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,retomerz/intellij-community,supersven/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,blademainer/intellij-community,slisson/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,kool79/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,caot/intellij-community,caot/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,wreckJ/intellij-community,da1z/intellij-community,robovm/robovm-studio,kool79/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,tmpgit/intellij-community,izonder/intellij-community,fitermay/intellij-community,semonte/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,signed/intellij-community,fitermay/intellij-community,da1z/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,adedayo/intellij-community,da1z/intellij-community,vladmm/intellij-community,caot/intellij-community,blademainer/intellij-community,semonte/intellij-community,ahb0327/intellij-community,kool79/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,petteyg/intellij-community,kool79/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,samthor/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,caot/intellij-community,vladmm/intellij-community,ibinti/intellij-community,apixandru/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.ui; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerInvocationUtil; import com.intellij.debugger.actions.DebuggerActions; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.DebuggerManagerThreadImpl; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.SuspendManagerUtil; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.engine.events.DebuggerContextCommandImpl; import com.intellij.debugger.engine.events.SuspendContextCommandImpl; import com.intellij.debugger.engine.jdi.StackFrameProxy; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.impl.DebuggerContextUtil; import com.intellij.debugger.impl.DebuggerSession; import com.intellij.debugger.impl.DebuggerStateManager; import com.intellij.debugger.jdi.StackFrameProxyImpl; import com.intellij.debugger.jdi.ThreadReferenceProxyImpl; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.debugger.ui.impl.DebuggerComboBoxRenderer; import com.intellij.debugger.ui.impl.FramesList; import com.intellij.debugger.ui.impl.UpdatableDebuggerView; import com.intellij.debugger.ui.impl.watch.MethodsTracker; import com.intellij.debugger.ui.impl.watch.StackFrameDescriptorImpl; import com.intellij.debugger.ui.impl.watch.ThreadDescriptorImpl; import com.intellij.debugger.ui.tree.render.DescriptorLabelListener; import com.intellij.ide.OccurenceNavigator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPopupMenu; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBoxWithWidePopup; import com.intellij.ui.PopupHandler; import com.intellij.ui.ScrollPaneFactory; import com.sun.jdi.ObjectCollectedException; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FramesPanel extends UpdatableDebuggerView { private final JComboBox myThreadsCombo; private final FramesList myFramesList; private final ThreadsListener myThreadsListener; private final FramesListener myFramesListener; private final DebuggerStateManager myStateManager; private boolean myShowLibraryFrames = DebuggerSettings.getInstance().SHOW_LIBRARY_STACKFRAMES; public FramesPanel(Project project, DebuggerStateManager stateManager) { super(project, stateManager); myStateManager = stateManager; setLayout(new BorderLayout()); myThreadsCombo = new ComboBoxWithWidePopup(); myThreadsCombo.setRenderer(new DebuggerComboBoxRenderer()); myThreadsListener = new ThreadsListener(); myThreadsCombo.addItemListener(myThreadsListener); myFramesList = new FramesList(project); myFramesListener = new FramesListener(); myFramesList.addListSelectionListener(myFramesListener); myFramesList.addMouseListener(new MouseAdapter() { public void mousePressed(final MouseEvent e) { int index = myFramesList.locationToIndex(e.getPoint()); if (index >= 0 && myFramesList.isSelectedIndex(index)) { processListValue(myFramesList.getModel().getElementAt(index)); } } }); registerThreadsPopupMenu(myFramesList); setBorder(null); add(myThreadsCombo, BorderLayout.NORTH); add(ScrollPaneFactory.createScrollPane(myFramesList), BorderLayout.CENTER); } public DebuggerStateManager getContextManager() { return myStateManager; } private class FramesListener implements ListSelectionListener { boolean myIsEnabled = true; public void setEnabled(boolean enabled) { myIsEnabled = enabled; } public void valueChanged(ListSelectionEvent e) { if (!myIsEnabled || e.getValueIsAdjusting()) { return; } final JList list = (JList)e.getSource(); processListValue(list.getSelectedValue()); } } private void processListValue(final Object selected) { if (selected instanceof StackFrameDescriptorImpl) { DebuggerContextUtil.setStackFrame(getContextManager(), ((StackFrameDescriptorImpl)selected).getFrameProxy()); } } private void registerThreadsPopupMenu(final JList framesList) { final PopupHandler popupHandler = new PopupHandler() { public void invokePopup(Component comp, int x, int y) { DefaultActionGroup group = (DefaultActionGroup)ActionManager.getInstance().getAction(DebuggerActions.THREADS_PANEL_POPUP); ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(DebuggerActions.THREADS_PANEL_POPUP, group); popupMenu.getComponent().show(comp, x, y); } }; framesList.addMouseListener(popupHandler); registerDisposable(new Disposable() { public void dispose() { myThreadsCombo.removeItemListener(myThreadsListener); framesList.removeMouseListener(popupHandler); } }); } private class ThreadsListener implements ItemListener { boolean myIsEnabled = true; public void setEnabled(boolean enabled) { myIsEnabled = enabled; } public void itemStateChanged(ItemEvent e) { if (!myIsEnabled) return; if (e.getStateChange() == ItemEvent.SELECTED) { ThreadDescriptorImpl item = (ThreadDescriptorImpl)e.getItem(); DebuggerContextUtil.setThread(getContextManager(), item); } } } /*invoked in swing thread*/ protected void rebuild(int event) { final DebuggerContextImpl context = getContext(); final boolean paused = context.getDebuggerSession().isPaused(); final boolean isRefresh = event == DebuggerSession.EVENT_REFRESH || event == DebuggerSession.EVENT_REFRESH_VIEWS_ONLY || event == DebuggerSession.EVENT_THREADS_REFRESH; if (!paused || !isRefresh) { myThreadsCombo.removeAllItems(); synchronized (myFramesList) { myFramesList.clear(); } } if (paused) { final DebugProcessImpl process = context.getDebugProcess(); if (process != null) { process.getManagerThread().schedule(new RefreshFramePanelCommand(isRefresh && myThreadsCombo.getItemCount() != 0)); } } } public boolean isShowLibraryFrames() { return myShowLibraryFrames; } public void setShowLibraryFrames(boolean showLibraryFrames) { if (myShowLibraryFrames != showLibraryFrames) { myShowLibraryFrames = showLibraryFrames; rebuild(DebuggerSession.EVENT_CONTEXT); } } public long getFramesLastUpdateTime() { return myFramesLastUpdateTime; } public void setFramesLastUpdateTime(long framesLastUpdateTime) { myFramesLastUpdateTime = framesLastUpdateTime; } private class RefreshFramePanelCommand extends DebuggerContextCommandImpl { private final boolean myRefreshOnly; private final ThreadDescriptorImpl[] myThreadDescriptorsToUpdate; public RefreshFramePanelCommand(final boolean refreshOnly) { super(getContext()); myRefreshOnly = refreshOnly; if (refreshOnly) { final int size = myThreadsCombo.getItemCount(); myThreadDescriptorsToUpdate = new ThreadDescriptorImpl[size]; for (int idx = 0; idx < size; idx++) { myThreadDescriptorsToUpdate[idx] = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx); } } else { myThreadDescriptorsToUpdate = null; } } private List<ThreadDescriptorImpl> createThreadDescriptorsList() { final List<ThreadReferenceProxyImpl> threads = new ArrayList<ThreadReferenceProxyImpl>(getSuspendContext().getDebugProcess().getVirtualMachineProxy().allThreads()); Collections.sort(threads, ThreadReferenceProxyImpl.ourComparator); final List<ThreadDescriptorImpl> descriptors = new ArrayList<ThreadDescriptorImpl>(threads.size()); EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext(); for (ThreadReferenceProxyImpl thread : threads) { ThreadDescriptorImpl threadDescriptor = new ThreadDescriptorImpl(thread); threadDescriptor.setContext(evaluationContext); threadDescriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); descriptors.add(threadDescriptor); } return descriptors; } public void threadAction() { if (myRefreshOnly && myThreadDescriptorsToUpdate.length != myThreadsCombo.getItemCount()) { // there is no sense in refreshing combobox if thread list has changed since creation of this command return; } final DebuggerContextImpl context = getDebuggerContext(); final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy(); if(threadToSelect == null) { return; } final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), threadToSelect); final ThreadDescriptorImpl currentThreadDescriptor = (ThreadDescriptorImpl)myThreadsCombo.getSelectedItem(); final ThreadReferenceProxyImpl currentThread = currentThreadDescriptor != null? currentThreadDescriptor.getThreadReference() : null; if (myRefreshOnly && threadToSelect.equals(currentThread)) { context.getDebugProcess().getManagerThread().schedule(new UpdateFramesListCommand(context, threadContext)); } else { context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext)); } if (myRefreshOnly) { final EvaluationContextImpl evaluationContext = context.createEvaluationContext(); for (ThreadDescriptorImpl descriptor : myThreadDescriptorsToUpdate) { descriptor.setContext(evaluationContext); descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); } DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myThreadsListener.setEnabled(false); selectThread(threadToSelect); myFramesList.repaint(); } finally { myThreadsListener.setEnabled(true); } } }); } else { // full rebuild refillThreadsCombo(threadToSelect); } } protected void commandCancelled() { if (!DebuggerManagerThreadImpl.isManagerThread()) { return; } // context thread is not suspended final DebuggerContextImpl context = getDebuggerContext(); final SuspendContextImpl suspendContext = context.getSuspendContext(); if (suspendContext == null) { return; } final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy(); if(threadToSelect == null) { return; } if (!suspendContext.isResumed()) { final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(suspendContext, threadToSelect); context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext)); refillThreadsCombo(threadToSelect); } } private void refillThreadsCombo(final ThreadReferenceProxyImpl threadToSelect) { final List<ThreadDescriptorImpl> threadItems = createThreadDescriptorsList(); DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myThreadsListener.setEnabled(false); myThreadsCombo.removeAllItems(); for (final ThreadDescriptorImpl threadItem : threadItems) { myThreadsCombo.addItem(threadItem); } selectThread(threadToSelect); } finally { myThreadsListener.setEnabled(true); } } }); } } private class UpdateFramesListCommand extends SuspendContextCommandImpl { private final DebuggerContextImpl myDebuggerContext; public UpdateFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) { super(suspendContext); myDebuggerContext = debuggerContext; } public void contextAction() throws Exception { updateFrameList(myDebuggerContext.getThreadProxy()); DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myFramesListener.setEnabled(false); final StackFrameProxyImpl contextFrame = getDebuggerContext().getFrameProxy(); if(contextFrame != null) { selectFrame(contextFrame); } } finally { myFramesListener.setEnabled(true); } } }); } private void updateFrameList(ThreadReferenceProxyImpl thread) { try { if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) { return; } } catch (ObjectCollectedException e) { return; } final EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext(); final List<StackFrameDescriptorImpl> descriptors = new ArrayList<StackFrameDescriptorImpl>(); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); final int size = model.getSize(); for (int i = 0; i < size; i++) { final Object elem = model.getElementAt(i); if (elem instanceof StackFrameDescriptorImpl) { descriptors.add((StackFrameDescriptorImpl)elem); } } } for (StackFrameDescriptorImpl descriptor : descriptors) { descriptor.setContext(evaluationContext); descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); } } public DebuggerContextImpl getDebuggerContext() { return myDebuggerContext; } } private class RebuildFramesListCommand extends SuspendContextCommandImpl { private final DebuggerContextImpl myDebuggerContext; public RebuildFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) { super(suspendContext); myDebuggerContext = debuggerContext; } public void contextAction() throws Exception { final ThreadReferenceProxyImpl thread = myDebuggerContext.getThreadProxy(); try { if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) { DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myFramesListener.setEnabled(false); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); model.clear(); model.addElement(new Object() { public String toString() { return DebuggerBundle.message("frame.panel.frames.not.available"); } }); myFramesList.setSelectedIndex(0); } } finally { myFramesListener.setEnabled(true); } } }); return; } } catch (ObjectCollectedException e) { return; } List<StackFrameProxyImpl> frames; try { frames = thread.frames(); } catch (EvaluateException e) { frames = Collections.emptyList(); } final StackFrameProxyImpl contextFrame = myDebuggerContext.getFrameProxy(); final EvaluationContextImpl evaluationContext = myDebuggerContext.createEvaluationContext(); final DebuggerManagerThreadImpl managerThread = myDebuggerContext.getDebugProcess().getManagerThread(); final MethodsTracker tracker = new MethodsTracker(); final int totalFramesCount = frames.size(); int index = 0; final IndexCounter indexCounter = new IndexCounter(totalFramesCount); final long timestamp = Math.abs(System.nanoTime()); for (StackFrameProxyImpl stackFrameProxy : frames) { managerThread.schedule( new AppendFrameCommand( getSuspendContext(), stackFrameProxy, evaluationContext, tracker, index++, stackFrameProxy.equals(contextFrame), timestamp, indexCounter ) ); } } } private void selectThread(ThreadReferenceProxyImpl toSelect) { int count = myThreadsCombo.getItemCount(); for (int idx = 0; idx < count; idx++) { ThreadDescriptorImpl item = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx); if (toSelect.equals(item.getThreadReference())) { if (!item.equals(myThreadsCombo.getSelectedItem())) { myThreadsCombo.setSelectedIndex(idx); } return; } } } /*invoked in swing thread*/ private void selectFrame(StackFrameProxy frame) { synchronized (myFramesList) { final int count = myFramesList.getElementCount(); final Object selectedValue = myFramesList.getSelectedValue(); final DefaultListModel model = myFramesList.getModel(); for (int idx = 0; idx < count; idx++) { final Object elem = model.getElementAt(idx); if (elem instanceof StackFrameDescriptorImpl) { final StackFrameDescriptorImpl item = (StackFrameDescriptorImpl)elem; if (frame.equals(item.getFrameProxy())) { if (!item.equals(selectedValue)) { myFramesList.setSelectedIndex(idx); } return; } } } } } private static class IndexCounter { private final int[] myData; private IndexCounter(int totalSize) { myData = new int[totalSize]; for (int idx = 0; idx < totalSize; idx++) { myData[idx] = 0; } } public void markCalculated(int idx){ myData[idx] = 1; } public int getActualIndex(final int index) { int result = 0; for (int idx = 0; idx < index; idx++) { result += myData[idx]; } return result; } } private volatile long myFramesLastUpdateTime = 0L; private class AppendFrameCommand extends SuspendContextCommandImpl { private final StackFrameProxyImpl myFrame; private final EvaluationContextImpl myEvaluationContext; private final MethodsTracker myTracker; private final int myIndexToInsert; private final boolean myIsContextFrame; private final long myTimestamp; private final IndexCounter myCounter; public AppendFrameCommand(SuspendContextImpl suspendContext, StackFrameProxyImpl frame, EvaluationContextImpl evaluationContext, MethodsTracker tracker, int indexToInsert, final boolean isContextFrame, final long timestamp, IndexCounter counter) { super(suspendContext); myFrame = frame; myEvaluationContext = evaluationContext; myTracker = tracker; myIndexToInsert = indexToInsert; myIsContextFrame = isContextFrame; myTimestamp = timestamp; myCounter = counter; } public void contextAction() throws Exception { final StackFrameDescriptorImpl descriptor = new StackFrameDescriptorImpl(myFrame, myTracker); descriptor.setContext(myEvaluationContext); descriptor.updateRepresentation(myEvaluationContext, DescriptorLabelListener.DUMMY_LISTENER); final Project project = getProject(); DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { public void run() { try { myFramesListener.setEnabled(false); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); if (model.isEmpty() || myFramesLastUpdateTime < myTimestamp) { myFramesLastUpdateTime = myTimestamp; model.clear(); } if (myTimestamp != myFramesLastUpdateTime) { return; // the command has expired } final boolean shouldHide = !myShowLibraryFrames && !myIsContextFrame && myIndexToInsert != 0 && (descriptor.isSynthetic() || descriptor.isInLibraryContent()); if (!shouldHide) { myCounter.markCalculated(myIndexToInsert); final int actualIndex = myCounter.getActualIndex(myIndexToInsert); model.insertElementAt(descriptor, actualIndex); if (myIsContextFrame) { myFramesList.setSelectedIndex(actualIndex); } } } } finally { myFramesListener.setEnabled(true); } } }); } } public void requestFocus() { myThreadsCombo.requestFocus(); } public OccurenceNavigator getOccurenceNavigator() { return myFramesList; } public FramesList getFramesList() { return myFramesList; } }
java/debugger/impl/src/com/intellij/debugger/ui/FramesPanel.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.ui; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerInvocationUtil; import com.intellij.debugger.actions.DebuggerActions; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.DebuggerManagerThreadImpl; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.SuspendManagerUtil; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.engine.events.DebuggerContextCommandImpl; import com.intellij.debugger.engine.events.SuspendContextCommandImpl; import com.intellij.debugger.engine.jdi.StackFrameProxy; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.impl.DebuggerContextUtil; import com.intellij.debugger.impl.DebuggerSession; import com.intellij.debugger.impl.DebuggerStateManager; import com.intellij.debugger.jdi.StackFrameProxyImpl; import com.intellij.debugger.jdi.ThreadReferenceProxyImpl; import com.intellij.debugger.settings.DebuggerSettings; import com.intellij.debugger.ui.impl.DebuggerComboBoxRenderer; import com.intellij.debugger.ui.impl.FramesList; import com.intellij.debugger.ui.impl.UpdatableDebuggerView; import com.intellij.debugger.ui.impl.watch.MethodsTracker; import com.intellij.debugger.ui.impl.watch.StackFrameDescriptorImpl; import com.intellij.debugger.ui.impl.watch.ThreadDescriptorImpl; import com.intellij.debugger.ui.tree.render.DescriptorLabelListener; import com.intellij.ide.OccurenceNavigator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPopupMenu; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBoxWithWidePopup; import com.intellij.ui.PopupHandler; import com.intellij.ui.ScrollPaneFactory; import com.sun.jdi.ObjectCollectedException; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FramesPanel extends UpdatableDebuggerView { private final JComboBox myThreadsCombo; private final FramesList myFramesList; private final ThreadsListener myThreadsListener; private final FramesListener myFramesListener; private final DebuggerStateManager myStateManager; private boolean myShowLibraryFrames = DebuggerSettings.getInstance().SHOW_LIBRARY_STACKFRAMES; public FramesPanel(Project project, DebuggerStateManager stateManager) { super(project, stateManager); myStateManager = stateManager; setLayout(new BorderLayout()); myThreadsCombo = new ComboBoxWithWidePopup(); myThreadsCombo.setRenderer(new DebuggerComboBoxRenderer()); myThreadsListener = new ThreadsListener(); myThreadsCombo.addItemListener(myThreadsListener); myFramesList = new FramesList(project); myFramesListener = new FramesListener(); myFramesList.addListSelectionListener(myFramesListener); myFramesList.addMouseListener(new MouseAdapter() { public void mousePressed(final MouseEvent e) { int index = myFramesList.locationToIndex(e.getPoint()); if (index >= 0 && myFramesList.isSelectedIndex(index)) { processListValue(myFramesList.getModel().getElementAt(index)); } } }); registerThreadsPopupMenu(myFramesList); setBorder(null); add(myThreadsCombo, BorderLayout.NORTH); add(ScrollPaneFactory.createScrollPane(myFramesList), BorderLayout.CENTER); } public DebuggerStateManager getContextManager() { return myStateManager; } private class FramesListener implements ListSelectionListener { boolean myIsEnabled = true; public void setEnabled(boolean enabled) { myIsEnabled = enabled; } public void valueChanged(ListSelectionEvent e) { if (!myIsEnabled || e.getValueIsAdjusting()) { return; } final JList list = (JList)e.getSource(); processListValue(list.getSelectedValue()); } } private void processListValue(final Object selected) { if (selected instanceof StackFrameDescriptorImpl) { DebuggerContextUtil.setStackFrame(getContextManager(), ((StackFrameDescriptorImpl)selected).getFrameProxy()); } } private void registerThreadsPopupMenu(final JList framesList) { final PopupHandler popupHandler = new PopupHandler() { public void invokePopup(Component comp, int x, int y) { DefaultActionGroup group = (DefaultActionGroup)ActionManager.getInstance().getAction(DebuggerActions.THREADS_PANEL_POPUP); ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(DebuggerActions.THREADS_PANEL_POPUP, group); popupMenu.getComponent().show(comp, x, y); } }; framesList.addMouseListener(popupHandler); registerDisposable(new Disposable() { public void dispose() { myThreadsCombo.removeItemListener(myThreadsListener); framesList.removeMouseListener(popupHandler); } }); } private class ThreadsListener implements ItemListener { boolean myIsEnabled = true; public void setEnabled(boolean enabled) { myIsEnabled = enabled; } public void itemStateChanged(ItemEvent e) { if (!myIsEnabled) return; if (e.getStateChange() == ItemEvent.SELECTED) { ThreadDescriptorImpl item = (ThreadDescriptorImpl)e.getItem(); DebuggerContextUtil.setThread(getContextManager(), item); } } } /*invoked in swing thread*/ protected void rebuild(int event) { final DebuggerContextImpl context = getContext(); final boolean paused = context.getDebuggerSession().isPaused(); final boolean isRefresh = event == DebuggerSession.EVENT_REFRESH || event == DebuggerSession.EVENT_REFRESH_VIEWS_ONLY || event == DebuggerSession.EVENT_THREADS_REFRESH; if (!paused || !isRefresh) { myThreadsCombo.removeAllItems(); synchronized (myFramesList) { myFramesList.clear(); } } if (paused) { final DebugProcessImpl process = context.getDebugProcess(); if (process != null) { process.getManagerThread().schedule(new RefreshFramePanelCommand(isRefresh && myThreadsCombo.getItemCount() != 0)); } } } public boolean isShowLibraryFrames() { return myShowLibraryFrames; } public void setShowLibraryFrames(boolean showLibraryFrames) { if (myShowLibraryFrames != showLibraryFrames) { myShowLibraryFrames = showLibraryFrames; rebuild(DebuggerSession.EVENT_CONTEXT); } } public long getFramesLastUpdateTime() { return myFramesLastUpdateTime; } public void setFramesLastUpdateTime(long framesLastUpdateTime) { myFramesLastUpdateTime = framesLastUpdateTime; } private class RefreshFramePanelCommand extends DebuggerContextCommandImpl { private final boolean myRefreshOnly; private final ThreadDescriptorImpl[] myThreadDescriptorsToUpdate; public RefreshFramePanelCommand(final boolean refreshOnly) { super(getContext()); myRefreshOnly = refreshOnly; if (refreshOnly) { final int size = myThreadsCombo.getItemCount(); myThreadDescriptorsToUpdate = new ThreadDescriptorImpl[size]; for (int idx = 0; idx < size; idx++) { myThreadDescriptorsToUpdate[idx] = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx); } } else { myThreadDescriptorsToUpdate = null; } } private List<ThreadDescriptorImpl> createThreadDescriptorsList() { final List<ThreadReferenceProxyImpl> threads = new ArrayList<ThreadReferenceProxyImpl>(getSuspendContext().getDebugProcess().getVirtualMachineProxy().allThreads()); Collections.sort(threads, ThreadReferenceProxyImpl.ourComparator); final List<ThreadDescriptorImpl> descriptors = new ArrayList<ThreadDescriptorImpl>(threads.size()); EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext(); for (ThreadReferenceProxyImpl thread : threads) { ThreadDescriptorImpl threadDescriptor = new ThreadDescriptorImpl(thread); threadDescriptor.setContext(evaluationContext); threadDescriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); descriptors.add(threadDescriptor); } return descriptors; } public void threadAction() { if (myRefreshOnly && myThreadDescriptorsToUpdate.length != myThreadsCombo.getItemCount()) { // there is no sense in refreshing combobox if thread list has changed since creation of this command return; } final DebuggerContextImpl context = getDebuggerContext(); final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy(); if(threadToSelect == null) { return; } final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(context.getSuspendContext(), threadToSelect); final ThreadDescriptorImpl currentThreadDescriptor = (ThreadDescriptorImpl)myThreadsCombo.getSelectedItem(); final ThreadReferenceProxyImpl currentThread = currentThreadDescriptor != null? currentThreadDescriptor.getThreadReference() : null; if (myRefreshOnly && threadToSelect.equals(currentThread)) { context.getDebugProcess().getManagerThread().schedule(new UpdateFramesListCommand(context, threadContext)); } else { context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext)); } if (myRefreshOnly) { final EvaluationContextImpl evaluationContext = context.createEvaluationContext(); for (ThreadDescriptorImpl descriptor : myThreadDescriptorsToUpdate) { descriptor.setContext(evaluationContext); descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); } DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myThreadsListener.setEnabled(false); selectThread(threadToSelect); myFramesList.repaint(); } finally { myThreadsListener.setEnabled(true); } } }); } else { // full rebuild refillThreadsCombo(threadToSelect); } } protected void commandCancelled() { if (!DebuggerManagerThreadImpl.isManagerThread()) { return; } // context thread is not suspended final DebuggerContextImpl context = getDebuggerContext(); final SuspendContextImpl suspendContext = context.getSuspendContext(); if (suspendContext == null) { return; } final ThreadReferenceProxyImpl threadToSelect = context.getThreadProxy(); if(threadToSelect == null) { return; } if (!suspendContext.isResumed()) { final SuspendContextImpl threadContext = SuspendManagerUtil.getSuspendContextForThread(suspendContext, threadToSelect); context.getDebugProcess().getManagerThread().schedule(new RebuildFramesListCommand(context, threadContext)); refillThreadsCombo(threadToSelect); } } private void refillThreadsCombo(final ThreadReferenceProxyImpl threadToSelect) { final List<ThreadDescriptorImpl> threadItems = createThreadDescriptorsList(); DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myThreadsListener.setEnabled(false); myThreadsCombo.removeAllItems(); for (final ThreadDescriptorImpl threadItem : threadItems) { myThreadsCombo.addItem(threadItem); } selectThread(threadToSelect); } finally { myThreadsListener.setEnabled(true); } } }); } } private class UpdateFramesListCommand extends SuspendContextCommandImpl { private final DebuggerContextImpl myDebuggerContext; public UpdateFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) { super(suspendContext); myDebuggerContext = debuggerContext; } public void contextAction() throws Exception { updateFrameList(myDebuggerContext.getThreadProxy()); DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myFramesListener.setEnabled(false); final StackFrameProxyImpl contextFrame = getDebuggerContext().getFrameProxy(); if(contextFrame != null) { selectFrame(contextFrame); } } finally { myFramesListener.setEnabled(true); } } }); } private void updateFrameList(ThreadReferenceProxyImpl thread) { try { if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) { return; } } catch (ObjectCollectedException e) { return; } final EvaluationContextImpl evaluationContext = getDebuggerContext().createEvaluationContext(); final List<StackFrameDescriptorImpl> descriptors = new ArrayList<StackFrameDescriptorImpl>(); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); final int size = model.getSize(); for (int i = 0; i < size; i++) { final Object elem = model.getElementAt(i); if (elem instanceof StackFrameDescriptorImpl) { descriptors.add((StackFrameDescriptorImpl)elem); } } } for (StackFrameDescriptorImpl descriptor : descriptors) { descriptor.setContext(evaluationContext); descriptor.updateRepresentation(evaluationContext, DescriptorLabelListener.DUMMY_LISTENER); } } public DebuggerContextImpl getDebuggerContext() { return myDebuggerContext; } } private class RebuildFramesListCommand extends SuspendContextCommandImpl { private final DebuggerContextImpl myDebuggerContext; public RebuildFramesListCommand(DebuggerContextImpl debuggerContext, SuspendContextImpl suspendContext) { super(suspendContext); myDebuggerContext = debuggerContext; } public void contextAction() throws Exception { final ThreadReferenceProxyImpl thread = myDebuggerContext.getThreadProxy(); try { if(!getSuspendContext().getDebugProcess().getSuspendManager().isSuspended(thread)) { DebuggerInvocationUtil.swingInvokeLater(getProject(), new Runnable() { public void run() { try { myFramesListener.setEnabled(false); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); model.clear(); model.addElement(new Object() { public String toString() { return DebuggerBundle.message("frame.panel.frames.not.available"); } }); myFramesList.setSelectedIndex(0); } } finally { myFramesListener.setEnabled(true); } } }); return; } } catch (ObjectCollectedException e) { return; } List<StackFrameProxyImpl> frames; try { frames = thread.frames(); } catch (EvaluateException e) { frames = Collections.emptyList(); } final StackFrameProxyImpl contextFrame = myDebuggerContext.getFrameProxy(); final EvaluationContextImpl evaluationContext = myDebuggerContext.createEvaluationContext(); final DebuggerManagerThreadImpl managerThread = myDebuggerContext.getDebugProcess().getManagerThread(); final MethodsTracker tracker = new MethodsTracker(); final int totalFramesCount = frames.size(); int index = 0; final IndexCounter indexCounter = new IndexCounter(totalFramesCount); final long timestamp = Math.abs(System.nanoTime()); for (StackFrameProxyImpl stackFrameProxy : frames) { managerThread.schedule( new AppendFrameCommand( getSuspendContext(), stackFrameProxy, evaluationContext, tracker, index++, stackFrameProxy.equals(contextFrame), totalFramesCount, timestamp, indexCounter ) ); } } } private void selectThread(ThreadReferenceProxyImpl toSelect) { int count = myThreadsCombo.getItemCount(); for (int idx = 0; idx < count; idx++) { ThreadDescriptorImpl item = (ThreadDescriptorImpl)myThreadsCombo.getItemAt(idx); if (toSelect.equals(item.getThreadReference())) { if (!item.equals(myThreadsCombo.getSelectedItem())) { myThreadsCombo.setSelectedIndex(idx); } return; } } } /*invoked in swing thread*/ private void selectFrame(StackFrameProxy frame) { synchronized (myFramesList) { final int count = myFramesList.getElementCount(); final Object selectedValue = myFramesList.getSelectedValue(); final DefaultListModel model = myFramesList.getModel(); for (int idx = 0; idx < count; idx++) { final Object elem = model.getElementAt(idx); if (elem instanceof StackFrameDescriptorImpl) { final StackFrameDescriptorImpl item = (StackFrameDescriptorImpl)elem; if (frame.equals(item.getFrameProxy())) { if (!item.equals(selectedValue)) { myFramesList.setSelectedIndex(idx); } return; } } } } } private static class IndexCounter { private final int[] myData; private IndexCounter(int totalSize) { myData = new int[totalSize]; for (int idx = 0; idx < totalSize; idx++) { myData[idx] = 1; } } public void markHidden(int idx){ myData[idx] = 0; } public int getActualIndex(final int index) { int result = 0; for (int idx = 0; idx < index; idx++) { result += myData[idx]; } return result; } } private volatile long myFramesLastUpdateTime = 0L; private class AppendFrameCommand extends SuspendContextCommandImpl { private final StackFrameProxyImpl myFrame; private final EvaluationContextImpl myEvaluationContext; private final MethodsTracker myTracker; private final int myIndexToInsert; private final boolean myIsContextFrame; private final int myTotalFramesCount; private final long myTimestamp; private final IndexCounter myCounter; public AppendFrameCommand(SuspendContextImpl suspendContext, StackFrameProxyImpl frame, EvaluationContextImpl evaluationContext, MethodsTracker tracker, int indexToInsert, final boolean isContextFrame, final int totalFramesCount, final long timestamp, IndexCounter counter) { super(suspendContext); myFrame = frame; myEvaluationContext = evaluationContext; myTracker = tracker; myIndexToInsert = indexToInsert; myIsContextFrame = isContextFrame; myTotalFramesCount = totalFramesCount; myTimestamp = timestamp; myCounter = counter; } public void contextAction() throws Exception { final StackFrameDescriptorImpl descriptor = new StackFrameDescriptorImpl(myFrame, myTracker); descriptor.setContext(myEvaluationContext); descriptor.updateRepresentation(myEvaluationContext, DescriptorLabelListener.DUMMY_LISTENER); final Project project = getProject(); DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { public void run() { try { myFramesListener.setEnabled(false); synchronized (myFramesList) { final DefaultListModel model = myFramesList.getModel(); if (model.isEmpty() || myFramesLastUpdateTime < myTimestamp) { myFramesLastUpdateTime = myTimestamp; model.clear(); for (int idx = 0; idx < myTotalFramesCount; idx++) { final String label = "<frame " + idx + ">"; model.addElement(new Object() { public String toString() { return label; } }); } } if (myTimestamp != myFramesLastUpdateTime) { return; // the command has expired } final int actualIndex = myCounter.getActualIndex(myIndexToInsert); model.removeElementAt(actualIndex); // remove placeholder boolean shouldHide = !myShowLibraryFrames && !myIsContextFrame && myIndexToInsert != 0 && (descriptor.isSynthetic() || descriptor.isInLibraryContent()); if (shouldHide) { myCounter.markHidden(myIndexToInsert); } else { model.insertElementAt(descriptor, actualIndex); if (myIsContextFrame) { myFramesList.setSelectedIndex(actualIndex); } } } } finally { myFramesListener.setEnabled(true); } } }); } } public void requestFocus() { myThreadsCombo.requestFocus(); } public OccurenceNavigator getOccurenceNavigator() { return myFramesList; } public FramesList getFramesList() { return myFramesList; } }
rollback incorrect change
java/debugger/impl/src/com/intellij/debugger/ui/FramesPanel.java
rollback incorrect change
Java
apache-2.0
04f87b84b87bcfd3d2652179318b579c2d528333
0
ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,JayanthyChengan/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean; import edu.harvard.iq.dataverse.authorization.DataverseRole; import edu.harvard.iq.dataverse.authorization.DataverseRolePermissionHelper; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.RoleAssignee; import edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo; import edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean; import edu.harvard.iq.dataverse.authorization.groups.impl.builtin.AuthenticatedUsers; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroup; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.exception.PermissionException; import edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.RevokeRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseDefaultContributorRoleCommand; import edu.harvard.iq.dataverse.util.JsfHelper; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import edu.harvard.iq.dataverse.util.StringUtil; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.commons.lang.StringEscapeUtils; /** * * @author gdurand */ @ViewScoped @Named public class ManagePermissionsPage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(ManagePermissionsPage.class.getCanonicalName()); @EJB DvObjectServiceBean dvObjectService; @EJB DataverseRoleServiceBean roleService; @EJB RoleAssigneeServiceBean roleAssigneeService; @EJB PermissionServiceBean permissionService; @EJB AuthenticationServiceBean authenticationService; @EJB ExplicitGroupServiceBean explicitGroupService; @EJB GroupServiceBean groupService; @EJB EjbDataverseEngine commandEngine; @EJB UserNotificationServiceBean userNotificationService; @Inject DataverseRequestServiceBean dvRequestService; @Inject PermissionsWrapper permissionsWrapper; @PersistenceContext(unitName = "VDCNet-ejbPU") EntityManager em; @Inject DataverseSession session; private DataverseRolePermissionHelper dataverseRolePermissionHelper; private List<DataverseRole> roleList; DvObject dvObject = new Dataverse(); // by default we use a Dataverse, but this will be overridden in init by the findById public DvObject getDvObject() { return dvObject; } public void setDvObject(DvObject dvObject) { this.dvObject = dvObject; /* SEK 09/15/2016 - may need to do something here if permissions are transmitted/inherited from dataverse to dataverse */ /*if (dvObject instanceof DvObjectContainer) { inheritAssignments = !((DvObjectContainer) dvObject).isPermissionRoot(); }*/ } public String init() { //@todo deal with any kind of dvObject if (dvObject.getId() != null) { dvObject = dvObjectService.findDvObject(dvObject.getId()); } // check if dvObject exists and user has permission if (dvObject == null) { return permissionsWrapper.notFound(); } // for dataFiles, check the perms on its owning dataset DvObject checkPermissionsdvObject = dvObject instanceof DataFile ? dvObject.getOwner() : dvObject; if (!permissionService.on(checkPermissionsdvObject).has(checkPermissionsdvObject instanceof Dataverse ? Permission.ManageDataversePermissions : Permission.ManageDatasetPermissions)) { return permissionsWrapper.notAuthorized(); } // initialize the configure settings if (dvObject instanceof Dataverse) { initAccessSettings(); } roleList = roleService.findAll(); roleAssignments = initRoleAssignments(); dataverseRolePermissionHelper = new DataverseRolePermissionHelper(roleList); return ""; } /* main page - role assignment table */ // used by remove Role Assignment private RoleAssignment selectedRoleAssignment; public RoleAssignment getSelectedRoleAssignment() { return selectedRoleAssignment; } public void setSelectedRoleAssignment(RoleAssignment selectedRoleAssignment) { this.selectedRoleAssignment = selectedRoleAssignment; } private List<RoleAssignmentRow> roleAssignments; public List<RoleAssignmentRow> getRoleAssignments() { return roleAssignments; } public void setRoleAssignments(List<RoleAssignmentRow> roleAssignments) { this.roleAssignments = roleAssignments; } public List<RoleAssignmentRow> initRoleAssignments() { List<RoleAssignmentRow> raList = null; if (dvObject != null && dvObject.getId() != null) { Set<RoleAssignment> ras = roleService.rolesAssignments(dvObject); raList = new ArrayList<>(ras.size()); for (RoleAssignment roleAssignment : ras) { // for files, only show role assignments which can download if (!(dvObject instanceof DataFile) || roleAssignment.getRole().permissions().contains(Permission.DownloadFile)) { RoleAssignee roleAssignee = roleAssigneeService.getRoleAssignee(roleAssignment.getAssigneeIdentifier()); if (roleAssignee != null) { raList.add(new RoleAssignmentRow(roleAssignment, roleAssignee.getDisplayInfo())); } else { logger.info("Could not find role assignee based on role assignment id " + roleAssignment.getId()); } } } } return raList; } public void removeRoleAssignment() { revokeRole(selectedRoleAssignment); if (dvObject instanceof Dataverse) { initAccessSettings(); // in case the revoke was for the AuthenticatedUsers group } roleAssignments = initRoleAssignments(); showAssignmentMessages(); } // internal method used by removeRoleAssignment and saveConfiguration private void revokeRole(RoleAssignment ra) { try { commandEngine.submit(new RevokeRoleCommand(ra, dvRequestService.getDataverseRequest())); JsfHelper.addSuccessMessage(ra.getRole().getName() + " role for " + roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()).getDisplayInfo().getTitle() + " was removed."); RoleAssignee assignee = roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()); notifyRoleChange(assignee, UserNotification.Type.REVOKEROLE); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role assignment was not able to be removed.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role assignment could not be removed."); logger.log(Level.SEVERE, "Error removing role assignment: " + ex.getMessage(), ex); } } /* main page - roles table */ public List<DataverseRole> getRoles() { if (dvObject != null && dvObject.getId() != null) { return roleService.findByOwnerId(dvObject.getId()); } return new ArrayList<>(); } public void createNewRole(ActionEvent e) { setRole(new DataverseRole()); role.setOwner(dvObject); } public void cloneRole(String roleId) { DataverseRole clonedRole = new DataverseRole(); clonedRole.setOwner(dvObject); DataverseRole originalRole = roleService.find(Long.parseLong(roleId)); clonedRole.addPermissions(originalRole.permissions()); setRole(clonedRole); } public void editRole(String roleId) { setRole(roleService.find(Long.parseLong(roleId))); } /* ============================================================================ edit configuration dialog // only for dataverse version of page ============================================================================ */ private String authenticatedUsersContributorRoleAlias = null; private String defaultContributorRoleAlias = DataverseRole.EDITOR; public String getAuthenticatedUsersContributorRoleAlias() { return authenticatedUsersContributorRoleAlias; } public void setAuthenticatedUsersContributorRoleAlias(String authenticatedUsersContributorRoleAlias) { this.authenticatedUsersContributorRoleAlias = authenticatedUsersContributorRoleAlias; } public String getDefaultContributorRoleAlias() { return defaultContributorRoleAlias; } public void setDefaultContributorRoleAlias(String defaultContributorRoleAlias) { this.defaultContributorRoleAlias = defaultContributorRoleAlias; } public void initAccessSettings() { if (dvObject instanceof Dataverse) { authenticatedUsersContributorRoleAlias = ""; List<RoleAssignment> aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject); for (RoleAssignment roleAssignment : aUsersRoleAssignments) { String roleAlias = roleAssignment.getRole().getAlias(); authenticatedUsersContributorRoleAlias = roleAlias; break; // @todo handle case where more than one role has been assigned to the AutenticatedUsers group! } defaultContributorRoleAlias = ((Dataverse) dvObject).getDefaultContributorRole().getAlias(); } } public void saveConfiguration(ActionEvent e) { // Set role (if any) for authenticatedUsers DataverseRole roleToAssign = null; List<String> contributorRoles = Arrays.asList(DataverseRole.FULL_CONTRIBUTOR, DataverseRole.DV_CONTRIBUTOR, DataverseRole.DS_CONTRIBUTOR); if (!StringUtil.isEmpty(authenticatedUsersContributorRoleAlias)) { roleToAssign = roleService.findBuiltinRoleByAlias(authenticatedUsersContributorRoleAlias); } // then, check current contributor role List<RoleAssignment> aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject); for (RoleAssignment roleAssignment : aUsersRoleAssignments) { DataverseRole currentRole = roleAssignment.getRole(); if (contributorRoles.contains(currentRole.getAlias())) { if (currentRole.equals(roleToAssign)) { roleToAssign = null; // found the role, so no need to assign } else { revokeRole(roleAssignment); } } } // finally, assign role, if new if (roleToAssign != null) { assignRole(AuthenticatedUsers.get(), roleToAssign); } // set dataverse default contributor role if (dvObject instanceof Dataverse) { Dataverse dv = (Dataverse) dvObject; DataverseRole defaultRole = roleService.findBuiltinRoleByAlias(defaultContributorRoleAlias); if (!defaultRole.equals(dv.getDefaultContributorRole())) { try { commandEngine.submit(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, dvRequestService.getDataverseRequest(), dv)); JsfHelper.addSuccessMessage("The default permissions for this dataverse have been updated."); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "Cannot assign default permissions.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "Cannot assign default permissions."); logger.log(Level.SEVERE, "Error assigning default permissions: " + ex.getMessage(), ex); } } } roleAssignments = initRoleAssignments(); showConfigureMessages(); } /* ============================================================================ assign roles dialog ============================================================================ */ private List<RoleAssignee> roleAssignSelectedRoleAssignees; private Long selectedRoleId; public List<RoleAssignee> getRoleAssignSelectedRoleAssignees() { return roleAssignSelectedRoleAssignees; } public void setRoleAssignSelectedRoleAssignees(List<RoleAssignee> selectedRoleAssignees) { this.roleAssignSelectedRoleAssignees = selectedRoleAssignees; } public Long getSelectedRoleId() { return selectedRoleId; } public void setSelectedRoleId(Long selectedRoleId) { this.selectedRoleId = selectedRoleId; } public void initAssigneeDialog(ActionEvent ae) { roleAssignSelectedRoleAssignees = new LinkedList<>(); selectedRoleId = null; showNoMessages(); } public List<RoleAssignee> completeRoleAssignee( String query ) { return roleAssigneeService.filterRoleAssignees(query, dvObject, roleAssignSelectedRoleAssignees); } public List<DataverseRole> getAvailableRoles() { List<DataverseRole> roles = new LinkedList<>(); if (dvObject != null && dvObject.getId() != null) { if (dvObject instanceof Dataverse) { roles.addAll(roleService.availableRoles(dvObject.getId())); } else if (dvObject instanceof Dataset) { // don't show roles that only have Dataverse level permissions // current the available roles for a dataset are gotten from its parent for (DataverseRole role : roleService.availableRoles(dvObject.getOwner().getId())) { for (Permission permission : role.permissions()) { if (permission.appliesTo(Dataset.class) || permission.appliesTo(DataFile.class)) { roles.add(role); break; } } } } else if (dvObject instanceof DataFile) { roles.add(roleService.findBuiltinRoleByAlias(DataverseRole.FILE_DOWNLOADER)); } Collections.sort(roles, DataverseRole.CMP_BY_NAME); } return roles; } public DataverseRole getAssignedRole() { if (selectedRoleId != null) { return roleService.find(selectedRoleId); } return null; } public String getAssignedRoleObjectTypes(){ String retString = ""; if (selectedRoleId != null) { /* SEK 09/15/2016 SEK commenting out for now because permissions are not inherited if (dataverseRolePermissionHelper.hasDataversePermissions(selectedRoleId) && dvObject instanceof Dataverse){ String dvLabel = ResourceBundle.getBundle("Bundle").getString("dataverses"); retString = dvLabel; } */ if (dataverseRolePermissionHelper.hasDatasetPermissions(selectedRoleId) && dvObject instanceof Dataverse){ String dsLabel = ResourceBundle.getBundle("Bundle").getString("datasets"); if(!retString.isEmpty()) { retString +=", " + dsLabel; } else { retString = dsLabel; } } if (dataverseRolePermissionHelper.hasFilePermissions(selectedRoleId)){ String filesLabel = ResourceBundle.getBundle("Bundle").getString("files"); if(!retString.isEmpty()) { retString +=", " + filesLabel; } else { retString = filesLabel; } } return retString; } return null; } public String getDefinitionLevelString(){ if (dvObject != null){ if (dvObject instanceof Dataverse) return ResourceBundle.getBundle("Bundle").getString("dataverse"); if (dvObject instanceof Dataset) return ResourceBundle.getBundle("Bundle").getString("dataset"); } return null; } public void assignRole(ActionEvent evt) { logger.info("Got to assignRole"); List<RoleAssignee> selectedRoleAssigneesList = getRoleAssignSelectedRoleAssignees(); if ( selectedRoleAssigneesList == null ) { logger.info("** SELECTED role asignees is null"); selectedRoleAssigneesList = new LinkedList<>(); } for (RoleAssignee roleAssignee : selectedRoleAssigneesList) { assignRole(roleAssignee, roleService.find(selectedRoleId)); } roleAssignments = initRoleAssignments(); } /** * Notify a {@code RoleAssignee} that a role was either assigned or revoked. * Will notify all members of a group. * @param ra The {@code RoleAssignee} to be notified. * @param type The type of notification. */ private void notifyRoleChange(RoleAssignee ra, UserNotification.Type type) { if (ra instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) ra, new Timestamp(new Date().getTime()), type, dvObject.getId()); } else if (ra instanceof ExplicitGroup) { ExplicitGroup eg = (ExplicitGroup) ra; Set<String> explicitGroupMembers = eg.getContainedRoleAssgineeIdentifiers(); for (String id : explicitGroupMembers) { RoleAssignee explicitGroupMember = roleAssigneeService.getRoleAssignee(id); if (explicitGroupMember instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) explicitGroupMember, new Timestamp(new Date().getTime()), type, dvObject.getId()); } } } } private void assignRole(RoleAssignee ra, DataverseRole r) { try { String privateUrlToken = null; commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken)); JsfHelper.addSuccessMessage(r.getName() + " role assigned to " + ra.getDisplayInfo().getTitle() + " for " + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + "."); // don't notify if role = file downloader and object is not released if (!(r.getAlias().equals(DataverseRole.FILE_DOWNLOADER) && !dvObject.isReleased()) ){ notifyRoleChange(ra, UserNotification.Type.ASSIGNROLE); } } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role was not able to be assigned.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role was not able to be assigned."); logger.log(Level.SEVERE, "Error assiging role: " + ex.getMessage(), ex); } showAssignmentMessages(); } /* ============================================================================ edit role dialog ============================================================================ */ private DataverseRole role = new DataverseRole(); private List<String> selectedPermissions; public DataverseRole getRole() { return role; } public void setRole(DataverseRole role) { this.role = role; selectedPermissions = new LinkedList<>(); if (role != null) { for (Permission p : role.permissions()) { selectedPermissions.add(p.name()); } } } public List<String> getSelectedPermissions() { return selectedPermissions; } public void setSelectedPermissions(List<String> selectedPermissions) { this.selectedPermissions = selectedPermissions; } public List<Permission> getPermissions() { return Arrays.asList(Permission.values()); } public void updateRole(ActionEvent e) { // @todo currently only works for Dataverse since CreateRoleCommand only takes a dataverse // we need to decide if we want roles at the dataset level or not if (dvObject instanceof Dataverse) { role.clearPermissions(); for (String pmsnStr : getSelectedPermissions()) { role.addPermission(Permission.valueOf(pmsnStr)); } try { String roleState = role.getId() != null ? "updated" : "created"; setRole(commandEngine.submit(new CreateRoleCommand(role, dvRequestService.getDataverseRequest(), (Dataverse) role.getOwner()))); JsfHelper.addSuccessMessage("The role was " + roleState + ". To assign it to a user and/or group, click on the Assign Roles to Users/Groups button in the Users/Groups section of this page."); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role was not able to be saved.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role was not able to be saved."); logger.log(Level.SEVERE, "Error saving role: " + ex.getMessage(), ex); } } showRoleMessages(); } public DataverseRolePermissionHelper getDataverseRolePermissionHelper() { return dataverseRolePermissionHelper; } public void setDataverseRolePermissionHelper(DataverseRolePermissionHelper dataverseRolePermissionHelper) { this.dataverseRolePermissionHelper = dataverseRolePermissionHelper; } /* ============================================================================ Internal methods ============================================================================ */ boolean renderConfigureMessages = false; boolean renderAssignmentMessages = false; boolean renderRoleMessages = false; private void showNoMessages() { renderConfigureMessages = false; renderAssignmentMessages = false; renderRoleMessages = false; } private void showConfigureMessages() { renderConfigureMessages = true; renderAssignmentMessages = false; renderRoleMessages = false; } private void showAssignmentMessages() { renderConfigureMessages = false; renderAssignmentMessages = true; renderRoleMessages = false; } private void showRoleMessages() { renderConfigureMessages = false; renderAssignmentMessages = false; renderRoleMessages = true; } public Boolean getRenderConfigureMessages() { return renderConfigureMessages; } public void setRenderConfigureMessages(Boolean renderConfigureMessages) { this.renderConfigureMessages = renderConfigureMessages; } public Boolean getRenderAssignmentMessages() { return renderAssignmentMessages; } public void setRenderAssignmentMessages(Boolean renderAssignmentMessages) { this.renderAssignmentMessages = renderAssignmentMessages; } public Boolean getRenderRoleMessages() { return renderRoleMessages; } public void setRenderRoleMessages(Boolean renderRoleMessages) { this.renderRoleMessages = renderRoleMessages; } // inner class used for display of role assignments public static class RoleAssignmentRow { private final RoleAssigneeDisplayInfo assigneeDisplayInfo; private final RoleAssignment ra; public RoleAssignmentRow(RoleAssignment anRa, RoleAssigneeDisplayInfo disInf) { ra = anRa; assigneeDisplayInfo = disInf; } public RoleAssignment getRoleAssignment() { return ra; } public RoleAssigneeDisplayInfo getAssigneeDisplayInfo() { return assigneeDisplayInfo; } public DataverseRole getRole() { return ra.getRole(); } public String getRoleName() { return getRole().getName(); } public DvObject getDefinitionPoint() { return ra.getDefinitionPoint(); } public String getAssignedDvName() { return ra.getDefinitionPoint().getDisplayName(); } public Long getId() { return ra.getId(); } } }
src/main/java/edu/harvard/iq/dataverse/ManagePermissionsPage.java
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean; import edu.harvard.iq.dataverse.authorization.DataverseRole; import edu.harvard.iq.dataverse.authorization.DataverseRolePermissionHelper; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.RoleAssignee; import edu.harvard.iq.dataverse.authorization.RoleAssigneeDisplayInfo; import edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean; import edu.harvard.iq.dataverse.authorization.groups.impl.builtin.AuthenticatedUsers; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroup; import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean; import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser; import edu.harvard.iq.dataverse.engine.command.exception.CommandException; import edu.harvard.iq.dataverse.engine.command.exception.PermissionException; import edu.harvard.iq.dataverse.engine.command.impl.AssignRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.CreateRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.RevokeRoleCommand; import edu.harvard.iq.dataverse.engine.command.impl.UpdateDataverseDefaultContributorRoleCommand; import edu.harvard.iq.dataverse.util.JsfHelper; import static edu.harvard.iq.dataverse.util.JsfHelper.JH; import edu.harvard.iq.dataverse.util.StringUtil; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.event.ActionEvent; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.commons.lang.StringEscapeUtils; /** * * @author gdurand */ @ViewScoped @Named public class ManagePermissionsPage implements java.io.Serializable { private static final Logger logger = Logger.getLogger(ManagePermissionsPage.class.getCanonicalName()); @EJB DvObjectServiceBean dvObjectService; @EJB DataverseRoleServiceBean roleService; @EJB RoleAssigneeServiceBean roleAssigneeService; @EJB PermissionServiceBean permissionService; @EJB AuthenticationServiceBean authenticationService; @EJB ExplicitGroupServiceBean explicitGroupService; @EJB GroupServiceBean groupService; @EJB EjbDataverseEngine commandEngine; @EJB UserNotificationServiceBean userNotificationService; @Inject DataverseRequestServiceBean dvRequestService; @Inject PermissionsWrapper permissionsWrapper; @PersistenceContext(unitName = "VDCNet-ejbPU") EntityManager em; @Inject DataverseSession session; private DataverseRolePermissionHelper dataverseRolePermissionHelper; private List<DataverseRole> roleList; DvObject dvObject = new Dataverse(); // by default we use a Dataverse, but this will be overridden in init by the findById public DvObject getDvObject() { return dvObject; } public void setDvObject(DvObject dvObject) { this.dvObject = dvObject; /*if (dvObject instanceof DvObjectContainer) { inheritAssignments = !((DvObjectContainer) dvObject).isPermissionRoot(); }*/ } public String init() { //@todo deal with any kind of dvObject if (dvObject.getId() != null) { dvObject = dvObjectService.findDvObject(dvObject.getId()); } // check if dvObject exists and user has permission if (dvObject == null) { return permissionsWrapper.notFound(); } // for dataFiles, check the perms on its owning dataset DvObject checkPermissionsdvObject = dvObject instanceof DataFile ? dvObject.getOwner() : dvObject; if (!permissionService.on(checkPermissionsdvObject).has(checkPermissionsdvObject instanceof Dataverse ? Permission.ManageDataversePermissions : Permission.ManageDatasetPermissions)) { return permissionsWrapper.notAuthorized(); } // initialize the configure settings if (dvObject instanceof Dataverse) { initAccessSettings(); } roleList = roleService.findAll(); roleAssignments = initRoleAssignments(); dataverseRolePermissionHelper = new DataverseRolePermissionHelper(roleList); return ""; } /* main page - role assignment table */ // used by remove Role Assignment private RoleAssignment selectedRoleAssignment; public RoleAssignment getSelectedRoleAssignment() { return selectedRoleAssignment; } public void setSelectedRoleAssignment(RoleAssignment selectedRoleAssignment) { this.selectedRoleAssignment = selectedRoleAssignment; } private List<RoleAssignmentRow> roleAssignments; public List<RoleAssignmentRow> getRoleAssignments() { return roleAssignments; } public void setRoleAssignments(List<RoleAssignmentRow> roleAssignments) { this.roleAssignments = roleAssignments; } public List<RoleAssignmentRow> initRoleAssignments() { List<RoleAssignmentRow> raList = null; if (dvObject != null && dvObject.getId() != null) { Set<RoleAssignment> ras = roleService.rolesAssignments(dvObject); raList = new ArrayList<>(ras.size()); for (RoleAssignment roleAssignment : ras) { // for files, only show role assignments which can download if (!(dvObject instanceof DataFile) || roleAssignment.getRole().permissions().contains(Permission.DownloadFile)) { RoleAssignee roleAssignee = roleAssigneeService.getRoleAssignee(roleAssignment.getAssigneeIdentifier()); if (roleAssignee != null) { raList.add(new RoleAssignmentRow(roleAssignment, roleAssignee.getDisplayInfo())); } else { logger.info("Could not find role assignee based on role assignment id " + roleAssignment.getId()); } } } } return raList; } public void removeRoleAssignment() { revokeRole(selectedRoleAssignment); if (dvObject instanceof Dataverse) { initAccessSettings(); // in case the revoke was for the AuthenticatedUsers group } roleAssignments = initRoleAssignments(); showAssignmentMessages(); } // internal method used by removeRoleAssignment and saveConfiguration private void revokeRole(RoleAssignment ra) { try { commandEngine.submit(new RevokeRoleCommand(ra, dvRequestService.getDataverseRequest())); JsfHelper.addSuccessMessage(ra.getRole().getName() + " role for " + roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()).getDisplayInfo().getTitle() + " was removed."); RoleAssignee assignee = roleAssigneeService.getRoleAssignee(ra.getAssigneeIdentifier()); notifyRoleChange(assignee, UserNotification.Type.REVOKEROLE); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role assignment was not able to be removed.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role assignment could not be removed."); logger.log(Level.SEVERE, "Error removing role assignment: " + ex.getMessage(), ex); } } /* main page - roles table */ public List<DataverseRole> getRoles() { if (dvObject != null && dvObject.getId() != null) { return roleService.findByOwnerId(dvObject.getId()); } return new ArrayList<>(); } public void createNewRole(ActionEvent e) { setRole(new DataverseRole()); role.setOwner(dvObject); } public void cloneRole(String roleId) { DataverseRole clonedRole = new DataverseRole(); clonedRole.setOwner(dvObject); DataverseRole originalRole = roleService.find(Long.parseLong(roleId)); clonedRole.addPermissions(originalRole.permissions()); setRole(clonedRole); } public void editRole(String roleId) { setRole(roleService.find(Long.parseLong(roleId))); } /* ============================================================================ edit configuration dialog // only for dataverse version of page ============================================================================ */ private String authenticatedUsersContributorRoleAlias = null; private String defaultContributorRoleAlias = DataverseRole.EDITOR; public String getAuthenticatedUsersContributorRoleAlias() { return authenticatedUsersContributorRoleAlias; } public void setAuthenticatedUsersContributorRoleAlias(String authenticatedUsersContributorRoleAlias) { this.authenticatedUsersContributorRoleAlias = authenticatedUsersContributorRoleAlias; } public String getDefaultContributorRoleAlias() { return defaultContributorRoleAlias; } public void setDefaultContributorRoleAlias(String defaultContributorRoleAlias) { this.defaultContributorRoleAlias = defaultContributorRoleAlias; } public void initAccessSettings() { if (dvObject instanceof Dataverse) { authenticatedUsersContributorRoleAlias = ""; List<RoleAssignment> aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject); for (RoleAssignment roleAssignment : aUsersRoleAssignments) { String roleAlias = roleAssignment.getRole().getAlias(); authenticatedUsersContributorRoleAlias = roleAlias; break; // @todo handle case where more than one role has been assigned to the AutenticatedUsers group! } defaultContributorRoleAlias = ((Dataverse) dvObject).getDefaultContributorRole().getAlias(); } } public void saveConfiguration(ActionEvent e) { // Set role (if any) for authenticatedUsers DataverseRole roleToAssign = null; List<String> contributorRoles = Arrays.asList(DataverseRole.FULL_CONTRIBUTOR, DataverseRole.DV_CONTRIBUTOR, DataverseRole.DS_CONTRIBUTOR); if (!StringUtil.isEmpty(authenticatedUsersContributorRoleAlias)) { roleToAssign = roleService.findBuiltinRoleByAlias(authenticatedUsersContributorRoleAlias); } // then, check current contributor role List<RoleAssignment> aUsersRoleAssignments = roleService.directRoleAssignments(AuthenticatedUsers.get(), dvObject); for (RoleAssignment roleAssignment : aUsersRoleAssignments) { DataverseRole currentRole = roleAssignment.getRole(); if (contributorRoles.contains(currentRole.getAlias())) { if (currentRole.equals(roleToAssign)) { roleToAssign = null; // found the role, so no need to assign } else { revokeRole(roleAssignment); } } } // finally, assign role, if new if (roleToAssign != null) { assignRole(AuthenticatedUsers.get(), roleToAssign); } // set dataverse default contributor role if (dvObject instanceof Dataverse) { Dataverse dv = (Dataverse) dvObject; DataverseRole defaultRole = roleService.findBuiltinRoleByAlias(defaultContributorRoleAlias); if (!defaultRole.equals(dv.getDefaultContributorRole())) { try { commandEngine.submit(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, dvRequestService.getDataverseRequest(), dv)); JsfHelper.addSuccessMessage("The default permissions for this dataverse have been updated."); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "Cannot assign default permissions.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "Cannot assign default permissions."); logger.log(Level.SEVERE, "Error assigning default permissions: " + ex.getMessage(), ex); } } } roleAssignments = initRoleAssignments(); showConfigureMessages(); } /* ============================================================================ assign roles dialog ============================================================================ */ private List<RoleAssignee> roleAssignSelectedRoleAssignees; private Long selectedRoleId; public List<RoleAssignee> getRoleAssignSelectedRoleAssignees() { return roleAssignSelectedRoleAssignees; } public void setRoleAssignSelectedRoleAssignees(List<RoleAssignee> selectedRoleAssignees) { this.roleAssignSelectedRoleAssignees = selectedRoleAssignees; } public Long getSelectedRoleId() { return selectedRoleId; } public void setSelectedRoleId(Long selectedRoleId) { this.selectedRoleId = selectedRoleId; } public void initAssigneeDialog(ActionEvent ae) { roleAssignSelectedRoleAssignees = new LinkedList<>(); selectedRoleId = null; showNoMessages(); } public List<RoleAssignee> completeRoleAssignee( String query ) { return roleAssigneeService.filterRoleAssignees(query, dvObject, roleAssignSelectedRoleAssignees); } public List<DataverseRole> getAvailableRoles() { List<DataverseRole> roles = new LinkedList<>(); if (dvObject != null && dvObject.getId() != null) { if (dvObject instanceof Dataverse) { roles.addAll(roleService.availableRoles(dvObject.getId())); } else if (dvObject instanceof Dataset) { // don't show roles that only have Dataverse level permissions // current the available roles for a dataset are gotten from its parent for (DataverseRole role : roleService.availableRoles(dvObject.getOwner().getId())) { for (Permission permission : role.permissions()) { if (permission.appliesTo(Dataset.class) || permission.appliesTo(DataFile.class)) { roles.add(role); break; } } } } else if (dvObject instanceof DataFile) { roles.add(roleService.findBuiltinRoleByAlias(DataverseRole.FILE_DOWNLOADER)); } Collections.sort(roles, DataverseRole.CMP_BY_NAME); } return roles; } public DataverseRole getAssignedRole() { if (selectedRoleId != null) { return roleService.find(selectedRoleId); } return null; } public String getAssignedRoleObjectTypes(){ String retString = ""; if (selectedRoleId != null) { if (dataverseRolePermissionHelper.hasDataversePermissions(selectedRoleId) && dvObject instanceof Dataverse){ String dvLabel = ResourceBundle.getBundle("Bundle").getString("dataverses"); retString = dvLabel; } if (dataverseRolePermissionHelper.hasDatasetPermissions(selectedRoleId) && dvObject instanceof Dataverse){ String dsLabel = ResourceBundle.getBundle("Bundle").getString("datasets"); if(!retString.isEmpty()) { retString +=", " + dsLabel; } else { retString = dsLabel; } } if (dataverseRolePermissionHelper.hasFilePermissions(selectedRoleId)){ String filesLabel = ResourceBundle.getBundle("Bundle").getString("files"); if(!retString.isEmpty()) { retString +=", " + filesLabel; } else { retString = filesLabel; } } return retString; } return null; } public String getDefinitionLevelString(){ if (dvObject != null){ if (dvObject instanceof Dataverse) return ResourceBundle.getBundle("Bundle").getString("dataverse"); if (dvObject instanceof Dataset) return ResourceBundle.getBundle("Bundle").getString("dataset"); } return null; } public void assignRole(ActionEvent evt) { logger.info("Got to assignRole"); List<RoleAssignee> selectedRoleAssigneesList = getRoleAssignSelectedRoleAssignees(); if ( selectedRoleAssigneesList == null ) { logger.info("** SELECTED role asignees is null"); selectedRoleAssigneesList = new LinkedList<>(); } for (RoleAssignee roleAssignee : selectedRoleAssigneesList) { assignRole(roleAssignee, roleService.find(selectedRoleId)); } roleAssignments = initRoleAssignments(); } /** * Notify a {@code RoleAssignee} that a role was either assigned or revoked. * Will notify all members of a group. * @param ra The {@code RoleAssignee} to be notified. * @param type The type of notification. */ private void notifyRoleChange(RoleAssignee ra, UserNotification.Type type) { if (ra instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) ra, new Timestamp(new Date().getTime()), type, dvObject.getId()); } else if (ra instanceof ExplicitGroup) { ExplicitGroup eg = (ExplicitGroup) ra; Set<String> explicitGroupMembers = eg.getContainedRoleAssgineeIdentifiers(); for (String id : explicitGroupMembers) { RoleAssignee explicitGroupMember = roleAssigneeService.getRoleAssignee(id); if (explicitGroupMember instanceof AuthenticatedUser) { userNotificationService.sendNotification((AuthenticatedUser) explicitGroupMember, new Timestamp(new Date().getTime()), type, dvObject.getId()); } } } } private void assignRole(RoleAssignee ra, DataverseRole r) { try { String privateUrlToken = null; commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(), privateUrlToken)); JsfHelper.addSuccessMessage(r.getName() + " role assigned to " + ra.getDisplayInfo().getTitle() + " for " + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()) + "."); // don't notify if role = file downloader and object is not released if (!(r.getAlias().equals(DataverseRole.FILE_DOWNLOADER) && !dvObject.isReleased()) ){ notifyRoleChange(ra, UserNotification.Type.ASSIGNROLE); } } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role was not able to be assigned.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role was not able to be assigned."); logger.log(Level.SEVERE, "Error assiging role: " + ex.getMessage(), ex); } showAssignmentMessages(); } /* ============================================================================ edit role dialog ============================================================================ */ private DataverseRole role = new DataverseRole(); private List<String> selectedPermissions; public DataverseRole getRole() { return role; } public void setRole(DataverseRole role) { this.role = role; selectedPermissions = new LinkedList<>(); if (role != null) { for (Permission p : role.permissions()) { selectedPermissions.add(p.name()); } } } public List<String> getSelectedPermissions() { return selectedPermissions; } public void setSelectedPermissions(List<String> selectedPermissions) { this.selectedPermissions = selectedPermissions; } public List<Permission> getPermissions() { return Arrays.asList(Permission.values()); } public void updateRole(ActionEvent e) { // @todo currently only works for Dataverse since CreateRoleCommand only takes a dataverse // we need to decide if we want roles at the dataset level or not if (dvObject instanceof Dataverse) { role.clearPermissions(); for (String pmsnStr : getSelectedPermissions()) { role.addPermission(Permission.valueOf(pmsnStr)); } try { String roleState = role.getId() != null ? "updated" : "created"; setRole(commandEngine.submit(new CreateRoleCommand(role, dvRequestService.getDataverseRequest(), (Dataverse) role.getOwner()))); JsfHelper.addSuccessMessage("The role was " + roleState + ". To assign it to a user and/or group, click on the Assign Roles to Users/Groups button in the Users/Groups section of this page."); } catch (PermissionException ex) { JH.addMessage(FacesMessage.SEVERITY_ERROR, "The role was not able to be saved.", "Permissions " + ex.getRequiredPermissions().toString() + " missing."); } catch (CommandException ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, "The role was not able to be saved."); logger.log(Level.SEVERE, "Error saving role: " + ex.getMessage(), ex); } } showRoleMessages(); } public DataverseRolePermissionHelper getDataverseRolePermissionHelper() { return dataverseRolePermissionHelper; } public void setDataverseRolePermissionHelper(DataverseRolePermissionHelper dataverseRolePermissionHelper) { this.dataverseRolePermissionHelper = dataverseRolePermissionHelper; } /* ============================================================================ Internal methods ============================================================================ */ boolean renderConfigureMessages = false; boolean renderAssignmentMessages = false; boolean renderRoleMessages = false; private void showNoMessages() { renderConfigureMessages = false; renderAssignmentMessages = false; renderRoleMessages = false; } private void showConfigureMessages() { renderConfigureMessages = true; renderAssignmentMessages = false; renderRoleMessages = false; } private void showAssignmentMessages() { renderConfigureMessages = false; renderAssignmentMessages = true; renderRoleMessages = false; } private void showRoleMessages() { renderConfigureMessages = false; renderAssignmentMessages = false; renderRoleMessages = true; } public Boolean getRenderConfigureMessages() { return renderConfigureMessages; } public void setRenderConfigureMessages(Boolean renderConfigureMessages) { this.renderConfigureMessages = renderConfigureMessages; } public Boolean getRenderAssignmentMessages() { return renderAssignmentMessages; } public void setRenderAssignmentMessages(Boolean renderAssignmentMessages) { this.renderAssignmentMessages = renderAssignmentMessages; } public Boolean getRenderRoleMessages() { return renderRoleMessages; } public void setRenderRoleMessages(Boolean renderRoleMessages) { this.renderRoleMessages = renderRoleMessages; } // inner class used for display of role assignments public static class RoleAssignmentRow { private final RoleAssigneeDisplayInfo assigneeDisplayInfo; private final RoleAssignment ra; public RoleAssignmentRow(RoleAssignment anRa, RoleAssigneeDisplayInfo disInf) { ra = anRa; assigneeDisplayInfo = disInf; } public RoleAssignment getRoleAssignment() { return ra; } public RoleAssigneeDisplayInfo getAssigneeDisplayInfo() { return assigneeDisplayInfo; } public DataverseRole getRole() { return ra.getRole(); } public String getRoleName() { return getRole().getName(); } public DvObject getDefinitionPoint() { return ra.getDefinitionPoint(); } public String getAssignedDvName() { return ra.getDefinitionPoint().getDisplayName(); } public Long getId() { return ra.getId(); } } }
#2657 Remove DV from permissions caveat
src/main/java/edu/harvard/iq/dataverse/ManagePermissionsPage.java
#2657 Remove DV from permissions caveat
Java
bsd-2-clause
f04413bcb6fdf6bfa1b19f3c8d5fce99597185db
0
alpha-asp/Alpha,AntoniusW/Alpha,alpha-asp/Alpha
/** * Copyright (c) 2016-2019, the Alpha Team. * All rights reserved. * * Additional changes made by Siemens. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package at.ac.tuwien.kr.alpha.grounder; import at.ac.tuwien.kr.alpha.common.*; import at.ac.tuwien.kr.alpha.common.NoGood.Type; import at.ac.tuwien.kr.alpha.common.atoms.*; import at.ac.tuwien.kr.alpha.common.terms.VariableTerm; import at.ac.tuwien.kr.alpha.grounder.atoms.ChoiceAtom; import at.ac.tuwien.kr.alpha.grounder.atoms.EnumerationAtom; import at.ac.tuwien.kr.alpha.grounder.atoms.IntervalLiteral; import at.ac.tuwien.kr.alpha.grounder.atoms.RuleAtom; import at.ac.tuwien.kr.alpha.grounder.bridges.Bridge; import at.ac.tuwien.kr.alpha.grounder.heuristics.GrounderHeuristicsConfiguration; import at.ac.tuwien.kr.alpha.grounder.structure.AnalyzeUnjustified; import at.ac.tuwien.kr.alpha.grounder.structure.ProgramAnalysis; import at.ac.tuwien.kr.alpha.grounder.transformation.*; import at.ac.tuwien.kr.alpha.solver.ThriceTruth; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static at.ac.tuwien.kr.alpha.Util.oops; import static at.ac.tuwien.kr.alpha.common.Literals.atomOf; import static java.util.Collections.singletonList; /** * A semi-naive grounder. * Copyright (c) 2016-2019, the Alpha Team. */ public class NaiveGrounder extends BridgedGrounder implements ProgramAnalyzingGrounder { private static final Logger LOGGER = LoggerFactory.getLogger(NaiveGrounder.class); private final WorkingMemory workingMemory = new WorkingMemory(); private final AtomStore atomStore; private final NogoodRegistry registry = new NogoodRegistry(); final NoGoodGenerator noGoodGenerator; private final ChoiceRecorder choiceRecorder; private final ProgramAnalysis programAnalysis; private final AnalyzeUnjustified analyzeUnjustified; private final Map<Predicate, LinkedHashSet<Instance>> factsFromProgram = new LinkedHashMap<>(); private final Map<IndexedInstanceStorage, ArrayList<FirstBindingAtom>> rulesUsingPredicateWorkingMemory = new HashMap<>(); private final Map<NonGroundRule, HashSet<Substitution>> knownGroundingSubstitutions = new HashMap<>(); private final Map<Integer, NonGroundRule> knownNonGroundRules = new HashMap<>(); private ArrayList<NonGroundRule> fixedRules = new ArrayList<>(); private LinkedHashSet<Atom> removeAfterObtainingNewNoGoods = new LinkedHashSet<>(); private boolean disableInstanceRemoval; private final boolean useCountingGridNormalization; private final boolean debugInternalChecks; private final GrounderHeuristicsConfiguration heuristicsConfiguration; public NaiveGrounder(Program program, AtomStore atomStore, boolean debugInternalChecks, Bridge... bridges) { this(program, atomStore, new GrounderHeuristicsConfiguration(), debugInternalChecks, bridges); } private NaiveGrounder(Program program, AtomStore atomStore, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean debugInternalChecks, Bridge... bridges) { this(program, atomStore, p -> true, heuristicsConfiguration, false, debugInternalChecks, bridges); } NaiveGrounder(Program program, AtomStore atomStore, java.util.function.Predicate<Predicate> filter, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean useCountingGrid, boolean debugInternalChecks, Bridge... bridges) { super(filter, bridges); this.atomStore = atomStore; this.heuristicsConfiguration = heuristicsConfiguration; LOGGER.debug("Grounder configuration: " + heuristicsConfiguration); programAnalysis = new ProgramAnalysis(program); analyzeUnjustified = new AnalyzeUnjustified(programAnalysis, atomStore, factsFromProgram); // Apply program transformations/rewritings. useCountingGridNormalization = useCountingGrid; applyProgramTransformations(program); LOGGER.debug("Transformed input program is:\n" + program); initializeFactsAndRules(program); final Set<NonGroundRule> uniqueGroundRulePerGroundHead = getRulesWithUniqueHead(); choiceRecorder = new ChoiceRecorder(atomStore); noGoodGenerator = new NoGoodGenerator(atomStore, choiceRecorder, factsFromProgram, programAnalysis, uniqueGroundRulePerGroundHead); this.debugInternalChecks = debugInternalChecks; } private void initializeFactsAndRules(Program program) { // initialize all facts for (Atom fact : program.getFacts()) { final Predicate predicate = fact.getPredicate(); // Record predicate workingMemory.initialize(predicate); // Construct fact instance(s). List<Instance> instances = FactIntervalEvaluator.constructFactInstances(fact); // Add instances to corresponding list of facts. factsFromProgram.putIfAbsent(predicate, new LinkedHashSet<>()); HashSet<Instance> internalPredicateInstances = factsFromProgram.get(predicate); internalPredicateInstances.addAll(instances); } // Register internal atoms. workingMemory.initialize(RuleAtom.PREDICATE); workingMemory.initialize(ChoiceAtom.OFF); workingMemory.initialize(ChoiceAtom.ON); // Initialize rules and constraints. for (Rule rule : program.getRules()) { // Record the rule for later use NonGroundRule nonGroundRule = NonGroundRule.constructNonGroundRule(rule); knownNonGroundRules.put(nonGroundRule.getRuleId(), nonGroundRule); LOGGER.debug("NonGroundRule #" + nonGroundRule.getRuleId() + ": " + nonGroundRule); // Record defining rules for each predicate. Atom headAtom = nonGroundRule.getHeadAtom(); if (headAtom != null) { Predicate headPredicate = headAtom.getPredicate(); programAnalysis.recordDefiningRule(headPredicate, nonGroundRule); } // Create working memories for all predicates occurring in the rule for (Predicate predicate : nonGroundRule.getOccurringPredicates()) { // FIXME: this also contains interval/builtin predicates that are not needed. workingMemory.initialize(predicate); } // If the rule has fixed ground instantiations, it is not registered but grounded once like facts. if (nonGroundRule.groundingOrder.fixedInstantiation()) { fixedRules.add(nonGroundRule); continue; } // Register each starting literal at the corresponding working memory. for (Literal literal : nonGroundRule.groundingOrder.getStartingLiterals()) { registerLiteralAtWorkingMemory(literal, nonGroundRule); } } } private Set<NonGroundRule> getRulesWithUniqueHead() { // FIXME: below optimisation (adding support nogoods if there is only one rule instantiation per unique atom over the interpretation) could be done as a transformation (adding a non-ground constraint corresponding to the nogood that is generated by the grounder). // Record all unique rule heads. final Set<NonGroundRule> uniqueGroundRulePerGroundHead = new HashSet<>(); for (Map.Entry<Predicate, HashSet<NonGroundRule>> headDefiningRules : programAnalysis.getPredicateDefiningRules().entrySet()) { if (headDefiningRules.getValue().size() != 1) { continue; } NonGroundRule nonGroundRule = headDefiningRules.getValue().iterator().next(); // Check that all variables of the body also occur in the head (otherwise grounding is not unique). Atom headAtom = nonGroundRule.getHeadAtom(); // Rule is not guaranteed unique if there are facts for it. HashSet<Instance> potentialFacts = factsFromProgram.get(headAtom.getPredicate()); if (potentialFacts != null && !potentialFacts.isEmpty()) { continue; } // Collect head and body variables. HashSet<VariableTerm> occurringVariablesHead = new HashSet<>(headAtom.toLiteral().getBindingVariables()); HashSet<VariableTerm> occurringVariablesBody = new HashSet<>(); for (Atom atom : nonGroundRule.getBodyAtomsPositive()) { occurringVariablesBody.addAll(atom.toLiteral().getBindingVariables()); } occurringVariablesBody.removeAll(occurringVariablesHead); // Check if ever body variables occurs in the head. if (occurringVariablesBody.isEmpty()) { uniqueGroundRulePerGroundHead.add(nonGroundRule); } } return uniqueGroundRulePerGroundHead; } private void applyProgramTransformations(Program program) { // Transform choice rules. new ChoiceHeadToNormal().transform(program); // Transform cardinality aggregates. new CardinalityNormalization(!useCountingGridNormalization).transform(program); // Transform sum aggregates. new SumNormalization().transform(program); // Transform intervals. new IntervalTermToIntervalAtom().transform(program); // Remove variable equalities. new VariableEqualityRemoval().transform(program); // Transform enumeration atoms. new EnumerationRewriting().transform(program); EnumerationAtom.resetEnumerations(); } /** * Registers a starting literal of a NonGroundRule at its corresponding working memory. * @param nonGroundRule the rule in which the literal occurs. */ private void registerLiteralAtWorkingMemory(Literal literal, NonGroundRule nonGroundRule) { if (literal.isNegated()) { throw new RuntimeException("Literal to register is negated. Should not happen."); } IndexedInstanceStorage workingMemory = this.workingMemory.get(literal.getPredicate(), true); rulesUsingPredicateWorkingMemory.putIfAbsent(workingMemory, new ArrayList<>()); rulesUsingPredicateWorkingMemory.get(workingMemory).add(new FirstBindingAtom(nonGroundRule, literal)); } @Override public AnswerSet assignmentToAnswerSet(Iterable<Integer> trueAtoms) { Map<Predicate, SortedSet<Atom>> predicateInstances = new LinkedHashMap<>(); SortedSet<Predicate> knownPredicates = new TreeSet<>(); // Iterate over all true atomIds, computeNextAnswerSet instances from atomStore and add them if not filtered. for (int trueAtom : trueAtoms) { final Atom atom = atomStore.get(trueAtom); Predicate predicate = atom.getPredicate(); // Skip atoms over internal predicates. if (predicate.isInternal()) { continue; } // Skip filtered predicates. if (!filter.test(predicate)) { continue; } knownPredicates.add(predicate); predicateInstances.putIfAbsent(predicate, new TreeSet<>()); Set<Atom> instances = predicateInstances.get(predicate); instances.add(atom); } // Add true atoms from facts. for (Map.Entry<Predicate, LinkedHashSet<Instance>> facts : factsFromProgram.entrySet()) { Predicate factPredicate = facts.getKey(); // Skip atoms over internal predicates. if (factPredicate.isInternal()) { continue; } // Skip filtered predicates. if (!filter.test(factPredicate)) { continue; } // Skip predicates without any instances. if (facts.getValue().isEmpty()) { continue; } knownPredicates.add(factPredicate); predicateInstances.putIfAbsent(factPredicate, new TreeSet<>()); for (Instance factInstance : facts.getValue()) { SortedSet<Atom> instances = predicateInstances.get(factPredicate); instances.add(new BasicAtom(factPredicate, factInstance.terms)); } } if (knownPredicates.isEmpty()) { return BasicAnswerSet.EMPTY; } return new BasicAnswerSet(knownPredicates, predicateInstances); } /** * Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once. * @return */ private HashMap<Integer, NoGood> bootstrap() { final HashMap<Integer, NoGood> groundNogoods = new LinkedHashMap<>(); for (Predicate predicate : factsFromProgram.keySet()) { // Instead of generating NoGoods, add instance to working memories directly. workingMemory.addInstances(predicate, true, factsFromProgram.get(predicate)); } for (NonGroundRule nonGroundRule : fixedRules) { // Generate NoGoods for all rules that have a fixed grounding. RuleGroundingOrder groundingOrder = nonGroundRule.groundingOrder.getFixedGroundingOrder(); BindingResult bindingResult = bindNextAtomInRule(nonGroundRule, groundingOrder, new Substitution(), null); groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, groundNogoods); } fixedRules = null; return groundNogoods; } @Override public Map<Integer, NoGood> getNoGoods(Assignment currentAssignment) { // In first call, prepare facts and ground rules. final Map<Integer, NoGood> newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>(); // Compute new ground rule (evaluate joins with newly changed atoms) for (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) { // Skip predicates solely used in the solver which do not occur in rules. Predicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate(); if (workingMemoryPredicate.isSolverInternal()) { continue; } // Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory. final ArrayList<FirstBindingAtom> firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory); // Skip working memories that are not used by any rule. if (firstBindingAtoms == null) { continue; } for (FirstBindingAtom firstBindingAtom : firstBindingAtoms) { // Use the recently added instances from the modified working memory to construct an initial substitution NonGroundRule nonGroundRule = firstBindingAtom.rule; // Generate substitutions from each recent instance. for (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) { // Check instance if it matches with the atom. final Substitution unifier = Substitution.unify(firstBindingAtom.startingLiteral, instance, new Substitution()); if (unifier == null) { continue; } final BindingResult bindingResult = bindNextAtomInRule( nonGroundRule, nonGroundRule.groundingOrder.orderStartingFrom(firstBindingAtom.startingLiteral), unifier, currentAssignment ); groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, newNoGoods); } } // Mark instances added by updateAssignment as done modifiedWorkingMemory.markRecentlyAddedInstancesDone(); } workingMemory.reset(); for (Atom removeAtom : removeAfterObtainingNewNoGoods) { final IndexedInstanceStorage storage = this.workingMemory.get(removeAtom, true); Instance instance = new Instance(removeAtom.getTerms()); if (storage.containsInstance(instance)) { // lax grounder heuristics may attempt to remove instances that are not yet in the working memory storage.removeInstance(instance); } } removeAfterObtainingNewNoGoods = new LinkedHashSet<>(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Grounded NoGoods are:"); for (Map.Entry<Integer, NoGood> noGoodEntry : newNoGoods.entrySet()) { LOGGER.debug("{} == {}", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue())); } LOGGER.debug("{}", choiceRecorder); } if (debugInternalChecks) { checkTypesOfNoGoods(newNoGoods.values()); } return newNoGoods; } /** * Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that process. * * @param nonGroundRule * the rule to be grounded * @param substitutions * the substitutions to be applied * @param newNoGoods * a set of nogoods to which newly generated nogoods will be added */ private void groundAndRegister(final NonGroundRule nonGroundRule, final List<Substitution> substitutions, final Map<Integer, NoGood> newNoGoods) { for (Substitution substitution : substitutions) { List<NoGood> generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution); registry.register(generatedNoGoods, newNoGoods); } } @Override public int register(NoGood noGood) { return registry.register(noGood); } private BindingResult bindNextAtomInRule(NonGroundRule rule, RuleGroundingOrder groundingOrder, Substitution partialSubstitution, Assignment currentAssignment) { int tolerance = heuristicsConfiguration.getTolerance(rule.isConstraint()); if (tolerance < 0) { tolerance = Integer.MAX_VALUE; } BindingResult bindingResult = bindNextAtomInRule(groundingOrder, 0, tolerance, tolerance, partialSubstitution, currentAssignment); if (LOGGER.isDebugEnabled()) { for (int i = 0; i < bindingResult.size(); i++) { Integer numberOfUnassignedPositiveBodyAtoms = bindingResult.numbersOfUnassignedPositiveBodyAtoms.get(i); if (numberOfUnassignedPositiveBodyAtoms > 0) { LOGGER.debug("Grounded rule in which " + numberOfUnassignedPositiveBodyAtoms + " positive atoms are still unassigned: " + rule + " (substitution: " + bindingResult.generatedSubstitutions.get(i) + ")"); } } } return bindingResult; } private BindingResult advanceAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { groundingOrder.considerUntilCurrentEnd(); return bindNextAtomInRule(groundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } private BindingResult pushBackAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { RuleGroundingOrder modifiedGroundingOrder = groundingOrder.pushBack(orderPosition); if (modifiedGroundingOrder == null) { return BindingResult.empty(); } return bindNextAtomInRule(modifiedGroundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } private BindingResult bindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { boolean laxGrounderHeuristic = originalTolerance > 0; Literal currentLiteral = groundingOrder.getLiteralAtOrderPosition(orderPosition); if (currentLiteral == null) { return BindingResult.singleton(partialSubstitution, originalTolerance - remainingTolerance); } Atom currentAtom = currentLiteral.getAtom(); if (currentLiteral instanceof FixedInterpretationLiteral) { // Generate all substitutions for the builtin/external/interval atom. FixedInterpretationLiteral substitutedLiteral = (FixedInterpretationLiteral)currentLiteral.substitute(partialSubstitution); // TODO: this has to be improved before merging into master: if (!substitutedLiteral.isGround() && !(substitutedLiteral instanceof ComparisonLiteral && ((ComparisonLiteral)substitutedLiteral).isLeftOrRightAssigning()) && !(substitutedLiteral instanceof IntervalLiteral && substitutedLiteral.getTerms().get(0).isGround()) && !(substitutedLiteral instanceof ExternalLiteral) ) { return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } final List<Substitution> substitutions = substitutedLiteral.getSubstitutions(partialSubstitution); if (substitutions.isEmpty()) { // if FixedInterpretationLiteral cannot be satisfied now, it will never be return BindingResult.empty(); } final BindingResult bindingResult = new BindingResult(); for (Substitution substitution : substitutions) { // Continue grounding with each of the generated values. bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, substitution, currentAssignment)); } return bindingResult; } if (currentAtom instanceof EnumerationAtom) { // Get the enumeration value and add it to the current partialSubstitution. ((EnumerationAtom) currentAtom).addEnumerationToSubstitution(partialSubstitution); return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } Collection<Instance> instances = null; // check if partialVariableSubstitution already yields a ground atom final Atom substitute = currentAtom.substitute(partialSubstitution); if (substitute.isGround()) { // Substituted atom is ground, in case it is positive, only ground if it also holds true if (currentLiteral.isNegated()) { // Atom occurs negated in the rule: continue grounding return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } if (!groundingOrder.isGround() && remainingTolerance <= 0 && !workingMemory.get(currentAtom.getPredicate(), true).containsInstance(new Instance(substitute.getTerms()))) { // Generate no variable substitution. return BindingResult.empty(); } // Check if atom is also assigned true. final LinkedHashSet<Instance> factInstances = factsFromProgram.get(substitute.getPredicate()); if (factInstances != null && factInstances.contains(new Instance(substitute.getTerms()))) { // Ground literal holds, continue finding a variable substitution. return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } // Atom is not a fact already. instances = singletonList(new Instance(substitute.getTerms())); } // substituted atom contains variables if (currentLiteral.isNegated()) { if (laxGrounderHeuristic) { return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } else { throw oops("Current atom should be positive at this point but is not"); } } if (instances == null) { instances = getInstancesForSubstitute(substitute, partialSubstitution); } if (laxGrounderHeuristic && instances.isEmpty()) { // we have reached a point where we have to terminate binding, // but it might be possible that a different grounding order would allow us to continue binding // under the presence of a lax grounder heuristic return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } return createBindings(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment, instances, substitute); } private Collection<Instance> getInstancesForSubstitute(Atom substitute, Substitution partialSubstitution) { Collection<Instance> instances; IndexedInstanceStorage storage = workingMemory.get(substitute.getPredicate(), true); if (partialSubstitution.isEmpty()) { // No variables are bound, but first atom in the body became recently true, consider all instances now. instances = storage.getAllInstances(); } else { instances = storage.getInstancesFromPartiallyGroundAtom(substitute); } return instances; } private BindingResult createBindings(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment, Collection<Instance> instances, Atom substitute) { BindingResult bindingResult = new BindingResult(); for (Instance instance : instances) { // Check each instance if it matches with the atom. Substitution unified = Substitution.unify(substitute, instance, new Substitution(partialSubstitution)); if (unified == null) { continue; } // Check if atom is also assigned true. Atom substituteClone = new BasicAtom(substitute.getPredicate(), substitute.getTerms()); Atom substitutedAtom = substituteClone.substitute(unified); if (!substitutedAtom.isGround()) { throw oops("Grounded atom should be ground but is not"); } AtomicInteger atomicRemainingTolerance = new AtomicInteger(remainingTolerance); // TODO: done this way for call-by-reference, should be refactored if (factsFromProgram.get(substitutedAtom.getPredicate()) == null || !factsFromProgram.get(substitutedAtom.getPredicate()).contains(new Instance(substitutedAtom.getTerms()))) { if (storeAtomAndTerminateIfAtomDoesNotHold(substitutedAtom, currentAssignment, atomicRemainingTolerance)) { continue; } } bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, atomicRemainingTolerance.get(), unified, currentAssignment)); } return bindingResult; } private boolean storeAtomAndTerminateIfAtomDoesNotHold(final Atom substitute, Assignment currentAssignment, AtomicInteger remainingTolerance) { final int atomId = atomStore.putIfAbsent(substitute); if (currentAssignment != null) { ThriceTruth truth = currentAssignment.isAssigned(atomId) ? currentAssignment.getTruth(atomId) : null; if (truth == null || !truth.toBoolean()) { // Atom currently does not hold if (!disableInstanceRemoval) { removeAfterObtainingNewNoGoods.add(substitute); } if (truth == null && remainingTolerance.decrementAndGet() < 0) { // terminate if more positive atoms are unsatisfied as tolerated by the heuristic return true; } // terminate if positive body atom is assigned false return truth != null && !truth.toBoolean(); } } return false; } @Override public Pair<Map<Integer, Integer>, Map<Integer, Integer>> getChoiceAtoms() { return choiceRecorder.getAndResetChoices(); } @Override public Map<Integer, Set<Integer>> getHeadsToBodies() { return choiceRecorder.getAndResetHeadsToBodies(); } @Override public void updateAssignment(Iterator<Integer> it) { while (it.hasNext()) { workingMemory.addInstance(atomStore.get(it.next()), true); } } @Override public void forgetAssignment(int[] atomIds) { throw new UnsupportedOperationException("Forgetting assignments is not implemented"); } public static String groundAndPrintRule(NonGroundRule rule, Substitution substitution) { StringBuilder ret = new StringBuilder(); if (!rule.isConstraint()) { Atom groundHead = rule.getHeadAtom().substitute(substitution); ret.append(groundHead.toString()); } ret.append(" :- "); boolean isFirst = true; for (Atom bodyAtom : rule.getBodyAtomsPositive()) { ret.append(groundLiteralToString(bodyAtom.toLiteral(), substitution, isFirst)); isFirst = false; } for (Atom bodyAtom : rule.getBodyAtomsNegative()) { ret.append(groundLiteralToString(bodyAtom.toLiteral(false), substitution, isFirst)); isFirst = false; } ret.append("."); return ret.toString(); } static String groundLiteralToString(Literal literal, Substitution substitution, boolean isFirst) { Literal groundLiteral = literal.substitute(substitution); return (isFirst ? "" : ", ") + groundLiteral.toString(); } @Override public NonGroundRule getNonGroundRule(Integer ruleId) { return knownNonGroundRules.get(ruleId); } @Override public boolean isFact(Atom atom) { LinkedHashSet<Instance> instances = factsFromProgram.get(atom.getPredicate()); if (instances == null) { return false; } return instances.contains(new Instance(atom.getTerms())); } @Override public Set<Literal> justifyAtom(int atomToJustify, Assignment currentAssignment) { Set<Literal> literals = analyzeUnjustified.analyze(atomToJustify, currentAssignment); // Remove facts from justification before handing it over to the solver. for (Iterator<Literal> iterator = literals.iterator(); iterator.hasNext();) { Literal literal = iterator.next(); if (literal.isNegated()) { continue; } LinkedHashSet<Instance> factsOverPredicate = factsFromProgram.get(literal.getPredicate()); if (factsOverPredicate != null && factsOverPredicate.contains(new Instance(literal.getAtom().getTerms()))) { iterator.remove(); } } return literals; } /** * Checks that every nogood not marked as {@link NoGood.Type#INTERNAL} contains only * atoms which are not {@link Predicate#isSolverInternal()} (except {@link RuleAtom}s, which are allowed). * @param newNoGoods */ private void checkTypesOfNoGoods(Collection<NoGood> newNoGoods) { for (NoGood noGood : newNoGoods) { if (noGood.getType() != Type.INTERNAL) { for (int literal : noGood) { Atom atom = atomStore.get(atomOf(literal)); if (atom.getPredicate().isSolverInternal() && !(atom instanceof RuleAtom)) { throw oops("NoGood containing atom of internal predicate " + atom + " is " + noGood.getType() + " instead of INTERNAL"); } } } } } private static class FirstBindingAtom { final NonGroundRule rule; final Literal startingLiteral; FirstBindingAtom(NonGroundRule rule, Literal startingLiteral) { this.rule = rule; this.startingLiteral = startingLiteral; } } private static class BindingResult { final List<Substitution> generatedSubstitutions = new ArrayList<>(); final List<Integer> numbersOfUnassignedPositiveBodyAtoms = new ArrayList<>(); void add(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) { this.generatedSubstitutions.add(generatedSubstitution); this.numbersOfUnassignedPositiveBodyAtoms.add(numberOfUnassignedPositiveBodyAtoms); } void add(BindingResult otherBindingResult) { this.generatedSubstitutions.addAll(otherBindingResult.generatedSubstitutions); this.numbersOfUnassignedPositiveBodyAtoms.addAll(otherBindingResult.numbersOfUnassignedPositiveBodyAtoms); } int size() { return generatedSubstitutions.size(); } static BindingResult empty() { return new BindingResult(); } static BindingResult singleton(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) { BindingResult bindingResult = new BindingResult(); bindingResult.add(generatedSubstitution, numberOfUnassignedPositiveBodyAtoms); return bindingResult; } } }
src/main/java/at/ac/tuwien/kr/alpha/grounder/NaiveGrounder.java
/** * Copyright (c) 2016-2019, the Alpha Team. * All rights reserved. * * Additional changes made by Siemens. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package at.ac.tuwien.kr.alpha.grounder; import at.ac.tuwien.kr.alpha.common.*; import at.ac.tuwien.kr.alpha.common.NoGood.Type; import at.ac.tuwien.kr.alpha.common.atoms.*; import at.ac.tuwien.kr.alpha.common.terms.VariableTerm; import at.ac.tuwien.kr.alpha.grounder.atoms.ChoiceAtom; import at.ac.tuwien.kr.alpha.grounder.atoms.EnumerationAtom; import at.ac.tuwien.kr.alpha.grounder.atoms.IntervalLiteral; import at.ac.tuwien.kr.alpha.grounder.atoms.RuleAtom; import at.ac.tuwien.kr.alpha.grounder.bridges.Bridge; import at.ac.tuwien.kr.alpha.grounder.heuristics.GrounderHeuristicsConfiguration; import at.ac.tuwien.kr.alpha.grounder.structure.AnalyzeUnjustified; import at.ac.tuwien.kr.alpha.grounder.structure.ProgramAnalysis; import at.ac.tuwien.kr.alpha.grounder.transformation.*; import at.ac.tuwien.kr.alpha.solver.ThriceTruth; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import static at.ac.tuwien.kr.alpha.Util.oops; import static at.ac.tuwien.kr.alpha.common.Literals.atomOf; import static java.util.Collections.singletonList; /** * A semi-naive grounder. * Copyright (c) 2016-2019, the Alpha Team. */ public class NaiveGrounder extends BridgedGrounder implements ProgramAnalyzingGrounder { private static final Logger LOGGER = LoggerFactory.getLogger(NaiveGrounder.class); private final WorkingMemory workingMemory = new WorkingMemory(); private final AtomStore atomStore; private final NogoodRegistry registry = new NogoodRegistry(); final NoGoodGenerator noGoodGenerator; private final ChoiceRecorder choiceRecorder; private final ProgramAnalysis programAnalysis; private final AnalyzeUnjustified analyzeUnjustified; private final Map<Predicate, LinkedHashSet<Instance>> factsFromProgram = new LinkedHashMap<>(); private final Map<IndexedInstanceStorage, ArrayList<FirstBindingAtom>> rulesUsingPredicateWorkingMemory = new HashMap<>(); private final Map<NonGroundRule, HashSet<Substitution>> knownGroundingSubstitutions = new HashMap<>(); private final Map<Integer, NonGroundRule> knownNonGroundRules = new HashMap<>(); private ArrayList<NonGroundRule> fixedRules = new ArrayList<>(); private LinkedHashSet<Atom> removeAfterObtainingNewNoGoods = new LinkedHashSet<>(); private boolean disableInstanceRemoval; private final boolean useCountingGridNormalization; private final boolean debugInternalChecks; private final GrounderHeuristicsConfiguration heuristicsConfiguration; public NaiveGrounder(Program program, AtomStore atomStore, boolean debugInternalChecks, Bridge... bridges) { this(program, atomStore, new GrounderHeuristicsConfiguration(), debugInternalChecks, bridges); } private NaiveGrounder(Program program, AtomStore atomStore, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean debugInternalChecks, Bridge... bridges) { this(program, atomStore, p -> true, heuristicsConfiguration, false, debugInternalChecks, bridges); } NaiveGrounder(Program program, AtomStore atomStore, java.util.function.Predicate<Predicate> filter, GrounderHeuristicsConfiguration heuristicsConfiguration, boolean useCountingGrid, boolean debugInternalChecks, Bridge... bridges) { super(filter, bridges); this.atomStore = atomStore; this.heuristicsConfiguration = heuristicsConfiguration; LOGGER.debug("Grounder configuration: " + heuristicsConfiguration); programAnalysis = new ProgramAnalysis(program); analyzeUnjustified = new AnalyzeUnjustified(programAnalysis, atomStore, factsFromProgram); // Apply program transformations/rewritings. useCountingGridNormalization = useCountingGrid; applyProgramTransformations(program); LOGGER.debug("Transformed input program is:\n" + program); initializeFactsAndRules(program); final Set<NonGroundRule> uniqueGroundRulePerGroundHead = getRulesWithUniqueHead(); choiceRecorder = new ChoiceRecorder(atomStore); noGoodGenerator = new NoGoodGenerator(atomStore, choiceRecorder, factsFromProgram, programAnalysis, uniqueGroundRulePerGroundHead); this.debugInternalChecks = debugInternalChecks; } private void initializeFactsAndRules(Program program) { // initialize all facts for (Atom fact : program.getFacts()) { final Predicate predicate = fact.getPredicate(); // Record predicate workingMemory.initialize(predicate); // Construct fact instance(s). List<Instance> instances = FactIntervalEvaluator.constructFactInstances(fact); // Add instances to corresponding list of facts. factsFromProgram.putIfAbsent(predicate, new LinkedHashSet<>()); HashSet<Instance> internalPredicateInstances = factsFromProgram.get(predicate); internalPredicateInstances.addAll(instances); } // Register internal atoms. workingMemory.initialize(RuleAtom.PREDICATE); workingMemory.initialize(ChoiceAtom.OFF); workingMemory.initialize(ChoiceAtom.ON); // Initialize rules and constraints. for (Rule rule : program.getRules()) { // Record the rule for later use NonGroundRule nonGroundRule = NonGroundRule.constructNonGroundRule(rule); knownNonGroundRules.put(nonGroundRule.getRuleId(), nonGroundRule); LOGGER.debug("NonGroundRule #" + nonGroundRule.getRuleId() + ": " + nonGroundRule); // Record defining rules for each predicate. Atom headAtom = nonGroundRule.getHeadAtom(); if (headAtom != null) { Predicate headPredicate = headAtom.getPredicate(); programAnalysis.recordDefiningRule(headPredicate, nonGroundRule); } // Create working memories for all predicates occurring in the rule for (Predicate predicate : nonGroundRule.getOccurringPredicates()) { // FIXME: this also contains interval/builtin predicates that are not needed. workingMemory.initialize(predicate); } // If the rule has fixed ground instantiations, it is not registered but grounded once like facts. if (nonGroundRule.groundingOrder.fixedInstantiation()) { fixedRules.add(nonGroundRule); continue; } // Register each starting literal at the corresponding working memory. for (Literal literal : nonGroundRule.groundingOrder.getStartingLiterals()) { registerLiteralAtWorkingMemory(literal, nonGroundRule); } } } private Set<NonGroundRule> getRulesWithUniqueHead() { // FIXME: below optimisation (adding support nogoods if there is only one rule instantiation per unique atom over the interpretation) could be done as a transformation (adding a non-ground constraint corresponding to the nogood that is generated by the grounder). // Record all unique rule heads. final Set<NonGroundRule> uniqueGroundRulePerGroundHead = new HashSet<>(); for (Map.Entry<Predicate, HashSet<NonGroundRule>> headDefiningRules : programAnalysis.getPredicateDefiningRules().entrySet()) { if (headDefiningRules.getValue().size() != 1) { continue; } NonGroundRule nonGroundRule = headDefiningRules.getValue().iterator().next(); // Check that all variables of the body also occur in the head (otherwise grounding is not unique). Atom headAtom = nonGroundRule.getHeadAtom(); // Rule is not guaranteed unique if there are facts for it. HashSet<Instance> potentialFacts = factsFromProgram.get(headAtom.getPredicate()); if (potentialFacts != null && !potentialFacts.isEmpty()) { continue; } // Collect head and body variables. HashSet<VariableTerm> occurringVariablesHead = new HashSet<>(headAtom.toLiteral().getBindingVariables()); HashSet<VariableTerm> occurringVariablesBody = new HashSet<>(); for (Atom atom : nonGroundRule.getBodyAtomsPositive()) { occurringVariablesBody.addAll(atom.toLiteral().getBindingVariables()); } occurringVariablesBody.removeAll(occurringVariablesHead); // Check if ever body variables occurs in the head. if (occurringVariablesBody.isEmpty()) { uniqueGroundRulePerGroundHead.add(nonGroundRule); } } return uniqueGroundRulePerGroundHead; } private void applyProgramTransformations(Program program) { // Transform choice rules. new ChoiceHeadToNormal().transform(program); // Transform cardinality aggregates. new CardinalityNormalization(!useCountingGridNormalization).transform(program); // Transform sum aggregates. new SumNormalization().transform(program); // Transform intervals. new IntervalTermToIntervalAtom().transform(program); // Remove variable equalities. new VariableEqualityRemoval().transform(program); // Transform enumeration atoms. new EnumerationRewriting().transform(program); EnumerationAtom.resetEnumerations(); } /** * Registers a starting literal of a NonGroundRule at its corresponding working memory. * @param nonGroundRule the rule in which the literal occurs. */ private void registerLiteralAtWorkingMemory(Literal literal, NonGroundRule nonGroundRule) { if (literal.isNegated()) { throw new RuntimeException("Literal to register is negated. Should not happen."); } IndexedInstanceStorage workingMemory = this.workingMemory.get(literal.getPredicate(), true); rulesUsingPredicateWorkingMemory.putIfAbsent(workingMemory, new ArrayList<>()); rulesUsingPredicateWorkingMemory.get(workingMemory).add(new FirstBindingAtom(nonGroundRule, literal)); } @Override public AnswerSet assignmentToAnswerSet(Iterable<Integer> trueAtoms) { Map<Predicate, SortedSet<Atom>> predicateInstances = new LinkedHashMap<>(); SortedSet<Predicate> knownPredicates = new TreeSet<>(); // Iterate over all true atomIds, computeNextAnswerSet instances from atomStore and add them if not filtered. for (int trueAtom : trueAtoms) { final Atom atom = atomStore.get(trueAtom); Predicate predicate = atom.getPredicate(); // Skip atoms over internal predicates. if (predicate.isInternal()) { continue; } // Skip filtered predicates. if (!filter.test(predicate)) { continue; } knownPredicates.add(predicate); predicateInstances.putIfAbsent(predicate, new TreeSet<>()); Set<Atom> instances = predicateInstances.get(predicate); instances.add(atom); } // Add true atoms from facts. for (Map.Entry<Predicate, LinkedHashSet<Instance>> facts : factsFromProgram.entrySet()) { Predicate factPredicate = facts.getKey(); // Skip atoms over internal predicates. if (factPredicate.isInternal()) { continue; } // Skip filtered predicates. if (!filter.test(factPredicate)) { continue; } // Skip predicates without any instances. if (facts.getValue().isEmpty()) { continue; } knownPredicates.add(factPredicate); predicateInstances.putIfAbsent(factPredicate, new TreeSet<>()); for (Instance factInstance : facts.getValue()) { SortedSet<Atom> instances = predicateInstances.get(factPredicate); instances.add(new BasicAtom(factPredicate, factInstance.terms)); } } if (knownPredicates.isEmpty()) { return BasicAnswerSet.EMPTY; } return new BasicAnswerSet(knownPredicates, predicateInstances); } /** * Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once. * @return */ private HashMap<Integer, NoGood> bootstrap() { final HashMap<Integer, NoGood> groundNogoods = new LinkedHashMap<>(); for (Predicate predicate : factsFromProgram.keySet()) { // Instead of generating NoGoods, add instance to working memories directly. workingMemory.addInstances(predicate, true, factsFromProgram.get(predicate)); } for (NonGroundRule nonGroundRule : fixedRules) { // Generate NoGoods for all rules that have a fixed grounding. RuleGroundingOrder groundingOrder = nonGroundRule.groundingOrder.getFixedGroundingOrder(); BindingResult bindingResult = bindNextAtomInRule(nonGroundRule, groundingOrder, new Substitution(), null); groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, groundNogoods); } fixedRules = null; return groundNogoods; } @Override public Map<Integer, NoGood> getNoGoods(Assignment currentAssignment) { // In first call, prepare facts and ground rules. final Map<Integer, NoGood> newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>(); // Compute new ground rule (evaluate joins with newly changed atoms) for (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) { // Skip predicates solely used in the solver which do not occur in rules. Predicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate(); if (workingMemoryPredicate.isSolverInternal()) { continue; } // Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory. final ArrayList<FirstBindingAtom> firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory); // Skip working memories that are not used by any rule. if (firstBindingAtoms == null) { continue; } for (FirstBindingAtom firstBindingAtom : firstBindingAtoms) { // Use the recently added instances from the modified working memory to construct an initial substitution NonGroundRule nonGroundRule = firstBindingAtom.rule; // Generate substitutions from each recent instance. for (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) { // Check instance if it matches with the atom. final Substitution unifier = Substitution.unify(firstBindingAtom.startingLiteral, instance, new Substitution()); if (unifier == null) { continue; } final BindingResult bindingResult = bindNextAtomInRule( nonGroundRule, nonGroundRule.groundingOrder.orderStartingFrom(firstBindingAtom.startingLiteral), unifier, currentAssignment ); groundAndRegister(nonGroundRule, bindingResult.generatedSubstitutions, newNoGoods); } } // Mark instances added by updateAssignment as done modifiedWorkingMemory.markRecentlyAddedInstancesDone(); } workingMemory.reset(); for (Atom removeAtom : removeAfterObtainingNewNoGoods) { final IndexedInstanceStorage storage = this.workingMemory.get(removeAtom, true); Instance instance = new Instance(removeAtom.getTerms()); if (storage.containsInstance(instance)) { // lax grounder heuristics may attempt to remove instances that are not yet in the working memory storage.removeInstance(instance); } } removeAfterObtainingNewNoGoods = new LinkedHashSet<>(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Grounded NoGoods are:"); for (Map.Entry<Integer, NoGood> noGoodEntry : newNoGoods.entrySet()) { LOGGER.debug("{} == {}", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue())); } LOGGER.debug("{}", choiceRecorder); } if (debugInternalChecks) { checkTypesOfNoGoods(newNoGoods.values()); } return newNoGoods; } /** * Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that process. * * @param nonGroundRule * the rule to be grounded * @param substitutions * the substitutions to be applied * @param newNoGoods * a set of nogoods to which newly generated nogoods will be added */ private void groundAndRegister(final NonGroundRule nonGroundRule, final List<Substitution> substitutions, final Map<Integer, NoGood> newNoGoods) { for (Substitution substitution : substitutions) { List<NoGood> generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution); registry.register(generatedNoGoods, newNoGoods); } } @Override public int register(NoGood noGood) { return registry.register(noGood); } private BindingResult bindNextAtomInRule(NonGroundRule rule, RuleGroundingOrder groundingOrder, Substitution partialSubstitution, Assignment currentAssignment) { int tolerance = heuristicsConfiguration.getTolerance(rule.isConstraint()); if (tolerance < 0) { tolerance = Integer.MAX_VALUE; } BindingResult bindingResult = bindNextAtomInRule(groundingOrder, 0, tolerance, tolerance, partialSubstitution, currentAssignment); if (LOGGER.isDebugEnabled()) { for (int i = 0; i < bindingResult.size(); i++) { Integer numberOfUnassignedPositiveBodyAtoms = bindingResult.numbersOfUnassignedPositiveBodyAtoms.get(i); if (numberOfUnassignedPositiveBodyAtoms > 0) { LOGGER.debug("Grounded rule in which " + numberOfUnassignedPositiveBodyAtoms + " positive atoms are still unassigned: " + rule + " (substitution: " + bindingResult.generatedSubstitutions.get(i) + ")"); } } } return bindingResult; } private BindingResult advanceAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { groundingOrder.considerUntilCurrentEnd(); return bindNextAtomInRule(groundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } private BindingResult pushBackAndBindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { RuleGroundingOrder modifiedGroundingOrder = groundingOrder.pushBack(orderPosition); if (modifiedGroundingOrder == null) { return BindingResult.empty(); } return bindNextAtomInRule(modifiedGroundingOrder, orderPosition + 1, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } private BindingResult bindNextAtomInRule(RuleGroundingOrder groundingOrder, int orderPosition, int originalTolerance, int remainingTolerance, Substitution partialSubstitution, Assignment currentAssignment) { boolean laxGrounderHeuristic = originalTolerance > 0; Literal currentLiteral = groundingOrder.getLiteralAtOrderPosition(orderPosition); if (currentLiteral == null) { return BindingResult.singleton(partialSubstitution, originalTolerance - remainingTolerance); } Atom currentAtom = currentLiteral.getAtom(); if (currentLiteral instanceof FixedInterpretationLiteral) { // Generate all substitutions for the builtin/external/interval atom. FixedInterpretationLiteral substitutedLiteral = (FixedInterpretationLiteral)currentLiteral.substitute(partialSubstitution); // TODO: this has to be improved before merging into master: if (!substitutedLiteral.isGround() && !(substitutedLiteral instanceof ComparisonLiteral && ((ComparisonLiteral)substitutedLiteral).isLeftOrRightAssigning()) && !(substitutedLiteral instanceof IntervalLiteral && substitutedLiteral.getTerms().get(0).isGround()) && !(substitutedLiteral instanceof ExternalLiteral) ) { return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } final List<Substitution> substitutions = substitutedLiteral.getSubstitutions(partialSubstitution); if (substitutions.isEmpty()) { // if FixedInterpretationLiteral cannot be satisfied now, it will never be return BindingResult.empty(); } final BindingResult bindingResult = new BindingResult(); for (Substitution substitution : substitutions) { // Continue grounding with each of the generated values. bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, substitution, currentAssignment)); } return bindingResult; } if (currentAtom instanceof EnumerationAtom) { // Get the enumeration value and add it to the current partialSubstitution. ((EnumerationAtom) currentAtom).addEnumerationToSubstitution(partialSubstitution); return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } Collection<Instance> instances = null; // check if partialVariableSubstitution already yields a ground atom final Atom substitute = currentAtom.substitute(partialSubstitution); if (substitute.isGround()) { // Substituted atom is ground, in case it is positive, only ground if it also holds true if (currentLiteral.isNegated()) { // Atom occurs negated in the rule: continue grounding return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } if (!groundingOrder.isGround() && remainingTolerance <= 0 && !workingMemory.get(currentAtom.getPredicate(), true).containsInstance(new Instance(substitute.getTerms()))) { // Generate no variable substitution. return BindingResult.empty(); } // Check if atom is also assigned true. final LinkedHashSet<Instance> factInstances = factsFromProgram.get(substitute.getPredicate()); if (factInstances != null && factInstances.contains(new Instance(substitute.getTerms()))) { // Ground literal holds, continue finding a variable substitution. return advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } // Atom is not a fact already. instances = singletonList(new Instance(substitute.getTerms())); } // substituted atom contains variables if (currentLiteral.isNegated()) { if (laxGrounderHeuristic) { return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } else { throw oops("Current atom should be positive at this point but is not"); } } if (instances == null) { IndexedInstanceStorage storage = workingMemory.get(currentAtom.getPredicate(), true); if (partialSubstitution.isEmpty()) { // No variables are bound, but first atom in the body became recently true, consider all instances now. instances = storage.getAllInstances(); } else { instances = storage.getInstancesFromPartiallyGroundAtom(substitute); } } if (laxGrounderHeuristic && instances.isEmpty()) { // we have reached a point where we have to terminate binding, // but it might be possible that a different grounding order would allow us to continue binding // under the presence of a lax grounder heuristic return pushBackAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, remainingTolerance, partialSubstitution, currentAssignment); } BindingResult bindingResult = new BindingResult(); for (Instance instance : instances) { // Check each instance if it matches with the atom. Substitution unified = Substitution.unify(substitute, instance, new Substitution(partialSubstitution)); if (unified == null) { continue; } // Check if atom is also assigned true. Atom substituteClone = new BasicAtom(substitute.getPredicate(), substitute.getTerms()); Atom substitutedAtom = substituteClone.substitute(unified); if (!substitutedAtom.isGround()) { throw oops("Grounded atom should be ground but is not"); } AtomicInteger atomicRemainingTolerance = new AtomicInteger(remainingTolerance); // TODO: done this way for call-by-reference, should be refactored if (factsFromProgram.get(substitutedAtom.getPredicate()) == null || !factsFromProgram.get(substitutedAtom.getPredicate()).contains(new Instance(substitutedAtom.getTerms()))) { if (storeAtomAndTerminateIfAtomDoesNotHold(substitutedAtom, currentAssignment, atomicRemainingTolerance)) { continue; } } bindingResult.add(advanceAndBindNextAtomInRule(groundingOrder, orderPosition, originalTolerance, atomicRemainingTolerance.get(), unified, currentAssignment)); } return bindingResult; } private boolean storeAtomAndTerminateIfAtomDoesNotHold(final Atom substitute, Assignment currentAssignment, AtomicInteger remainingTolerance) { final int atomId = atomStore.putIfAbsent(substitute); if (currentAssignment != null) { ThriceTruth truth = currentAssignment.isAssigned(atomId) ? currentAssignment.getTruth(atomId) : null; if (truth == null || !truth.toBoolean()) { // Atom currently does not hold if (!disableInstanceRemoval) { removeAfterObtainingNewNoGoods.add(substitute); } if (truth == null && remainingTolerance.decrementAndGet() < 0) { // terminate if more positive atoms are unsatisfied as tolerated by the heuristic return true; } // terminate if positive body atom is assigned false return truth != null && !truth.toBoolean(); } } return false; } @Override public Pair<Map<Integer, Integer>, Map<Integer, Integer>> getChoiceAtoms() { return choiceRecorder.getAndResetChoices(); } @Override public Map<Integer, Set<Integer>> getHeadsToBodies() { return choiceRecorder.getAndResetHeadsToBodies(); } @Override public void updateAssignment(Iterator<Integer> it) { while (it.hasNext()) { workingMemory.addInstance(atomStore.get(it.next()), true); } } @Override public void forgetAssignment(int[] atomIds) { throw new UnsupportedOperationException("Forgetting assignments is not implemented"); } public static String groundAndPrintRule(NonGroundRule rule, Substitution substitution) { StringBuilder ret = new StringBuilder(); if (!rule.isConstraint()) { Atom groundHead = rule.getHeadAtom().substitute(substitution); ret.append(groundHead.toString()); } ret.append(" :- "); boolean isFirst = true; for (Atom bodyAtom : rule.getBodyAtomsPositive()) { ret.append(groundLiteralToString(bodyAtom.toLiteral(), substitution, isFirst)); isFirst = false; } for (Atom bodyAtom : rule.getBodyAtomsNegative()) { ret.append(groundLiteralToString(bodyAtom.toLiteral(false), substitution, isFirst)); isFirst = false; } ret.append("."); return ret.toString(); } static String groundLiteralToString(Literal literal, Substitution substitution, boolean isFirst) { Literal groundLiteral = literal.substitute(substitution); return (isFirst ? "" : ", ") + groundLiteral.toString(); } @Override public NonGroundRule getNonGroundRule(Integer ruleId) { return knownNonGroundRules.get(ruleId); } @Override public boolean isFact(Atom atom) { LinkedHashSet<Instance> instances = factsFromProgram.get(atom.getPredicate()); if (instances == null) { return false; } return instances.contains(new Instance(atom.getTerms())); } @Override public Set<Literal> justifyAtom(int atomToJustify, Assignment currentAssignment) { Set<Literal> literals = analyzeUnjustified.analyze(atomToJustify, currentAssignment); // Remove facts from justification before handing it over to the solver. for (Iterator<Literal> iterator = literals.iterator(); iterator.hasNext();) { Literal literal = iterator.next(); if (literal.isNegated()) { continue; } LinkedHashSet<Instance> factsOverPredicate = factsFromProgram.get(literal.getPredicate()); if (factsOverPredicate != null && factsOverPredicate.contains(new Instance(literal.getAtom().getTerms()))) { iterator.remove(); } } return literals; } /** * Checks that every nogood not marked as {@link NoGood.Type#INTERNAL} contains only * atoms which are not {@link Predicate#isSolverInternal()} (except {@link RuleAtom}s, which are allowed). * @param newNoGoods */ private void checkTypesOfNoGoods(Collection<NoGood> newNoGoods) { for (NoGood noGood : newNoGoods) { if (noGood.getType() != Type.INTERNAL) { for (int literal : noGood) { Atom atom = atomStore.get(atomOf(literal)); if (atom.getPredicate().isSolverInternal() && !(atom instanceof RuleAtom)) { throw oops("NoGood containing atom of internal predicate " + atom + " is " + noGood.getType() + " instead of INTERNAL"); } } } } } private static class FirstBindingAtom { final NonGroundRule rule; final Literal startingLiteral; FirstBindingAtom(NonGroundRule rule, Literal startingLiteral) { this.rule = rule; this.startingLiteral = startingLiteral; } } private static class BindingResult { final List<Substitution> generatedSubstitutions = new ArrayList<>(); final List<Integer> numbersOfUnassignedPositiveBodyAtoms = new ArrayList<>(); void add(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) { this.generatedSubstitutions.add(generatedSubstitution); this.numbersOfUnassignedPositiveBodyAtoms.add(numberOfUnassignedPositiveBodyAtoms); } void add(BindingResult otherBindingResult) { this.generatedSubstitutions.addAll(otherBindingResult.generatedSubstitutions); this.numbersOfUnassignedPositiveBodyAtoms.addAll(otherBindingResult.numbersOfUnassignedPositiveBodyAtoms); } int size() { return generatedSubstitutions.size(); } static BindingResult empty() { return new BindingResult(); } static BindingResult singleton(Substitution generatedSubstitution, int numberOfUnassignedPositiveBodyAtoms) { BindingResult bindingResult = new BindingResult(); bindingResult.add(generatedSubstitution, numberOfUnassignedPositiveBodyAtoms); return bindingResult; } } }
Refactoring NaiveGrounder
src/main/java/at/ac/tuwien/kr/alpha/grounder/NaiveGrounder.java
Refactoring NaiveGrounder
Java
mit
15b5ae619cc5dd9c72a2454f1fb3e18323418420
0
intuit/karate,intuit/karate,intuit/karate,intuit/karate
/* * The MIT License * * Copyright 2020 Intuit Inc. * * 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 com.intuit.karate.core; import com.intuit.karate.EventContext; import com.intuit.karate.FileUtils; import com.intuit.karate.Json; import com.intuit.karate.JsonUtils; import com.intuit.karate.KarateException; import com.intuit.karate.Logger; import com.intuit.karate.Match; import com.intuit.karate.MatchStep; import com.intuit.karate.PerfContext; import com.intuit.karate.StringUtils; import com.intuit.karate.XmlUtils; import com.intuit.karate.graal.JsEngine; import com.intuit.karate.graal.JsLambda; import com.intuit.karate.graal.JsList; import com.intuit.karate.graal.JsMap; import com.intuit.karate.graal.JsValue; import com.intuit.karate.http.HttpClient; import com.intuit.karate.http.HttpRequest; import com.intuit.karate.http.HttpRequestBuilder; import com.intuit.karate.http.ResourceType; import com.intuit.karate.http.WebSocketClient; import com.intuit.karate.http.WebSocketOptions; import com.intuit.karate.shell.Command; import java.io.File; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.graalvm.polyglot.Value; /** * * @author pthomas3 */ public class ScenarioBridge implements PerfContext, EventContext { private final ScenarioEngine ENGINE; protected ScenarioBridge(ScenarioEngine engine) { ENGINE = engine; } public void abort() { getEngine().setAborted(true); } public Object append(Value... vals) { List list = new ArrayList(); JsList jsList = new JsList(list); if (vals.length == 0) { return jsList; } Value val = vals[0]; if (val.hasArrayElements()) { list.addAll(val.as(List.class)); } else { list.add(val.as(Object.class)); } if (vals.length == 1) { return jsList; } for (int i = 1; i < vals.length; i++) { Value v = vals[i]; if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { list.add(v.as(Object.class)); } } return jsList; } private Object appendToInternal(String varName, Value... vals) { ScenarioEngine engine = getEngine(); Variable var = engine.vars.get(varName); if (!var.isList()) { return null; } List list = var.getValue(); for (Value v : vals) { if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { Object temp = v.as(Object.class); list.add(temp); } } engine.setVariable(varName, list); return new JsList(list); } public Object appendTo(Value ref, Value... vals) { if (ref.isString()) { return appendToInternal(ref.asString(), vals); } List list; if (ref.hasArrayElements()) { list = new JsValue(ref).getAsList(); // make sure we unwrap the "original" list } else { list = new ArrayList(); } for (Value v : vals) { if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { Object temp = v.as(Object.class); list.add(temp); } } return new JsList(list); } public Object call(String fileName) { return call(false, fileName, null); } public Object call(String fileName, Value arg) { return call(false, fileName, arg); } public Object call(boolean sharedScope, String fileName) { return call(sharedScope, fileName, null); } public Object call(boolean sharedScope, String fileName, Value arg) { ScenarioEngine engine = getEngine(); Variable called = new Variable(engine.fileReader.readFile(fileName)); Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope); return JsValue.fromJava(result.getValue()); } private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception { if (o instanceof Exception) { engine.logger.warn("callSingle() cached result is an exception"); throw (Exception) o; } // if we don't clone, an attach operation would update the tree within the cached value // causing future cache hit + attach attempts to fail ! o = engine.recurseAndAttachAndShallowClone(o); return JsValue.fromJava(o); } public Object callSingle(String fileName) throws Exception { return callSingle(fileName, null); } public Object callSingle(String fileName, Value arg) throws Exception { ScenarioEngine engine = getEngine(); final Map<String, Object> CACHE = engine.runtime.featureRuntime.suite.callSingleCache; if (CACHE.containsKey(fileName)) { engine.logger.trace("callSingle cache hit: {}", fileName); return callSingleResult(engine, CACHE.get(fileName)); } long startTime = System.currentTimeMillis(); engine.logger.trace("callSingle waiting for lock: {}", fileName); synchronized (CACHE) { // lock if (CACHE.containsKey(fileName)) { // retry long endTime = System.currentTimeMillis() - startTime; engine.logger.warn("this thread waited {} milliseconds for callSingle lock: {}", endTime, fileName); return callSingleResult(engine, CACHE.get(fileName)); } // this thread is the 'winner' engine.logger.info(">> lock acquired, begin callSingle: {}", fileName); int minutes = engine.getConfig().getCallSingleCacheMinutes(); Object result = null; File cacheFile = null; if (minutes > 0) { String cleanedName = StringUtils.toIdString(fileName); String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + ".txt"; cacheFile = new File(cacheFileName); long since = System.currentTimeMillis() - minutes * 60 * 1000; if (cacheFile.exists()) { long lastModified = cacheFile.lastModified(); if (lastModified > since) { String json = FileUtils.toString(cacheFile); result = JsonUtils.fromJson(json); engine.logger.info("callSingleCache hit: {}", cacheFile); } else { engine.logger.info("callSingleCache stale, last modified {} - is before {} (minutes: {})", lastModified, since, minutes); } } else { engine.logger.info("callSingleCache file does not exist, will create: {}", cacheFile); } } if (result == null) { Variable called = new Variable(read(fileName)); Variable argVar; if (arg == null || arg.isNull()) { argVar = null; } else { argVar = new Variable(arg); } Variable resultVar; try { resultVar = engine.call(called, argVar, false); } catch (Exception e) { // don't retain any vestiges of graal-js RuntimeException re = new RuntimeException(e.getMessage()); // we do this so that an exception is also "cached" resultVar = new Variable(re); // will be thrown at end engine.logger.warn("callSingle() will cache an exception"); } if (minutes > 0) { // cacheFile will be not null if (resultVar.isMapOrList()) { String json = resultVar.getAsString(); FileUtils.writeToFile(cacheFile, json); engine.logger.info("callSingleCache write: {}", cacheFile); } else { engine.logger.warn("callSingleCache write failed, not json-like: {}", resultVar); } } // functions have to be detached so that they can be re-hydrated in another js context result = engine.recurseAndDetachAndShallowClone(resultVar.getValue()); } CACHE.put(fileName, result); engine.logger.info("<< lock released, cached callSingle: {}", fileName); return callSingleResult(engine, result); } } public Object callonce(String path) { return callonce(false, path); } public Object callonce(boolean sharedScope, String path) { String exp = "read('" + path + "')"; Variable v = getEngine().call(true, exp, sharedScope); return JsValue.fromJava(v.getValue()); } @Override public void capturePerfEvent(String name, long startTime, long endTime) { PerfEvent event = new PerfEvent(startTime, endTime, name, 200); getEngine().capturePerfEvent(event); } public void configure(String key, Value value) { getEngine().configure(key, new Variable(value)); } public Object distinct(Value o) { if (!o.hasArrayElements()) { return JsList.EMPTY; } long count = o.getArraySize(); Set<Object> set = new LinkedHashSet(); for (int i = 0; i < count; i++) { Object value = JsValue.toJava(o.getArrayElement(i)); set.add(value); } return JsValue.fromJava(new ArrayList(set)); } public String doc(Value v) { Map<String, Object> arg; if (v.isString()) { arg = Collections.singletonMap("read", v.asString()); } else if (v.hasMembers()) { arg = new JsValue(v).getAsMap(); } else { getEngine().logger.warn("doc - unexpected argument: {}", v); return null; } return getEngine().docInternal(arg); } public void embed(Object o, String contentType) { ResourceType resourceType; if (contentType == null) { resourceType = ResourceType.fromObject(o, ResourceType.BINARY); } else { resourceType = ResourceType.fromContentType(contentType); } getEngine().runtime.embed(JsValue.toBytes(o), resourceType); } public Object eval(String exp) { Variable result = getEngine().evalJs(exp); return JsValue.fromJava(result.getValue()); } public String exec(Value value) { if (value.isString()) { return execInternal(Collections.singletonMap("line", value.asString())); } else if (value.hasArrayElements()) { List args = new JsValue(value).getAsList(); return execInternal(Collections.singletonMap("args", args)); } else { return execInternal(new JsValue(value).getAsMap()); } } private String execInternal(Map<String, Object> options) { Command command = getEngine().fork(false, options); command.waitSync(); return command.getAppender().collect(); } public String extract(String text, String regex, int group) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (!matcher.find()) { getEngine().logger.warn("failed to find pattern: {}", regex); return null; } return matcher.group(group); } public List<String> extractAll(String text, String regex, int group) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); List<String> list = new ArrayList(); while (matcher.find()) { list.add(matcher.group(group)); } return list; } public void fail(String reason) { getEngine().setFailedReason(new KarateException(reason)); } public Object filter(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); Value res = JsEngine.execute(f, v, i); if (res.isBoolean() && res.asBoolean()) { list.add(new JsValue(v).getValue()); } } return new JsList(list); } public Object filterKeys(Value o, Value... args) { if (!o.hasMembers() || args.length == 0) { return JsMap.EMPTY; } List<String> keys = new ArrayList(); if (args.length == 1) { if (args[0].isString()) { keys.add(args[0].asString()); } else if (args[0].hasArrayElements()) { long count = args[0].getArraySize(); for (int i = 0; i < count; i++) { keys.add(args[0].getArrayElement(i).toString()); } } else if (args[0].hasMembers()) { for (String s : args[0].getMemberKeys()) { keys.add(s); } } } else { for (Value v : args) { keys.add(v.toString()); } } Map map = new LinkedHashMap(keys.size()); for (String key : keys) { if (key == null) { continue; } Value v = o.getMember(key); if (v != null) { map.put(key, v.as(Object.class)); } } return new JsMap(map); } public void forEach(Value o, Value f) { assertIfJsFunction(f); if (o.hasArrayElements()) { long count = o.getArraySize(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); f.executeVoid(v, i); } } else if (o.hasMembers()) { //map int i = 0; for (String k : o.getMemberKeys()) { Value v = o.getMember(k); f.executeVoid(k, v, i++); } } else { throw new RuntimeException("not an array or object: " + o); } } public Command fork(Value value) { if (value.isString()) { return getEngine().fork(true, value.asString()); } else if (value.hasArrayElements()) { List args = new JsValue(value).getAsList(); return getEngine().fork(true, args); } else { return getEngine().fork(true, new JsValue(value).getAsMap()); } } // TODO breaking returns actual object not wrapper // and fromObject() has been removed // use new typeOf() method to find type public Object fromString(String exp) { ScenarioEngine engine = getEngine(); try { Variable result = engine.evalKarateExpression(exp); return JsValue.fromJava(result.getValue()); } catch (Exception e) { engine.setFailedReason(null); // special case engine.logger.warn("auto evaluation failed: {}", e.getMessage()); return exp; } } public Object get(String exp) { ScenarioEngine engine = getEngine(); Variable v; try { v = engine.evalKarateExpression(exp); // even json path expressions will work } catch (Exception e) { engine.logger.trace("karate.get failed for expression: '{}': {}", exp, e.getMessage()); engine.setFailedReason(null); // special case ! return null; } if (v != null) { return JsValue.fromJava(v.getValue()); } else { return null; } } public Object get(String exp, Object defaultValue) { Object result = get(exp); return result == null ? defaultValue : result; } // getters ================================================================= // TODO migrate these to functions not properties // public ScenarioEngine getEngine() { ScenarioEngine engine = ScenarioEngine.get(); return engine == null ? ENGINE : engine; } public String getEnv() { return getEngine().runtime.featureRuntime.suite.env; } public Object getFeature() { return new JsMap(getEngine().runtime.featureRuntime.result.toInfoJson()); } public Object getInfo() { // TODO deprecate return new JsMap(getEngine().runtime.getScenarioInfo()); } private LogFacade logFacade; public Object getLogger() { if (logFacade == null) { logFacade = new LogFacade(); } return logFacade; } public Object getOs() { String name = FileUtils.getOsName(); String type = FileUtils.getOsType(name).toString().toLowerCase(); Map<String, Object> map = new HashMap(2); map.put("name", name); map.put("type", type); return new JsMap(map); } // TODO breaking uri has been renamed to url public Object getPrevRequest() { HttpRequest hr = getEngine().getRequest(); if (hr == null) { return null; } Map<String, Object> map = new HashMap(); map.put("method", hr.getMethod()); map.put("url", hr.getUrl()); map.put("headers", hr.getHeaders()); map.put("body", hr.getBody()); return JsValue.fromJava(map); } public Object getProperties() { return new JsMap(getEngine().runtime.featureRuntime.suite.systemProperties); } public Object getScenario() { return new JsMap(getEngine().runtime.result.toKarateJson()); } public Object getTags() { return JsValue.fromJava(getEngine().runtime.tags.getTags()); } public Object getTagValues() { return JsValue.fromJava(getEngine().runtime.tags.getTagValues()); } //========================================================================== // public HttpRequestBuilder http(String url) { ScenarioEngine engine = getEngine(); HttpClient client = engine.runtime.featureRuntime.suite.clientFactory.create(engine); return new HttpRequestBuilder(client).url(url); } public Object jsonPath(Object o, String exp) { Json json = Json.of(o); return JsValue.fromJava(json.get(exp)); } public Object keysOf(Value o) { return new JsList(o.getMemberKeys()); } public void log(Value... values) { ScenarioEngine engine = getEngine(); if (engine.getConfig().isPrintEnabled()) { engine.logger.info("{}", new LogWrapper(values)); } } public Object lowerCase(Object o) { Variable var = new Variable(o); return JsValue.fromJava(var.toLowerCase().getValue()); } public Object map(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); Value res = JsEngine.execute(f, v, i); list.add(new JsValue(res).getValue()); } return new JsList(list); } public Object mapWithKey(Value v, String key) { if (!v.hasArrayElements()) { return JsList.EMPTY; } long count = v.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Map map = new LinkedHashMap(); Value res = v.getArrayElement(i); map.put(key, res.as(Object.class)); list.add(map); } return new JsList(list); } public Object match(Object actual, Object expected) { Match.Result mr = getEngine().match(Match.Type.EQUALS, actual, expected); return JsValue.fromJava(mr.toMap()); } public Object match(String exp) { MatchStep ms = new MatchStep(exp); Match.Result mr = getEngine().match(ms.type, ms.name, ms.path, ms.expected); return JsValue.fromJava(mr.toMap()); } public Object merge(Value... vals) { if (vals.length == 0) { return null; } if (vals.length == 1) { return vals[0]; } Map map = new HashMap(vals[0].as(Map.class)); for (int i = 1; i < vals.length; i++) { map.putAll(vals[i].as(Map.class)); } return new JsMap(map); } public void pause(Value value) { ScenarioEngine engine = getEngine(); if (!value.isNumber()) { engine.logger.warn("pause argument is not a number:", value); return; } if (engine.runtime.perfMode) { engine.runtime.featureRuntime.perfHook.pause(value.asInt()); } else if (engine.getConfig().isPauseIfNotPerf()) { try { Thread.sleep(value.asInt()); } catch (Exception e) { throw new RuntimeException(e); } } } public String pretty(Object o) { Variable v = new Variable(o); return v.getAsPrettyString(); } public String prettyXml(Object o) { Variable v = new Variable(o); return v.getAsPrettyXmlString(); } public void proceed() { proceed(null); } public void proceed(String requestUrlBase) { getEngine().mockProceed(requestUrlBase); } public Object range(int start, int end) { return range(start, end, 1); } public Object range(int start, int end, int interval) { if (interval <= 0) { throw new RuntimeException("interval must be a positive integer"); } List<Integer> list = new ArrayList(); if (start <= end) { for (int i = start; i <= end; i += interval) { list.add(i); } } else { for (int i = start; i >= end; i -= interval) { list.add(i); } } return JsValue.fromJava(list); } public Object read(String name) { Object result = getEngine().fileReader.readFile(name); return JsValue.fromJava(result); } public String readAsString(String fileName) { return getEngine().fileReader.readFileAsString(fileName); } public void remove(String name, String path) { getEngine().remove(name, path); } public Object repeat(int n, Value f) { assertIfJsFunction(f); List list = new ArrayList(n); for (int i = 0; i < n; i++) { Value v = JsEngine.execute(f, i); list.add(new JsValue(v).getValue()); } return new JsList(list); } // set multiple variables in one shot public void set(Map<String, Object> map) { getEngine().setVariables(map); } public void set(String name, Value value) { getEngine().setVariable(name, new Variable(value)); } // this makes sense mainly for xpath manipulation from within js public void set(String name, String path, Object value) { getEngine().set(name, path, new Variable(value)); } public void setXml(String name, String xml) { getEngine().setVariable(name, XmlUtils.toXmlDoc(xml)); } // this makes sense mainly for xpath manipulation from within js public void setXml(String name, String path, String xml) { getEngine().set(name, path, new Variable(XmlUtils.toXmlDoc(xml))); } @Override public void signal(Object o) { Value v = Value.asValue(o); getEngine().signal(JsValue.toJava(v)); } public Object sizeOf(Value v) { if (v.hasArrayElements()) { return v.getArraySize(); } else if (v.hasMembers()) { return v.getMemberKeys().size(); } else { return -1; } } public Object sort(Value o) { return sort(o, getEngine().JS.evalForValue("x => x")); } public Object sort(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); Map<Object, Object> map = new TreeMap(); for (int i = 0; i < count; i++) { Object item = JsValue.toJava(o.getArrayElement(i)); Value key = JsEngine.execute(f, item, i); if (key.isNumber()) { map.put(key.as(Number.class), item); } else { map.put(key.asString(), item); } } return JsValue.fromJava(new ArrayList(map.values())); } public MockServer start(Value value) { if (value.isString()) { return startInternal(Collections.singletonMap("mock", value.asString())); } else { return startInternal(new JsValue(value).getAsMap()); } } private MockServer startInternal(Map<String, Object> config) { String mock = (String) config.get("mock"); if (mock == null) { throw new RuntimeException("'mock' is missing: " + config); } File feature = toJavaFile(mock); MockServer.Builder builder = MockServer.feature(feature); String certFile = (String) config.get("cert"); if (certFile != null) { builder.certFile(toJavaFile(certFile)); } String keyFile = (String) config.get("key"); if (keyFile != null) { builder.keyFile(toJavaFile(keyFile)); } Boolean ssl = (Boolean) config.get("ssl"); if (ssl == null) { ssl = false; } Integer port = (Integer) config.get("port"); if (port == null) { port = 0; } Map<String, Object> arg = (Map) config.get("arg"); builder.args(arg); if (ssl) { builder.https(port); } else { builder.http(port); } return builder.build(); } public void stop(int port) { Command.waitForSocket(port); } public String toAbsolutePath(String relativePath) { return getEngine().fileReader.toAbsolutePath(relativePath); } public Object toBean(Object o, String className) { Json json = Json.of(o); Object bean = JsonUtils.fromJson(json.toString(), className); return JsValue.fromJava(bean); } public String toCsv(Object o) { Variable v = new Variable(o); if (!v.isList()) { throw new RuntimeException("not a json array: " + v); } List<Map<String, Object>> list = v.getValue(); return JsonUtils.toCsv(list); } public Object toJava(Value value) { if (value.canExecute()) { JsEngine copy = getEngine().JS.copy(); return new JsLambda(copy.attach(value)); } else { return new JsValue(value).getValue(); } } private File toJavaFile(String path) { return getEngine().fileReader.toResource(path).getFile(); } public Object toJson(Value value) { return toJson(value, false); } public Object toJson(Value value, boolean removeNulls) { JsValue jv = new JsValue(value); String json = JsonUtils.toJson(jv.getValue()); Object result = Json.of(json).value(); if (removeNulls) { JsonUtils.removeKeysWithNullValues(result); } return JsValue.fromJava(result); } // TODO deprecate public Object toList(Value value) { return new JsValue(value).getValue(); } // TODO deprecate public Object toMap(Value value) { return new JsValue(value).getValue(); } public String toString(Object o) { Variable v = new Variable(o); return v.getAsString(); } public String trim(String s) { return s == null ? null : s.trim(); } public String typeOf(Value value) { Variable v = new Variable(value); return v.getTypeString(); } public String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (Exception e) { getEngine().logger.warn("url encode failed: {}", e.getMessage()); return s; } } public String urlDecode(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (Exception e) { getEngine().logger.warn("url encode failed: {}", e.getMessage()); return s; } } public Object valuesOf(Value v) { if (v.hasArrayElements()) { return v; } else if (v.hasMembers()) { List list = new ArrayList(); for (String k : v.getMemberKeys()) { Value res = v.getMember(k); list.add(res.as(Object.class)); } return new JsList(list); } else { return null; } } public boolean waitForHttp(String url) { return Command.waitForHttp(url); } public boolean waitForPort(String host, int port) { return new Command().waitForPort(host, port); } public WebSocketClient webSocket(String url) { return webSocket(url, null, null); } public WebSocketClient webSocket(String url, Value value) { return webSocket(url, value, null); } public WebSocketClient webSocket(String url, Value listener, Value value) { Function<String, Boolean> handler; ScenarioEngine engine = getEngine(); if (listener == null || !listener.canExecute()) { handler = m -> true; } else { JsEngine copy = engine.JS.copy(); handler = new JsLambda(copy.attach(listener)); } WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue()); options.setTextHandler(handler); return engine.webSocket(options); } public WebSocketClient webSocketBinary(String url) { return webSocketBinary(url, null, null); } public WebSocketClient webSocketBinary(String url, Value value) { return webSocketBinary(url, value, null); } public WebSocketClient webSocketBinary(String url, Value listener, Value value) { Function<byte[], Boolean> handler; ScenarioEngine engine = getEngine(); if (listener == null || !listener.canExecute()) { handler = m -> true; } else { JsEngine copy = engine.JS.copy(); handler = new JsLambda(copy.attach(listener)); } WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue()); options.setBinaryHandler(handler); return engine.webSocket(options); } public File write(Object o, String path) { ScenarioEngine engine = getEngine(); path = engine.runtime.featureRuntime.suite.buildDir + File.separator + path; File file = new File(path); FileUtils.writeToFile(file, JsValue.toBytes(o)); engine.logger.debug("write to file: {}", file); return file; } public Object xmlPath(Object o, String path) { Variable var = new Variable(o); Variable res = ScenarioEngine.evalXmlPath(var, path); return JsValue.fromJava(res.getValue()); } // helpers ================================================================= // private static void assertIfJsFunction(Value f) { if (!f.canExecute()) { throw new RuntimeException("not a js function: " + f); } } // make sure log() toString() is lazy static class LogWrapper { final Value[] values; LogWrapper(Value... values) { // sometimes a null array gets passed in, graal weirdness this.values = values == null ? new Value[0] : values; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Value v : values) { Variable var = new Variable(v); sb.append(var.getAsPrettyString()).append(' '); } return sb.toString(); } } public static class LogFacade { private static Logger getLogger() { return ScenarioEngine.get().logger; } private static String wrap(Value... values) { return new LogWrapper(values).toString(); } public void debug(Value... values) { getLogger().debug(wrap(values)); } public void info(Value... values) { getLogger().info(wrap(values)); } public void trace(Value... values) { getLogger().trace(wrap(values)); } public void warn(Value... values) { getLogger().warn(wrap(values)); } public void error(Value... values) { getLogger().error(wrap(values)); } } }
karate-core/src/main/java/com/intuit/karate/core/ScenarioBridge.java
/* * The MIT License * * Copyright 2020 Intuit Inc. * * 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 com.intuit.karate.core; import com.intuit.karate.EventContext; import com.intuit.karate.FileUtils; import com.intuit.karate.Json; import com.intuit.karate.JsonUtils; import com.intuit.karate.KarateException; import com.intuit.karate.Logger; import com.intuit.karate.Match; import com.intuit.karate.MatchStep; import com.intuit.karate.PerfContext; import com.intuit.karate.StringUtils; import com.intuit.karate.XmlUtils; import com.intuit.karate.graal.JsEngine; import com.intuit.karate.graal.JsLambda; import com.intuit.karate.graal.JsList; import com.intuit.karate.graal.JsMap; import com.intuit.karate.graal.JsValue; import com.intuit.karate.http.HttpClient; import com.intuit.karate.http.HttpRequest; import com.intuit.karate.http.HttpRequestBuilder; import com.intuit.karate.http.ResourceType; import com.intuit.karate.http.WebSocketClient; import com.intuit.karate.http.WebSocketOptions; import com.intuit.karate.shell.Command; import java.io.File; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.graalvm.polyglot.Value; /** * * @author pthomas3 */ public class ScenarioBridge implements PerfContext, EventContext { private final ScenarioEngine ENGINE; protected ScenarioBridge(ScenarioEngine engine) { ENGINE = engine; } public void abort() { getEngine().setAborted(true); } public Object append(Value... vals) { List list = new ArrayList(); JsList jsList = new JsList(list); if (vals.length == 0) { return jsList; } Value val = vals[0]; if (val.hasArrayElements()) { list.addAll(val.as(List.class)); } else { list.add(val.as(Object.class)); } if (vals.length == 1) { return jsList; } for (int i = 1; i < vals.length; i++) { Value v = vals[i]; if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { list.add(v.as(Object.class)); } } return jsList; } private Object appendToInternal(String varName, Value... vals) { ScenarioEngine engine = getEngine(); Variable var = engine.vars.get(varName); if (!var.isList()) { return null; } List list = var.getValue(); for (Value v : vals) { if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { Object temp = v.as(Object.class); list.add(temp); } } engine.setVariable(varName, list); return new JsList(list); } public Object appendTo(Value ref, Value... vals) { if (ref.isString()) { return appendToInternal(ref.asString(), vals); } List list; if (ref.hasArrayElements()) { list = new JsValue(ref).getAsList(); // make sure we unwrap the "original" list } else { list = new ArrayList(); } for (Value v : vals) { if (v.hasArrayElements()) { list.addAll(v.as(List.class)); } else { Object temp = v.as(Object.class); list.add(temp); } } return new JsList(list); } public Object call(String fileName) { return call(false, fileName, null); } public Object call(String fileName, Value arg) { return call(false, fileName, arg); } public Object call(boolean sharedScope, String fileName) { return call(sharedScope, fileName, null); } public Object call(boolean sharedScope, String fileName, Value arg) { ScenarioEngine engine = getEngine(); Variable called = new Variable(engine.fileReader.readFile(fileName)); Variable result = engine.call(called, arg == null ? null : new Variable(arg), sharedScope); return JsValue.fromJava(result.getValue()); } private static Object callSingleResult(ScenarioEngine engine, Object o) throws Exception { if (o instanceof Exception) { engine.logger.warn("callSingle() cached result is an exception"); throw (Exception) o; } // if we don't clone, an attach operation would update the tree within the cached value // causing future cache hit + attach attempts to fail ! o = engine.recurseAndAttachAndShallowClone(o); return JsValue.fromJava(o); } public Object callSingle(String fileName) throws Exception { return callSingle(fileName, null); } public Object callSingle(String fileName, Value arg) throws Exception { ScenarioEngine engine = getEngine(); final Map<String, Object> CACHE = engine.runtime.featureRuntime.suite.callSingleCache; if (CACHE.containsKey(fileName)) { engine.logger.trace("callSingle cache hit: {}", fileName); return callSingleResult(engine, CACHE.get(fileName)); } long startTime = System.currentTimeMillis(); engine.logger.trace("callSingle waiting for lock: {}", fileName); synchronized (CACHE) { // lock if (CACHE.containsKey(fileName)) { // retry long endTime = System.currentTimeMillis() - startTime; engine.logger.warn("this thread waited {} milliseconds for callSingle lock: {}", endTime, fileName); return callSingleResult(engine, CACHE.get(fileName)); } // this thread is the 'winner' engine.logger.info(">> lock acquired, begin callSingle: {}", fileName); int minutes = engine.getConfig().getCallSingleCacheMinutes(); Object result = null; File cacheFile = null; if (minutes > 0) { String cleanedName = StringUtils.toIdString(fileName); String cacheFileName = engine.getConfig().getCallSingleCacheDir() + File.separator + cleanedName + ".txt"; cacheFile = new File(cacheFileName); long since = System.currentTimeMillis() - minutes * 60 * 1000; if (cacheFile.exists()) { long lastModified = cacheFile.lastModified(); if (lastModified > since) { String json = FileUtils.toString(cacheFile); result = JsonUtils.fromJson(json); engine.logger.info("callSingleCache hit: {}", cacheFile); } else { engine.logger.info("callSingleCache stale, last modified {} - is before {} (minutes: {})", lastModified, since, minutes); } } else { engine.logger.info("callSingleCache file does not exist, will create: {}", cacheFile); } } if (result == null) { Variable called = new Variable(read(fileName)); Variable argVar; if (arg == null || arg.isNull()) { argVar = null; } else { argVar = new Variable(arg); } Variable resultVar; try { resultVar = engine.call(called, argVar, false); } catch (Exception e) { // don't retain any vestiges of graal-js RuntimeException re = new RuntimeException(e.getMessage()); // we do this so that an exception is also "cached" resultVar = new Variable(re); // will be thrown at end engine.logger.warn("callSingle() will cache an exception"); } if (minutes > 0) { // cacheFile will be not null if (resultVar.isMapOrList()) { String json = resultVar.getAsString(); FileUtils.writeToFile(cacheFile, json); engine.logger.info("callSingleCache write: {}", cacheFile); } else { engine.logger.warn("callSingleCache write failed, not json-like: {}", resultVar); } } // functions have to be detached so that they can be re-hydrated in another js context result = engine.recurseAndDetachAndShallowClone(resultVar.getValue()); } CACHE.put(fileName, result); engine.logger.info("<< lock released, cached callSingle: {}", fileName); return callSingleResult(engine, result); } } public Object callonce(String path) { return callonce(false, path); } public Object callonce(boolean sharedScope, String path) { String exp = "read('" + path + "')"; Variable v = getEngine().call(true, exp, sharedScope); return JsValue.fromJava(v.getValue()); } @Override public void capturePerfEvent(String name, long startTime, long endTime) { PerfEvent event = new PerfEvent(startTime, endTime, name, 200); getEngine().capturePerfEvent(event); } public void configure(String key, Value value) { getEngine().configure(key, new Variable(value)); } public Object distinct(Value o) { if (!o.hasArrayElements()) { return JsList.EMPTY; } long count = o.getArraySize(); Set<Object> set = new LinkedHashSet(); for (int i = 0; i < count; i++) { Object value = JsValue.toJava(o.getArrayElement(i)); set.add(value); } return JsValue.fromJava(new ArrayList(set)); } public String doc(Value v) { Map<String, Object> arg; if (v.isString()) { arg = Collections.singletonMap("read", v.asString()); } else if (v.hasMembers()) { arg = new JsValue(v).getAsMap(); } else { getEngine().logger.warn("doc - unexpected argument: {}", v); return null; } return getEngine().docInternal(arg); } public void embed(Object o, String contentType) { ResourceType resourceType; if (contentType == null) { resourceType = ResourceType.fromObject(o, ResourceType.BINARY); } else { resourceType = ResourceType.fromContentType(contentType); } getEngine().runtime.embed(JsValue.toBytes(o), resourceType); } public Object eval(String exp) { Variable result = getEngine().evalJs(exp); return JsValue.fromJava(result.getValue()); } public String exec(Value value) { if (value.isString()) { return execInternal(Collections.singletonMap("line", value.asString())); } else if (value.hasArrayElements()) { List args = new JsValue(value).getAsList(); return execInternal(Collections.singletonMap("args", args)); } else { return execInternal(new JsValue(value).getAsMap()); } } private String execInternal(Map<String, Object> options) { Command command = getEngine().fork(false, options); command.waitSync(); return command.getAppender().collect(); } public String extract(String text, String regex, int group) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (!matcher.find()) { getEngine().logger.warn("failed to find pattern: {}", regex); return null; } return matcher.group(group); } public List<String> extractAll(String text, String regex, int group) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); List<String> list = new ArrayList(); while (matcher.find()) { list.add(matcher.group(group)); } return list; } public void fail(String reason) { getEngine().setFailedReason(new KarateException(reason)); } public Object filter(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); Value res = JsEngine.execute(f, v, i); if (res.isBoolean() && res.asBoolean()) { list.add(new JsValue(v).getValue()); } } return new JsList(list); } public Object filterKeys(Value o, Value... args) { if (!o.hasMembers() || args.length == 0) { return JsMap.EMPTY; } List<String> keys = new ArrayList(); if (args.length == 1) { if (args[0].isString()) { keys.add(args[0].asString()); } else if (args[0].hasArrayElements()) { long count = args[0].getArraySize(); for (int i = 0; i < count; i++) { keys.add(args[0].getArrayElement(i).toString()); } } else if (args[0].hasMembers()) { for (String s : args[0].getMemberKeys()) { keys.add(s); } } } else { for (Value v : args) { keys.add(v.toString()); } } Map map = new LinkedHashMap(keys.size()); for (String key : keys) { if (key == null) { continue; } Value v = o.getMember(key); if (v != null) { map.put(key, v.as(Object.class)); } } return new JsMap(map); } public void forEach(Value o, Value f) { assertIfJsFunction(f); if (o.hasArrayElements()) { long count = o.getArraySize(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); f.executeVoid(v, i); } } else if (o.hasMembers()) { //map int i = 0; for (String k : o.getMemberKeys()) { Value v = o.getMember(k); f.executeVoid(k, v, i++); } } else { throw new RuntimeException("not an array or object: " + o); } } public Command fork(Value value) { if (value.isString()) { return getEngine().fork(true, value.asString()); } else if (value.hasArrayElements()) { List args = new JsValue(value).getAsList(); return getEngine().fork(true, args); } else { return getEngine().fork(true, new JsValue(value).getAsMap()); } } // TODO breaking returns actual object not wrapper // and fromObject() has been removed // use new typeOf() method to find type public Object fromString(String exp) { ScenarioEngine engine = getEngine(); try { Variable result = engine.evalKarateExpression(exp); return JsValue.fromJava(result.getValue()); } catch (Exception e) { engine.setFailedReason(null); // special case engine.logger.warn("auto evaluation failed: {}", e.getMessage()); return exp; } } public Object get(String exp) { ScenarioEngine engine = getEngine(); Variable v; try { v = engine.evalKarateExpression(exp); // even json path expressions will work } catch (Exception e) { engine.logger.trace("karate.get failed for expression: '{}': {}", exp, e.getMessage()); engine.setFailedReason(null); // special case ! return null; } if (v != null) { return JsValue.fromJava(v.getValue()); } else { return null; } } public Object get(String exp, Object defaultValue) { Object result = get(exp); return result == null ? defaultValue : result; } // getters ================================================================= // TODO migrate these to functions not properties // public ScenarioEngine getEngine() { ScenarioEngine engine = ScenarioEngine.get(); return engine == null ? ENGINE : engine; } public String getEnv() { return getEngine().runtime.featureRuntime.suite.env; } public Object getFeature() { return new JsMap(getEngine().runtime.featureRuntime.result.toInfoJson()); } public Object getInfo() { // TODO deprecate return new JsMap(getEngine().runtime.getScenarioInfo()); } private LogFacade logFacade; public Object getLogger() { if (logFacade == null) { logFacade = new LogFacade(); } return logFacade; } public Object getOs() { String name = FileUtils.getOsName(); String type = FileUtils.getOsType(name).toString().toLowerCase(); Map<String, Object> map = new HashMap(2); map.put("name", name); map.put("type", type); return new JsMap(map); } // TODO breaking uri has been renamed to url public Object getPrevRequest() { HttpRequest hr = getEngine().getRequest(); if (hr == null) { return null; } Map<String, Object> map = new HashMap(); map.put("method", hr.getMethod()); map.put("url", hr.getUrl()); map.put("headers", hr.getHeaders()); map.put("body", hr.getBody()); return JsValue.fromJava(map); } public Object getProperties() { return new JsMap(getEngine().runtime.featureRuntime.suite.systemProperties); } public Object getScenario() { return new JsMap(getEngine().runtime.result.toKarateJson()); } public Object getTags() { return JsValue.fromJava(getEngine().runtime.tags.getTags()); } public Object getTagValues() { return JsValue.fromJava(getEngine().runtime.tags.getTagValues()); } //========================================================================== // public HttpRequestBuilder http(String url) { ScenarioEngine engine = getEngine(); HttpClient client = engine.runtime.featureRuntime.suite.clientFactory.create(engine); return new HttpRequestBuilder(client).url(url); } public Object jsonPath(Object o, String exp) { Json json = Json.of(o); return JsValue.fromJava(json.get(exp)); } public Object keysOf(Value o) { return new JsList(o.getMemberKeys()); } public void log(Value... values) { ScenarioEngine engine = getEngine(); if (engine.getConfig().isPrintEnabled()) { engine.logger.info("{}", new LogWrapper(values)); } } public Object lowerCase(Object o) { Variable var = new Variable(o); return JsValue.fromJava(var.toLowerCase().getValue()); } public Object map(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Value v = o.getArrayElement(i); Value res = JsEngine.execute(f, v, i); list.add(new JsValue(res).getValue()); } return new JsList(list); } public Object mapWithKey(Value v, String key) { if (!v.hasArrayElements()) { return JsList.EMPTY; } long count = v.getArraySize(); List list = new ArrayList(); for (int i = 0; i < count; i++) { Map map = new LinkedHashMap(); Value res = v.getArrayElement(i); map.put(key, res.as(Object.class)); list.add(map); } return new JsList(list); } public Object match(Object actual, Object expected) { Match.Result mr = getEngine().match(Match.Type.EQUALS, actual, expected); return JsValue.fromJava(mr.toMap()); } public Object match(String exp) { MatchStep ms = new MatchStep(exp); Match.Result mr = getEngine().match(ms.type, ms.name, ms.path, ms.expected); return JsValue.fromJava(mr.toMap()); } public Object merge(Value... vals) { if (vals.length == 0) { return null; } if (vals.length == 1) { return vals[0]; } Map map = new HashMap(vals[0].as(Map.class)); for (int i = 1; i < vals.length; i++) { map.putAll(vals[i].as(Map.class)); } return new JsMap(map); } public void pause(Value value) { ScenarioEngine engine = getEngine(); if (!value.isNumber()) { engine.logger.warn("pause argument is not a number:", value); return; } if (engine.runtime.perfMode) { engine.runtime.featureRuntime.perfHook.pause(value.asInt()); } else if (engine.getConfig().isPauseIfNotPerf()) { try { Thread.sleep(value.asInt()); } catch (Exception e) { throw new RuntimeException(e); } } } public String pretty(Object o) { Variable v = new Variable(o); return v.getAsPrettyString(); } public String prettyXml(Object o) { Variable v = new Variable(o); return v.getAsPrettyXmlString(); } public void proceed() { proceed(null); } public void proceed(String requestUrlBase) { getEngine().mockProceed(requestUrlBase); } public Object range(int start, int end) { return range(start, end, 1); } public Object range(int start, int end, int interval) { if (interval <= 0) { throw new RuntimeException("interval must be a positive integer"); } List<Integer> list = new ArrayList(); if (start <= end) { for (int i = start; i <= end; i += interval) { list.add(i); } } else { for (int i = start; i >= end; i -= interval) { list.add(i); } } return JsValue.fromJava(list); } public Object read(String name) { Object result = getEngine().fileReader.readFile(name); return JsValue.fromJava(result); } public String readAsString(String fileName) { return getEngine().fileReader.readFileAsString(fileName); } public void remove(String name, String path) { getEngine().remove(name, path); } public Object repeat(int n, Value f) { assertIfJsFunction(f); List list = new ArrayList(n); for (int i = 0; i < n; i++) { Value v = JsEngine.execute(f, i); list.add(new JsValue(v).getValue()); } return new JsList(list); } // set multiple variables in one shot public void set(Map<String, Object> map) { getEngine().setVariables(map); } public void set(String name, Value value) { getEngine().setVariable(name, new Variable(value)); } // this makes sense mainly for xpath manipulation from within js public void set(String name, String path, Object value) { getEngine().set(name, path, new Variable(value)); } public void setXml(String name, String xml) { getEngine().setVariable(name, XmlUtils.toXmlDoc(xml)); } // this makes sense mainly for xpath manipulation from within js public void setXml(String name, String path, String xml) { getEngine().set(name, path, new Variable(XmlUtils.toXmlDoc(xml))); } @Override public void signal(Object o) { Value v = Value.asValue(o); getEngine().signal(JsValue.toJava(v)); } public Object sizeOf(Value v) { if (v.hasArrayElements()) { return v.getArraySize(); } else if (v.hasMembers()) { return v.getMemberKeys().size(); } else { return -1; } } public Object sort(Value o) { return sort(o, getEngine().JS.evalForValue("x => x")); } public Object sort(Value o, Value f) { if (!o.hasArrayElements()) { return JsList.EMPTY; } assertIfJsFunction(f); long count = o.getArraySize(); Map<Object, Object> map = new TreeMap(); for (int i = 0; i < count; i++) { Object item = JsValue.toJava(o.getArrayElement(i)); Value key = JsEngine.execute(f, item, i); if (key.isNumber()) { map.put(key.as(Number.class), item); } else { map.put(key.asString(), item); } } return JsValue.fromJava(new ArrayList(map.values())); } public MockServer start(Value value) { if (value.isString()) { return startInternal(Collections.singletonMap("mock", value.asString())); } else { return startInternal(new JsValue(value).getAsMap()); } } private MockServer startInternal(Map<String, Object> config) { String mock = (String) config.get("mock"); if (mock == null) { throw new RuntimeException("'mock' is missing: " + config); } File feature = toJavaFile(mock); MockServer.Builder builder = MockServer.feature(feature); String certFile = (String) config.get("cert"); if (certFile != null) { builder.certFile(toJavaFile(certFile)); } String keyFile = (String) config.get("key"); if (keyFile != null) { builder.keyFile(toJavaFile(keyFile)); } Boolean ssl = (Boolean) config.get("ssl"); if (ssl == null) { ssl = false; } Integer port = (Integer) config.get("port"); if (port == null) { port = 0; } Map<String, Object> arg = (Map) config.get("arg"); builder.args(arg); if (ssl) { builder.https(port); } else { builder.http(port); } return builder.build(); } public void stop(int port) { Command.waitForSocket(port); } public String toAbsolutePath(String relativePath) { return getEngine().fileReader.toAbsolutePath(relativePath); } public Object toBean(Object o, String className) { Json json = Json.of(o); Object bean = JsonUtils.fromJson(json.toString(), className); return JsValue.fromJava(bean); } public String toCsv(Object o) { Variable v = new Variable(o); if (!v.isList()) { throw new RuntimeException("not a json array: " + v); } List<Map<String, Object>> list = v.getValue(); return JsonUtils.toCsv(list); } public Object toJava(Value value) { if (value.canExecute()) { JsEngine copy = getEngine().JS.copy(); return new JsLambda(copy.attach(value)); } else { return new JsValue(value).getValue(); } } private File toJavaFile(String path) { return getEngine().fileReader.toResource(path).getFile(); } public Object toJson(Value value) { return toJson(value, false); } public Object toJson(Value value, boolean removeNulls) { JsValue jv = new JsValue(value); String json = JsonUtils.toJson(jv.getValue()); Object result = Json.of(json).value(); if (removeNulls) { JsonUtils.removeKeysWithNullValues(result); } return JsValue.fromJava(result); } // TODO deprecate public Object toList(Value value) { return new JsValue(value).getValue(); } // TODO deprecate public Object toMap(Value value) { return new JsValue(value).getValue(); } public String toString(Object o) { Variable v = new Variable(o); return v.getAsString(); } public String trim(String s) { return s == null ? null : s.trim(); } public String typeOf(Value value) { Variable v = new Variable(value); return v.getTypeString(); } public String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (Exception e) { getEngine().logger.warn("url encode failed: {}", e.getMessage()); return s; } } public String urlDecode(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (Exception e) { getEngine().logger.warn("url encode failed: {}", e.getMessage()); return s; } } public Object valuesOf(Value v) { if (v.hasArrayElements()) { return v; } else if (v.hasMembers()) { List list = new ArrayList(); for (String k : v.getMemberKeys()) { Value res = v.getMember(k); list.add(res.as(Object.class)); } return new JsList(list); } else { return null; } } public boolean waitForHttp(String url) { return Command.waitForHttp(url); } public boolean waitForPort(String host, int port) { return new Command().waitForPort(host, port); } public WebSocketClient webSocket(String url) { return webSocket(url, null, null); } public WebSocketClient webSocket(String url, Value value) { return webSocket(url, value, null); } public WebSocketClient webSocket(String url, Value listener, Value value) { Function<String, Boolean> handler; ScenarioEngine engine = getEngine(); if (listener == null || !listener.canExecute()) { handler = m -> true; } else { JsEngine copy = engine.JS.copy(); handler = new JsLambda(copy.attach(listener)); } WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue()); options.setTextHandler(handler); return engine.webSocket(options); } public WebSocketClient webSocketBinary(String url) { return webSocketBinary(url, null, null); } public WebSocketClient webSocketBinary(String url, Value value) { return webSocketBinary(url, value, null); } public WebSocketClient webSocketBinary(String url, Value listener, Value value) { Function<byte[], Boolean> handler; ScenarioEngine engine = getEngine(); if (listener == null || !listener.canExecute()) { handler = m -> true; } else { JsEngine copy = engine.JS.copy(); handler = new JsLambda(copy.attach(listener)); } WebSocketOptions options = new WebSocketOptions(url, value == null ? null : new JsValue(value).getValue()); options.setBinaryHandler(handler); return engine.webSocket(options); } public File write(Object o, String path) { ScenarioEngine engine = getEngine(); path = engine.runtime.featureRuntime.suite.buildDir + File.separator + path; File file = new File(path); FileUtils.writeToFile(file, JsValue.toBytes(o)); engine.logger.debug("write to file: {}", file); return file; } public Object xmlPath(Object o, String path) { Variable var = new Variable(o); Variable res = ScenarioEngine.evalXmlPath(var, path); return JsValue.fromJava(res.getValue()); } // helpers ================================================================= // private static void assertIfJsFunction(Value f) { if (!f.canExecute()) { throw new RuntimeException("not a js function: " + f); } } // make sure log() toString() is lazy static class LogWrapper { final Value[] values; LogWrapper(Value... values) { this.values = values; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Value v : values) { Variable var = new Variable(v); sb.append(var.getAsPrettyString()).append(' '); } return sb.toString(); } } public static class LogFacade { private static Logger getLogger() { return ScenarioEngine.get().logger; } private static String wrap(Value... values) { return new LogWrapper(values).toString(); } public void debug(Value... values) { getLogger().debug(wrap(values)); } public void info(Value... values) { getLogger().info(wrap(values)); } public void trace(Value... values) { getLogger().trace(wrap(values)); } public void warn(Value... values) { getLogger().warn(wrap(values)); } public void error(Value... values) { getLogger().error(wrap(values)); } } }
defensive coding based on a problem someone reported
karate-core/src/main/java/com/intuit/karate/core/ScenarioBridge.java
defensive coding based on a problem someone reported
Java
mit
5edefb0bf943852dc720342b668e0daa695419da
0
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
package ua.com.fielden.platform.sample.domain; import static java.lang.String.format; import java.util.Collection; import java.util.Date; import java.util.Map; import org.joda.time.DateTime; import com.google.inject.Inject; import ua.com.fielden.platform.continuation.NeedMoreData; import ua.com.fielden.platform.dao.CommonEntityDao; import ua.com.fielden.platform.dao.annotations.SessionRequired; import ua.com.fielden.platform.entity.annotation.EntityType; import ua.com.fielden.platform.entity.fetch.IFetchProvider; import ua.com.fielden.platform.entity.query.IFilter; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.sample.domain.observables.TgPersistentEntityWithPropertiesChangeSubject; /** * DAO implementation for companion object {@link ITgPersistentEntityWithProperties}. * It demos the use of {@link TgPersistentEntityWithPropertiesChangeSubject} for publishing change events to be propagated to the subscribed clients. * * @author Developers * */ @EntityType(TgPersistentEntityWithProperties.class) public class TgPersistentEntityWithPropertiesDao extends CommonEntityDao<TgPersistentEntityWithProperties> implements ITgPersistentEntityWithProperties { private final TgPersistentEntityWithPropertiesChangeSubject changeSubject; @Inject public TgPersistentEntityWithPropertiesDao(final TgPersistentEntityWithPropertiesChangeSubject changeSubject, final IFilter filter) { super(filter); this.changeSubject = changeSubject; } /** * Overridden to publish entity change events to an application wide observable. */ @Override @SessionRequired public TgPersistentEntityWithProperties save(final TgPersistentEntityWithProperties entity) { if (!entity.isPersisted()) { final Date dateValue = entity.getDateProp(); if (dateValue != null && new DateTime(2003, 2, 1, 6, 20).equals(new DateTime(dateValue))) { throw new IllegalArgumentException(format("Creation failed: [1/2/3 6:20] date is not permitted.")); } if (dateValue != null && new DateTime(2003, 2, 1, 6, 21).equals(new DateTime(dateValue))) { entity.getProperty("dateProp").setDomainValidationResult(Result.warning(dateValue, "[1/2/3 6:21] is acceptable, but with warning.")); } } else { final Result res = entity.isValid(); if (!res.isSuccessful()) { // throw precise exception about the validation error throw new IllegalArgumentException(format("Modification failed: %s", res.getMessage())); } } // let's demonstrate a simple approach to implementing user's warning acknowledgement // this example, albeit artificially, also demonstrates not just one but two sequential requests for additional user input in a form of acknowledgement if (entity.hasWarnings()) { if (!moreData("acknowledgedForTheFirstTime").isPresent()) { throw new NeedMoreData("Warnings need acknowledgement (first time)", TgAcknowledgeWarnings.class, "acknowledgedForTheFirstTime"); } else { final TgAcknowledgeWarnings continuation = this.<TgAcknowledgeWarnings> moreData("acknowledgedForTheFirstTime").get(); System.out.println("Acknowledged (first)? = " + continuation.getAcknowledged()); if (!moreData("acknowledgedForTheSecondTime").isPresent()) { throw new NeedMoreData("Warnings need acknowledgement (second time)", TgAcknowledgeWarnings.class, "acknowledgedForTheSecondTime"); } else { final TgAcknowledgeWarnings secondContinuation = this.<TgAcknowledgeWarnings> moreData("acknowledgedForTheSecondTime").get(); System.out.println("Acknowledged (second)? = " + secondContinuation.getAcknowledged()); } } } final boolean wasNew = false; // !entity.isPersisted(); final TgPersistentEntityWithProperties saved = super.save(entity); changeSubject.publish(saved); // if the entity was new and just successfully saved then let's return a new entity to mimic "continuous" entry // otherwise simply return the same entity if (wasNew && saved.isValid().isSuccessful()) { final TgPersistentEntityWithProperties newEntity = saved.getEntityFactory().newEntity(TgPersistentEntityWithProperties.class); // the following two lines can be uncommented to simulate the situation of an invalid new entity returned from save //newEntity.setRequiredValidatedProp(1); //newEntity.setRequiredValidatedProp(null); return newEntity; } return saved; } @Override public int batchDelete(final Collection<Long> entitiesIds) { return defaultBatchDelete(entitiesIds); } @Override @SessionRequired public void delete(final TgPersistentEntityWithProperties entity) { defaultDelete(entity); } @Override @SessionRequired public void delete(final EntityResultQueryModel<TgPersistentEntityWithProperties> model, final Map<String, Object> paramValues) { defaultDelete(model, paramValues); } @Override public IFetchProvider<TgPersistentEntityWithProperties> createFetchProvider() { return super.createFetchProvider() .with("key") // this property is "required" (necessary during saving) -- should be declared as fetching property .with("desc") .with("integerProp", "moneyProp", "bigDecimalProp", "stringProp", "booleanProp", "dateProp", "requiredValidatedProp") .with("domainInitProp", "nonConflictingProp", "conflictingProp") // .with("entityProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key")) .with("userParam", "userParam.basedOnUser") .with("entityProp", "entityProp.entityProp", "entityProp.compositeProp", "entityProp.compositeProp.desc", "entityProp.booleanProp") // .with("status") .with("critOnlyEntityProp") .with("compositeProp", "compositeProp.desc") // .with("producerInitProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key") .with("producerInitProp", "status.key", "status.desc") .with("colourProp"); // } }
platform-dao/src/main/java/ua/com/fielden/platform/sample/domain/TgPersistentEntityWithPropertiesDao.java
package ua.com.fielden.platform.sample.domain; import static java.lang.String.format; import java.util.Collection; import java.util.Date; import java.util.Map; import org.joda.time.DateTime; import com.google.inject.Inject; import ua.com.fielden.platform.continuation.NeedMoreData; import ua.com.fielden.platform.dao.CommonEntityDao; import ua.com.fielden.platform.dao.annotations.SessionRequired; import ua.com.fielden.platform.entity.annotation.EntityType; import ua.com.fielden.platform.entity.fetch.IFetchProvider; import ua.com.fielden.platform.entity.query.IFilter; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.sample.domain.observables.TgPersistentEntityWithPropertiesChangeSubject; /** * DAO implementation for companion object {@link ITgPersistentEntityWithProperties}. * It demos the use of {@link TgPersistentEntityWithPropertiesChangeSubject} for publishing change events to be propagated to the subscribed clients. * * @author Developers * */ @EntityType(TgPersistentEntityWithProperties.class) public class TgPersistentEntityWithPropertiesDao extends CommonEntityDao<TgPersistentEntityWithProperties> implements ITgPersistentEntityWithProperties { private final TgPersistentEntityWithPropertiesChangeSubject changeSubject; @Inject public TgPersistentEntityWithPropertiesDao(final TgPersistentEntityWithPropertiesChangeSubject changeSubject, final IFilter filter) { super(filter); this.changeSubject = changeSubject; } /** * Overridden to publish entity change events to an application wide observable. */ @Override @SessionRequired public TgPersistentEntityWithProperties save(final TgPersistentEntityWithProperties entity) { if (!entity.isPersisted()) { final Date dateValue = entity.getDateProp(); if (dateValue != null && new DateTime(2003, 2, 1, 6, 20).equals(new DateTime(dateValue))) { throw new IllegalArgumentException(format("Creation failed: [1/2/3 6:20] date is not permitted.")); } if (dateValue != null && new DateTime(2003, 2, 1, 6, 21).equals(new DateTime(dateValue))) { entity.getProperty("dateProp").setDomainValidationResult(Result.warning(dateValue, "[1/2/3 6:21] is acceptable, but with warning.")); } } else { final Result res = entity.isValid(); if (!res.isSuccessful()) { // throw precise exception about the validation error throw new IllegalArgumentException(format("Modification failed: %s", res.getMessage())); } } // let's demonstrate a simple approach to implementing user's warning acknowledgement // this example, albeit artificially, also demonstrates not just one but two sequential requests for additional user input in a form of acknowledgement if (entity.hasWarnings()) { if (moreData("acknowledgedForTheFirstTime").isPresent()) { final TgAcknowledgeWarnings continuation = this.<TgAcknowledgeWarnings> moreData("acknowledgedForTheFirstTime").get(); System.out.println("Acknowledged (first)? = " + continuation.getAcknowledged()); if (moreData("acknowledgedForTheSecondTime").isPresent()) { final TgAcknowledgeWarnings secondContinuation = this.<TgAcknowledgeWarnings> moreData("acknowledgedForTheSecondTime").get(); System.out.println("Acknowledged (second)? = " + secondContinuation.getAcknowledged()); } else { throw new NeedMoreData("Warnings need acknowledgement (second time)", TgAcknowledgeWarnings.class, "acknowledgedForTheSecondTime"); } } else { throw new NeedMoreData("Warnings need acknowledgement (first time)", TgAcknowledgeWarnings.class, "acknowledgedForTheFirstTime"); } } final boolean wasNew = false; // !entity.isPersisted(); final TgPersistentEntityWithProperties saved = super.save(entity); changeSubject.publish(saved); // if the entity was new and just successfully saved then let's return a new entity to mimic "continuous" entry // otherwise simply return the same entity if (wasNew && saved.isValid().isSuccessful()) { final TgPersistentEntityWithProperties newEntity = saved.getEntityFactory().newEntity(TgPersistentEntityWithProperties.class); // the following two lines can be uncommented to simulate the situation of an invalid new entity returned from save //newEntity.setRequiredValidatedProp(1); //newEntity.setRequiredValidatedProp(null); return newEntity; } return saved; } @Override public int batchDelete(final Collection<Long> entitiesIds) { return defaultBatchDelete(entitiesIds); } @Override @SessionRequired public void delete(final TgPersistentEntityWithProperties entity) { defaultDelete(entity); } @Override @SessionRequired public void delete(final EntityResultQueryModel<TgPersistentEntityWithProperties> model, final Map<String, Object> paramValues) { defaultDelete(model, paramValues); } @Override public IFetchProvider<TgPersistentEntityWithProperties> createFetchProvider() { return super.createFetchProvider() .with("key") // this property is "required" (necessary during saving) -- should be declared as fetching property .with("desc") .with("integerProp", "moneyProp", "bigDecimalProp", "stringProp", "booleanProp", "dateProp", "requiredValidatedProp") .with("domainInitProp", "nonConflictingProp", "conflictingProp") // .with("entityProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key")) .with("userParam", "userParam.basedOnUser") .with("entityProp", "entityProp.entityProp", "entityProp.compositeProp", "entityProp.compositeProp.desc", "entityProp.booleanProp") // .with("status") .with("critOnlyEntityProp") .with("compositeProp", "compositeProp.desc") // .with("producerInitProp", EntityUtils.fetch(TgPersistentEntityWithProperties.class).with("key") .with("producerInitProp", "status.key", "status.desc") .with("colourProp"); // } }
#602 Made the continuation related example a bit more readable.
platform-dao/src/main/java/ua/com/fielden/platform/sample/domain/TgPersistentEntityWithPropertiesDao.java
#602 Made the continuation related example a bit more readable.
Java
epl-1.0
06db9c84a7ec6284f0851da29b0dec3c89fb853a
0
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
package com.redhat.ceylon.eclipse.code.complete; import static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.formatPath; import static com.redhat.ceylon.eclipse.code.complete.ParameterContextValidator.findCharCount; import static com.redhat.ceylon.eclipse.util.Escaping.escapeName; import static com.redhat.ceylon.eclipse.util.Nodes.getReferencedNode; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isNameMatching; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.antlr.runtime.CommonToken; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.util.Nodes; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Functional; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.Value; public class CompletionUtil { public static List<Declaration> overloads(Declaration dec) { return dec.isAbstraction() ? dec.getOverloads() : singletonList(dec); } static List<Parameter> getParameters(ParameterList pl, boolean includeDefaults, boolean namedInvocation) { List<Parameter> ps = pl.getParameters(); if (includeDefaults) { return ps; } else { List<Parameter> list = new ArrayList<Parameter>(); for (Parameter p: ps) { if (!p.isDefaulted() || (namedInvocation && spreadable(p, ps))) { list.add(p); } } return list; } } private static boolean spreadable(Parameter param, List<Parameter> list) { Parameter lastParam = list.get(list.size()-1); if (param==lastParam && param.getModel() instanceof Value) { Type type = param.getType(); Unit unit = param.getDeclaration().getUnit(); return type!=null && unit.isIterableParameterType(type); } else { return false; } } static String fullPath(int offset, String prefix, Tree.ImportPath path) { StringBuilder fullPath = new StringBuilder(); if (path!=null) { String pathString = formatPath(path.getIdentifiers()); fullPath.append(pathString) .append('.'); int len = offset -path.getStartIndex() -prefix.length(); fullPath.setLength(len); } return fullPath.toString(); } static boolean isPackageDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("package.ceylon"); } static boolean isModuleDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("module.ceylon"); } static boolean isEmptyModuleDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return isModuleDescriptor(cpc) && lcu != null && lcu.getModuleDescriptors() .isEmpty(); } static boolean isEmptyPackageDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("package.ceylon") && lcu.getPackageDescriptors() .isEmpty(); } static int nextTokenType(CeylonParseController cpc, CommonToken token) { for (int i=token.getTokenIndex()+1; i<cpc.getTokens().size(); i++) { CommonToken tok = cpc.getTokens().get(i); if (tok.getChannel()!=CommonToken.HIDDEN_CHANNEL) { return tok.getType(); } } return -1; } static int getLine(final int offset, ITextViewer viewer) { int line=-1; try { line = viewer.getDocument().getLineOfOffset(offset); } catch (BadLocationException e) { e.printStackTrace(); } return line; } public static boolean isInBounds(List<Type> upperBounds, Type t) { boolean ok = true; for (Type ub: upperBounds) { if (!t.isSubtypeOf(ub) && !(ub.involvesTypeParameters() && t.getDeclaration() .inherits(ub.getDeclaration()))) { ok = false; break; } } return ok; } public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit) { return getSortedProposedValues(scope, unit, null); } public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit, final String exactName) { Map<String, DeclarationWithProximity> map = scope.getMatchingDeclarations(unit, "", 0); if (exactName!=null) { for (DeclarationWithProximity dwp: new ArrayList<DeclarationWithProximity> (map.values())) { if (!dwp.isUnimported() && !dwp.isAlias() && isNameMatching(dwp.getName(), exactName)) { map.put(dwp.getName(), new DeclarationWithProximity( dwp.getDeclaration(), -5)); } } } List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>( map.values()); Collections.sort(results, new ArgumentProposalComparator(exactName)); return results; } public static boolean isIgnoredLanguageModuleClass(Class clazz) { return clazz.isString() || clazz.isInteger() || clazz.isFloat() || clazz.isCharacter() || clazz.isAnnotation(); } public static boolean isIgnoredLanguageModuleValue(Value value) { String name = value.getName(); return name.equals("process") || name.equals("runtime") || name.equals("system") || name.equals("operatingSystem") || name.equals("language") || name.equals("emptyIterator") || name.equals("infinity") || name.endsWith("IntegerValue") || name.equals("finished"); } public static boolean isIgnoredLanguageModuleMethod(Function method) { String name = method.getName(); return name.equals("className") || name.equals("flatten") || name.equals("unflatten")|| name.equals("curry") || name.equals("uncurry") || name.equals("compose") || method.isAnnotation(); } static boolean isIgnoredLanguageModuleType(TypeDeclaration td) { return !td.isObject() && !td.isAnything() && !td.isString() && !td.isInteger() && !td.isCharacter() && !td.isFloat() && !td.isBoolean(); } public static String getInitialValueDescription( final Declaration dec, CeylonParseController cpc) { if (cpc!=null) { Node refnode = getReferencedNode(dec); Tree.SpecifierOrInitializerExpression sie = null; String arrow = null; if (refnode instanceof Tree.AttributeDeclaration) { Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) refnode; sie = ad.getSpecifierOrInitializerExpression(); arrow = " = "; } else if (refnode instanceof Tree.MethodDeclaration) { Tree.MethodDeclaration md = (Tree.MethodDeclaration) refnode; sie = md.getSpecifierExpression(); arrow = " => "; } Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); if (sie==null) { class FindInitializerVisitor extends Visitor { Tree.SpecifierOrInitializerExpression result; @Override public void visit( Tree.InitializerParameter that) { super.visit(that); Declaration d = that.getParameterModel() .getModel(); if (d!=null && d.equals(dec)) { result = that.getSpecifierExpression(); } } } FindInitializerVisitor fiv = new FindInitializerVisitor(); fiv.visit(lcu); sie = fiv.result; } if (sie!=null) { Tree.Expression e = sie.getExpression(); if (e!=null) { Tree.Term term = e.getTerm(); if (term instanceof Tree.Literal) { String text = term.getToken() .getText(); if (text.length()<20) { return arrow + text; } } else if (term instanceof Tree.BaseMemberOrTypeExpression) { Tree.BaseMemberOrTypeExpression bme = (Tree.BaseMemberOrTypeExpression) term; Tree.Identifier id = bme.getIdentifier(); if (id!=null && bme.getTypeArguments()==null) { return arrow + id.getText(); } } else if (term!=null) { Unit unit = lcu.getUnit(); if (term.getUnit().equals(unit)) { String impl = Nodes.toString(term, cpc.getTokens()); if (impl.length()<10) { return arrow + impl; } } } //don't have the token stream :-/ //TODO: figure out where to get it from! return arrow + "..."; } } } return ""; } public static String getDefaultValueDescription( Parameter param, CeylonParseController cpc) { if (param.isDefaulted()) { FunctionOrValue model = param.getModel(); if (model instanceof Functional) { return " => ..."; } else { return getInitialValueDescription(model, cpc); } } else { return ""; } } static String anonFunctionHeader( Type requiredType, Unit unit) { StringBuilder text = new StringBuilder(); text.append("("); boolean first = true; char c = 'a'; List<Type> argTypes = unit.getCallableArgumentTypes(requiredType); for (Type paramType: argTypes) { if (first) { first = false; } else { text.append(", "); } text.append(paramType.asSourceCodeString(unit)) .append(" ") .append(c++); } text.append(")"); return text.toString(); } public static IRegion getCurrentSpecifierRegion( IDocument document, int offset) throws BadLocationException { int start = offset; int length = 0; for (int i=offset; i<document.getLength(); i++) { char ch = document.getChar(i); if (Character.isWhitespace(ch) || ch==';'||ch==','||ch==')') { break; } length++; } return new Region(start, length); } public static String getProposedName( Declaration qualifier, Declaration dec, Unit unit) { StringBuilder buf = new StringBuilder(); if (qualifier!=null) { buf.append(escapeName(qualifier, unit)) .append('.'); } if (dec instanceof Constructor) { Constructor constructor = (Constructor) dec; TypeDeclaration clazz = constructor.getExtendedType() .getDeclaration(); buf.append(escapeName(clazz, unit)) .append('.'); } buf.append(escapeName(dec, unit)); return buf.toString(); } static IRegion getCurrentArgumentRegion( IDocument document, int loc, int index, int startOfArgs) throws BadLocationException { IRegion li = document.getLineInformationOfOffset(loc); int endOfLine = li.getOffset() + li.getLength(); int offset = findCharCount(index, document, loc+startOfArgs, endOfLine, ",;", "", true) + 1; if (offset>0 && document.getChar(offset)==' ') { offset++; } int nextOffset = findCharCount(index+1, document, loc+startOfArgs, endOfLine, ",;", "", true); int middleOffset = findCharCount(1, document, offset, nextOffset, "=", "", true)+1; if (middleOffset>0 && document.getChar(middleOffset)=='>') { middleOffset++; } while (middleOffset>0 && document.getChar(middleOffset)==' ') { middleOffset++; } if (middleOffset>offset && middleOffset<nextOffset) { offset = middleOffset; } if (nextOffset==-1) { nextOffset = offset; } return new Region(offset, nextOffset-offset); } public static String[] getAssignableLiterals( Type type, Unit unit) { TypeDeclaration dtd = unit.getDefiniteType(type) .getDeclaration(); if (dtd instanceof Class) { if (dtd.isInteger()) { return new String[] { "0", "1", "2" }; } if (dtd.isByte()) { return new String[] { "0.byte", "1.byte" }; } else if (dtd.isFloat()) { return new String[] { "0.0", "1.0", "2.0" }; } else if (dtd.isString()) { return new String[] { "\"\"", "\"\"\"\"\"\"" }; } else if (dtd.isCharacter()) { return new String[] { "' '", "'\\n'", "'\\t'" }; } else { return new String[0]; } } else if (dtd instanceof Interface) { if (dtd.isIterable()) { return new String[] { "{}" }; } else if (dtd.isSequential() || dtd.isEmpty()) { return new String[] { "[]" }; } else { return new String[0]; } } else { return new String[0]; } } }
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/complete/CompletionUtil.java
package com.redhat.ceylon.eclipse.code.complete; import static com.redhat.ceylon.compiler.typechecker.tree.TreeUtil.formatPath; import static com.redhat.ceylon.eclipse.code.complete.ParameterContextValidator.findCharCount; import static com.redhat.ceylon.eclipse.util.Escaping.escapeName; import static com.redhat.ceylon.eclipse.util.Nodes.getReferencedNode; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isNameMatching; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.antlr.runtime.CommonToken; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.util.Nodes; import com.redhat.ceylon.model.typechecker.model.Class; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Functional; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.Value; public class CompletionUtil { public static List<Declaration> overloads(Declaration dec) { return dec.isAbstraction() ? dec.getOverloads() : singletonList(dec); } static List<Parameter> getParameters(ParameterList pl, boolean includeDefaults, boolean namedInvocation) { List<Parameter> ps = pl.getParameters(); if (includeDefaults) { return ps; } else { List<Parameter> list = new ArrayList<Parameter>(); for (Parameter p: ps) { if (!p.isDefaulted() || (namedInvocation && spreadable(p, ps))) { list.add(p); } } return list; } } private static boolean spreadable(Parameter param, List<Parameter> list) { Parameter lastParam = list.get(list.size()-1); if (param==lastParam && param.getModel() instanceof Value) { Type type = param.getType(); Unit unit = param.getDeclaration().getUnit(); return type!=null && unit.isIterableParameterType(type); } else { return false; } } static String fullPath(int offset, String prefix, Tree.ImportPath path) { StringBuilder fullPath = new StringBuilder(); if (path!=null) { String pathString = formatPath(path.getIdentifiers()); fullPath.append(pathString) .append('.'); int len = offset -path.getStartIndex() -prefix.length(); fullPath.setLength(len); } return fullPath.toString(); } static boolean isPackageDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("package.ceylon"); } static boolean isModuleDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("module.ceylon"); } static boolean isEmptyModuleDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return isModuleDescriptor(cpc) && lcu != null && lcu.getModuleDescriptors() .isEmpty(); } static boolean isEmptyPackageDescriptor(CeylonParseController cpc) { Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); return lcu != null && lcu.getUnit() != null && lcu.getUnit() .getFilename() .equals("package.ceylon") && lcu.getPackageDescriptors() .isEmpty(); } static int nextTokenType(CeylonParseController cpc, CommonToken token) { for (int i=token.getTokenIndex()+1; i<cpc.getTokens().size(); i++) { CommonToken tok = cpc.getTokens().get(i); if (tok.getChannel()!=CommonToken.HIDDEN_CHANNEL) { return tok.getType(); } } return -1; } static int getLine(final int offset, ITextViewer viewer) { int line=-1; try { line = viewer.getDocument().getLineOfOffset(offset); } catch (BadLocationException e) { e.printStackTrace(); } return line; } public static boolean isInBounds(List<Type> upperBounds, Type t) { boolean ok = true; for (Type ub: upperBounds) { if (!t.isSubtypeOf(ub) && !(ub.involvesTypeParameters() && t.getDeclaration() .inherits(ub.getDeclaration()))) { ok = false; break; } } return ok; } public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit) { return getSortedProposedValues(scope, unit, null); } public static List<DeclarationWithProximity> getSortedProposedValues(Scope scope, Unit unit, final String exactName) { Map<String, DeclarationWithProximity> map = scope.getMatchingDeclarations(unit, "", 0); if (exactName!=null) { for (DeclarationWithProximity dwp: new ArrayList<DeclarationWithProximity> (map.values())) { if (!dwp.isUnimported() && !dwp.isAlias() && isNameMatching(dwp.getName(), exactName)) { map.put(dwp.getName(), new DeclarationWithProximity( dwp.getDeclaration(), -5)); } } } List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>( map.values()); Collections.sort(results, new ArgumentProposalComparator(exactName)); return results; } public static boolean isIgnoredLanguageModuleClass(Class clazz) { return clazz.isString() || clazz.isInteger() || clazz.isFloat() || clazz.isCharacter() || clazz.isAnnotation(); } public static boolean isIgnoredLanguageModuleValue(Value value) { String name = value.getName(); return name.equals("process") || name.equals("runtime") || name.equals("system") || name.equals("operatingSystem") || name.equals("language") || name.equals("emptyIterator") || name.equals("infinity") || name.endsWith("IntegerValue") || name.equals("finished"); } public static boolean isIgnoredLanguageModuleMethod(Function method) { String name = method.getName(); return name.equals("className") || name.equals("flatten") || name.equals("unflatten")|| name.equals("curry") || name.equals("uncurry") || name.equals("compose") || method.isAnnotation(); } static boolean isIgnoredLanguageModuleType(TypeDeclaration td) { return !td.isObject() && !td.isAnything() && !td.isString() && !td.isInteger() && !td.isCharacter() && !td.isFloat() && !td.isBoolean(); } public static String getInitialValueDescription( final Declaration dec, CeylonParseController cpc) { if (cpc!=null) { Node refnode = getReferencedNode(dec); Tree.SpecifierOrInitializerExpression sie = null; String arrow = null; if (refnode instanceof Tree.AttributeDeclaration) { Tree.AttributeDeclaration ad = (Tree.AttributeDeclaration) refnode; sie = ad.getSpecifierOrInitializerExpression(); arrow = " = "; } else if (refnode instanceof Tree.MethodDeclaration) { Tree.MethodDeclaration md = (Tree.MethodDeclaration) refnode; sie = md.getSpecifierExpression(); arrow = " => "; } Tree.CompilationUnit lcu = cpc.getLastCompilationUnit(); if (sie==null) { class FindInitializerVisitor extends Visitor { Tree.SpecifierOrInitializerExpression result; @Override public void visit( Tree.InitializerParameter that) { super.visit(that); Declaration d = that.getParameterModel() .getModel(); if (d!=null && d.equals(dec)) { result = that.getSpecifierExpression(); } } } FindInitializerVisitor fiv = new FindInitializerVisitor(); fiv.visit(lcu); sie = fiv.result; } if (sie!=null) { Tree.Expression e = sie.getExpression(); if (e!=null) { Tree.Term term = e.getTerm(); if (term instanceof Tree.Literal) { String text = term.getToken() .getText(); if (text.length()<20) { return arrow + text; } } else if (term instanceof Tree.BaseMemberOrTypeExpression) { Tree.BaseMemberOrTypeExpression bme = (Tree.BaseMemberOrTypeExpression) term; Tree.Identifier id = bme.getIdentifier(); if (id!=null && bme.getTypeArguments()==null) { return arrow + id.getText(); } } else if (term.getUnit() .equals(lcu.getUnit())) { String impl = Nodes.toString(term, cpc.getTokens()); if (impl.length()<10) { return arrow + impl; } } //don't have the token stream :-/ //TODO: figure out where to get it from! return arrow + "..."; } } } return ""; } public static String getDefaultValueDescription( Parameter param, CeylonParseController cpc) { if (param.isDefaulted()) { FunctionOrValue model = param.getModel(); if (model instanceof Functional) { return " => ..."; } else { return getInitialValueDescription(model, cpc); } } else { return ""; } } static String anonFunctionHeader( Type requiredType, Unit unit) { StringBuilder text = new StringBuilder(); text.append("("); boolean first = true; char c = 'a'; List<Type> argTypes = unit.getCallableArgumentTypes(requiredType); for (Type paramType: argTypes) { if (first) { first = false; } else { text.append(", "); } text.append(paramType.asSourceCodeString(unit)) .append(" ") .append(c++); } text.append(")"); return text.toString(); } public static IRegion getCurrentSpecifierRegion( IDocument document, int offset) throws BadLocationException { int start = offset; int length = 0; for (int i=offset; i<document.getLength(); i++) { char ch = document.getChar(i); if (Character.isWhitespace(ch) || ch==';'||ch==','||ch==')') { break; } length++; } return new Region(start, length); } public static String getProposedName( Declaration qualifier, Declaration dec, Unit unit) { StringBuilder buf = new StringBuilder(); if (qualifier!=null) { buf.append(escapeName(qualifier, unit)) .append('.'); } if (dec instanceof Constructor) { Constructor constructor = (Constructor) dec; TypeDeclaration clazz = constructor.getExtendedType() .getDeclaration(); buf.append(escapeName(clazz, unit)) .append('.'); } buf.append(escapeName(dec, unit)); return buf.toString(); } static IRegion getCurrentArgumentRegion( IDocument document, int loc, int index, int startOfArgs) throws BadLocationException { IRegion li = document.getLineInformationOfOffset(loc); int endOfLine = li.getOffset() + li.getLength(); int offset = findCharCount(index, document, loc+startOfArgs, endOfLine, ",;", "", true) + 1; if (offset>0 && document.getChar(offset)==' ') { offset++; } int nextOffset = findCharCount(index+1, document, loc+startOfArgs, endOfLine, ",;", "", true); int middleOffset = findCharCount(1, document, offset, nextOffset, "=", "", true)+1; if (middleOffset>0 && document.getChar(middleOffset)=='>') { middleOffset++; } while (middleOffset>0 && document.getChar(middleOffset)==' ') { middleOffset++; } if (middleOffset>offset && middleOffset<nextOffset) { offset = middleOffset; } if (nextOffset==-1) { nextOffset = offset; } return new Region(offset, nextOffset-offset); } public static String[] getAssignableLiterals( Type type, Unit unit) { TypeDeclaration dtd = unit.getDefiniteType(type) .getDeclaration(); if (dtd instanceof Class) { if (dtd.isInteger()) { return new String[] { "0", "1", "2" }; } if (dtd.isByte()) { return new String[] { "0.byte", "1.byte" }; } else if (dtd.isFloat()) { return new String[] { "0.0", "1.0", "2.0" }; } else if (dtd.isString()) { return new String[] { "\"\"", "\"\"\"\"\"\"" }; } else if (dtd.isCharacter()) { return new String[] { "' '", "'\\n'", "'\\t'" }; } else { return new String[0]; } } else if (dtd instanceof Interface) { if (dtd.isIterable()) { return new String[] { "{}" }; } else if (dtd.isSequential() || dtd.isEmpty()) { return new String[] { "[]" }; } else { return new String[0]; } } else { return new String[0]; } } }
squash npe
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/complete/CompletionUtil.java
squash npe
Java
epl-1.0
4541582e9704abde2973d94ea22d9336920f1876
0
ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio
/* * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, Member of the Helmholtz Association, * (DESY), HAMBURG, GERMANY. THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, * THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF * WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY SOFTWARE IS AUTHORIZED * HEREUNDER EXCEPT UNDER THIS DISCLAIMER. DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE * REDISTRIBUTION, MODIFICATION, USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE * DISTRIBUTION OF THIS PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY * FIND A COPY AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.sds.components.model; import org.csstudio.sds.model.AbstractTextTypeWidgetModel; import org.csstudio.sds.model.AbstractWidgetModel; import org.csstudio.sds.model.CursorStyleEnum; import org.csstudio.sds.model.TextAlignmentEnum; import org.csstudio.sds.model.TextTypeEnum; import org.csstudio.sds.model.WidgetPropertyCategory; import org.csstudio.sds.util.ColorAndFontUtil; /** * A widget model for text inputs. * * @author Alexander Will, Kai Meyer * @version $Revision$ */ public final class TextInputModel extends AbstractTextTypeWidgetModel { /** * The ID of the text input. */ public static final String PROP_INPUT_TEXT = "inputText"; //$NON-NLS-1$ /** * The ID of the font property. */ public static final String PROP_FONT = "font"; //$NON-NLS-1$ /** * The ID of the text alignment property. */ public static final String PROP_TEXT_ALIGNMENT = "textAlignment"; //$NON-NLS-1$ /** * The ID of this widget model. */ public static final String ID = "org.csstudio.sds.components.Textinput"; //$NON-NLS-1$ /** * The default value of the height property. */ private static final int DEFAULT_HEIGHT = 20; /** * The default value of the width property. */ private static final int DEFAULT_WIDTH = 80; /** * The ID of the <i>transparent</i> property. */ public static final String PROP_TRANSPARENT = "transparent"; /** * The ID of the <i>double type</i> property. */ public static final int TYPE_DOUBLE = 1; /** * Standard constructor. */ public TextInputModel() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setCursorId(CursorStyleEnum.IBEAM.name()); } /** * {@inheritDoc} */ @Override public String getTypeID() { return ID; } /** * {@inheritDoc} */ @Override protected void configureProperties() { // Display addStringProperty(PROP_INPUT_TEXT, "Input Text", WidgetPropertyCategory.DISPLAY, "", true,PROP_TOOLTIP); //$NON-NLS-1$ addArrayOptionProperty(PROP_TEXT_TYPE, "Value Type", WidgetPropertyCategory.DISPLAY, TextTypeEnum.getDisplayNames(), TextTypeEnum.DOUBLE.getIndex(), false, PROP_INPUT_TEXT); addIntegerProperty(PROP_PRECISION, "Decimal places", WidgetPropertyCategory.DISPLAY, 2, 0, 10, false,PROP_TEXT_TYPE); // Format addFontProperty(PROP_FONT, "Font", WidgetPropertyCategory.FORMAT, ColorAndFontUtil.toFontString("Arial", 8), false, PROP_COLOR_FOREGROUND); //$NON-NLS-1$ addArrayOptionProperty(PROP_TEXT_ALIGNMENT, "Text Alignment", WidgetPropertyCategory.FORMAT, TextAlignmentEnum.getDisplayNames(), TextAlignmentEnum.CENTER.getIndex(), false, PROP_FONT ); addBooleanProperty(PROP_TRANSPARENT, "Transparent Background", WidgetPropertyCategory.FORMAT, true, true, AbstractWidgetModel.PROP_COLOR_BACKGROUND); } /** * {@inheritDoc} */ @Override protected String getDefaultToolTip() { StringBuffer buffer = new StringBuffer(); buffer.append(createTooltipParameter(PROP_ALIASES) + "\n"); buffer.append("Text:\t"); buffer.append(createTooltipParameter(PROP_INPUT_TEXT)); return buffer.toString(); } /** * Gets the input text. * * @return the input text */ public String getInputText() { return getStringProperty(PROP_INPUT_TEXT); } /** * Gets, if the marks should be shown or not. * * @return int 0 = Center, 1 = Top, 2 = Bottom, 3 = Left, 4 = Right */ public int getTextAlignment() { return getArrayOptionProperty(PROP_TEXT_ALIGNMENT); } /** * Returns, if this widget should have a transparent background. * * @return boolean True, if it should have a transparent background, false otherwise */ public boolean getTransparent() { return getBooleanProperty(PROP_TRANSPARENT); } /** * {@inheritDoc} */ @Override public String getStringValueID() { return PROP_INPUT_TEXT; } }
applications/plugins/org.csstudio.sds.components/src/org/csstudio/sds/components/model/TextInputModel.java
/* * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, Member of the Helmholtz Association, * (DESY), HAMBURG, GERMANY. THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, * THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF * WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY SOFTWARE IS AUTHORIZED * HEREUNDER EXCEPT UNDER THIS DISCLAIMER. DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE * REDISTRIBUTION, MODIFICATION, USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE * DISTRIBUTION OF THIS PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY * FIND A COPY AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.sds.components.model; import org.csstudio.sds.model.AbstractTextTypeWidgetModel; import org.csstudio.sds.model.AbstractWidgetModel; import org.csstudio.sds.model.CursorStyleEnum; import org.csstudio.sds.model.TextAlignmentEnum; import org.csstudio.sds.model.TextTypeEnum; import org.csstudio.sds.model.WidgetPropertyCategory; import org.csstudio.sds.util.ColorAndFontUtil; /** * A widget model for text inputs. * * @author Alexander Will, Kai Meyer * @version $Revision$ */ public final class TextInputModel extends AbstractTextTypeWidgetModel { /** * The ID of the text input. */ public static final String PROP_INPUT_TEXT = "inputText"; //$NON-NLS-1$ /** * The ID of the font property. */ public static final String PROP_FONT = "font"; //$NON-NLS-1$ /** * The ID of the text alignment property. */ public static final String PROP_TEXT_ALIGNMENT = "textAlignment"; //$NON-NLS-1$ /** * The ID of this widget model. */ public static final String ID = "org.csstudio.sds.components.Textinput"; //$NON-NLS-1$ /** * The default value of the height property. */ private static final int DEFAULT_HEIGHT = 20; /** * The default value of the width property. */ private static final int DEFAULT_WIDTH = 80; /** * The ID of the <i>transparent</i> property. */ public static final String PROP_TRANSPARENT = "transparent"; /** * The ID of the <i>double type</i> property. */ public static final int TYPE_DOUBLE = 1; /** * Standard constructor. */ public TextInputModel() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setCursorId(CursorStyleEnum.IBEAM.name()); } /** * {@inheritDoc} */ @Override public String getTypeID() { return ID; } /** * {@inheritDoc} */ @Override protected void configureProperties() { // Display addStringProperty(PROP_INPUT_TEXT, "Input Text", WidgetPropertyCategory.DISPLAY, "", true,PROP_TOOLTIP); //$NON-NLS-1$ addArrayOptionProperty(PROP_TEXT_ALIGNMENT, "Text Alignment", WidgetPropertyCategory.DISPLAY, TextAlignmentEnum.getDisplayNames(), TextAlignmentEnum.CENTER.getIndex(), false, PROP_INPUT_TEXT ); addArrayOptionProperty(PROP_TEXT_TYPE, "Value Type", WidgetPropertyCategory.DISPLAY, TextTypeEnum.getDisplayNames(), TextTypeEnum.DOUBLE.getIndex(), false, PROP_TEXT_ALIGNMENT); addIntegerProperty(PROP_PRECISION, "Decimal places", WidgetPropertyCategory.DISPLAY, 2, 0, 10, false,PROP_TEXT_TYPE); // Format addFontProperty(PROP_FONT, "Font", WidgetPropertyCategory.FORMAT, ColorAndFontUtil.toFontString("Arial", 8), false, PROP_COLOR_FOREGROUND); //$NON-NLS-1$ addBooleanProperty(PROP_TRANSPARENT, "Transparent Background", WidgetPropertyCategory.FORMAT, true, true, AbstractWidgetModel.PROP_COLOR_BACKGROUND); } /** * {@inheritDoc} */ @Override protected String getDefaultToolTip() { StringBuffer buffer = new StringBuffer(); buffer.append(createTooltipParameter(PROP_ALIASES) + "\n"); buffer.append("Text:\t"); buffer.append(createTooltipParameter(PROP_INPUT_TEXT)); return buffer.toString(); } /** * Gets the input text. * * @return the input text */ public String getInputText() { return getStringProperty(PROP_INPUT_TEXT); } /** * Gets, if the marks should be shown or not. * * @return int 0 = Center, 1 = Top, 2 = Bottom, 3 = Left, 4 = Right */ public int getTextAlignment() { return getArrayOptionProperty(PROP_TEXT_ALIGNMENT); } /** * Returns, if this widget should have a transparent background. * * @return boolean True, if it should have a transparent background, false otherwise */ public boolean getTransparent() { return getBooleanProperty(PROP_TRANSPARENT); } /** * {@inheritDoc} */ @Override public String getStringValueID() { return PROP_INPUT_TEXT; } }
change Text Alignment category to format
applications/plugins/org.csstudio.sds.components/src/org/csstudio/sds/components/model/TextInputModel.java
change Text Alignment category to format
Java
epl-1.0
80d42828c913d4822c8c80a2779f2c8d2dc76418
0
miklossy/xtext-core,miklossy/xtext-core
/******************************************************************************* * Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.parser.terminalrules; import org.eclipse.xtext.Grammar; import org.eclipse.xtext.GrammarUtil; import org.eclipse.xtext.IGrammarAccess; import org.eclipse.xtext.conversion.IValueConverter; import org.eclipse.xtext.conversion.ValueConverter; import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService; import org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter; import org.eclipse.xtext.parsetree.AbstractNode; import org.eclipse.xtext.util.Strings; import com.google.inject.Inject; /** * @author Sebastian Zarnekow - Initial contribution and API */ public class TerminalRuleTestLanguageConverters extends AbstractDeclarativeValueConverterService { // copied from Common.Terminals but without rule for int private Grammar g; @Inject public void setGrammar(IGrammarAccess ga) { this.g = ga.getGrammar(); } @ValueConverter(rule = "ID") public IValueConverter<String> ID() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return string.startsWith("^") ? string.substring(1) : string; } @Override protected String internalToString(String value) { if (GrammarUtil.getAllKeywords(g).contains(value)) { return "^"+value; } return value; } }; } @ValueConverter(rule = "STRING") public IValueConverter<String> STRING() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return Strings.convertFromJavaString(string.substring(1, string.length() - 1)); } @Override protected String internalToString(String value) { return '"' + Strings.convertToJavaString(value) + '"'; } }; } }
tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/terminalrules/TerminalRuleTestLanguageConverters.java
/******************************************************************************* * Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.parser.terminalrules; import org.eclipse.xtext.Grammar; import org.eclipse.xtext.GrammarUtil; import org.eclipse.xtext.IGrammarAccess; import org.eclipse.xtext.conversion.IValueConverter; import org.eclipse.xtext.conversion.ValueConverter; import org.eclipse.xtext.conversion.impl.AbstractAnnotationBasedValueConverterService; import org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter; import org.eclipse.xtext.parsetree.AbstractNode; import org.eclipse.xtext.util.Strings; import com.google.inject.Inject; /** * @author Sebastian Zarnekow - Initial contribution and API */ public class TerminalRuleTestLanguageConverters extends AbstractAnnotationBasedValueConverterService { // copied from Common.Terminals but without rule for int private Grammar g; @Inject public void setGrammar(IGrammarAccess ga) { this.g = ga.getGrammar(); } @ValueConverter(rule = "ID") public IValueConverter<String> ID() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return string.startsWith("^") ? string.substring(1) : string; } @Override protected String internalToString(String value) { if (GrammarUtil.getAllKeywords(g).contains(value)) { return "^"+value; } return value; } }; } @ValueConverter(rule = "STRING") public IValueConverter<String> STRING() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return Strings.convertFromJavaString(string.substring(1, string.length() - 1)); } @Override protected String internalToString(String value) { return '"' + Strings.convertToJavaString(value) + '"'; } }; } }
AbstractAnnotationBased ... renamed to AbstractDeclarative...
tests/org.eclipse.xtext.generator.tests/src/org/eclipse/xtext/parser/terminalrules/TerminalRuleTestLanguageConverters.java
AbstractAnnotationBased ... renamed to AbstractDeclarative...
Java
mpl-2.0
1eeb6ff4c760b6e8a9dcbe6c55c0f4ca3c0a5180
0
etomica/etomica,ajschult/etomica,etomica/etomica,etomica/etomica,ajschult/etomica,ajschult/etomica
package etomica.potential; import etomica.Atom; import etomica.AtomSet; import etomica.Default; import etomica.EtomicaElement; import etomica.EtomicaInfo; import etomica.Simulation; import etomica.Space; import etomica.space.Vector; /** * @author David Kofke * * Inverse-power potential between an atom and all four boundaries of the phase. */ public class P1SoftBoundary extends Potential1 implements PotentialSoft, EtomicaElement { private final Vector gradient; private double radius; private Atom atom; public P1SoftBoundary() { this(Simulation.getDefault().space); } public P1SoftBoundary(Space space) { super(space); gradient = space.makeVector(); setRadius(0.5*Default.ATOM_SIZE); } public static EtomicaInfo getEtomicaInfo() { EtomicaInfo info = new EtomicaInfo("PotentialSoft repulsive potential at the phase boundaries"); return info; } public double energy(AtomSet a) { Vector dimensions = ((Atom)a).node.parentPhase().boundary().dimensions(); double rx = atom.coord.position().x(0); double ry = atom.coord.position().x(1); double dx1 = (dimensions.x(0) - rx); double dy1 = (dimensions.x(1) - ry); return energy(rx) + energy(ry) + energy(dx1) + energy(dy1); }//end of energy private double energy(double r) { r /= radius; double r2 = r*r; double r6 = r2*r2*r2; return r6*r6; } private double gradient(double r) { double rr = radius/r; double r2 = rr*rr; double r6 = r2*r2*r2; return -12*r6*r6/r; } public Vector gradient(AtomSet a) { Vector dimensions = boundary.dimensions(); double rx = ((Atom)a).coord.position().x(0); double ry = atom.coord.position().x(1); double dx1 = (dimensions.x(0) - rx); double dy1 = (dimensions.x(1) - ry); double gradx = gradient(rx) - gradient(dx1); double grady = gradient(ry) - gradient(dy1); gradient.setX(0,gradx); gradient.setX(1,grady); return gradient; } public double virial(AtomSet atoms) { return 0.0; } /** * Returns the radius. * @return double */ public double getRadius() { return radius; } /** * Sets the radius. * @param radius The radius to set */ public void setRadius(double radius) { this.radius = radius; } }
etomica/potential/P1SoftBoundary.java
package etomica.potential; import etomica.Atom; import etomica.AtomSet; import etomica.Default; import etomica.EtomicaElement; import etomica.EtomicaInfo; import etomica.Simulation; import etomica.Space; import etomica.space.Vector; /** * @author David Kofke * * Inverse-power potential between an atom and all four boundaries of the phase. */ public class P1SoftBoundary extends Potential1 implements PotentialSoft, EtomicaElement { private final int D; private final Vector gradient; private double radius, radius2; private double cutoff = Double.MAX_VALUE; private Atom atom; public P1SoftBoundary() { this(Simulation.getDefault().space); } public P1SoftBoundary(Space space) { super(space); D = space.D(); gradient = space.makeVector(); setRadius(0.5*Default.ATOM_SIZE); } public static EtomicaInfo getEtomicaInfo() { EtomicaInfo info = new EtomicaInfo("PotentialSoft repulsive potential at the phase boundaries"); return info; } public double energy(AtomSet a) { Vector dimensions = ((Atom)a).node.parentPhase().boundary().dimensions(); double rx = atom.coord.position().x(0); double ry = atom.coord.position().x(1); double dx1 = (dimensions.x(0) - rx); double dy1 = (dimensions.x(1) - ry); return energy(rx) + energy(ry) + energy(dx1) + energy(dy1); }//end of energy private double energy(double r) { r /= radius; double r2 = r*r; double r6 = r2*r2*r2; return r6*r6; } private double gradient(double r) { double rr = radius/r; double r2 = rr*rr; double r6 = r2*r2*r2; return -12*r6*r6/r; } public Vector gradient(AtomSet a) { Vector dimensions = boundary.dimensions(); double rx = ((Atom)a).coord.position().x(0); double ry = atom.coord.position().x(1); double dx1 = (dimensions.x(0) - rx); double dy1 = (dimensions.x(1) - ry); double gradx = gradient(rx) - gradient(dx1); double grady = gradient(ry) - gradient(dy1); gradient.setX(0,gradx); gradient.setX(1,grady); return gradient; } public double virial(AtomSet atoms) { return 0.0; } /** * Returns the radius. * @return double */ public double getRadius() { return radius; } /** * Sets the radius. * @param radius The radius to set */ public void setRadius(double radius) { this.radius = radius; radius2 = radius*radius; } }
cleanup -- remove used fields
etomica/potential/P1SoftBoundary.java
cleanup -- remove used fields
Java
lgpl-2.1
4d2f8303c6a329be274d8adc96a8e963fe298b05
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2013 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * Read the HuGE GWAS flat file and create GWAS items and GWASResults. * @author Richard Smith */ public class HugeGwasConverter extends BioFileConverter { // private static final String DATASET_TITLE = "HuGE GWAS Integrator"; private static final String DATA_SOURCE_NAME = "HuGE Navigator"; private String headerStart = "rs Number(region location)"; private Map<String, String> genes = new HashMap<String, String>(); private Map<String, String> pubs = new HashMap<String, String>(); private Map<String, String> snps = new HashMap<String, String>(); private Map<String, String> studies = new HashMap<String, String>(); private static final String HUMAN_TAXON = "9606"; private List<String> invalidGenes = Arrays.asList(new String[] {"nr", "intergenic"}); // approximately the minimum permitted double value in postgres private static final double MIN_POSTGRES_DOUBLE = 1.0E-307; private static final Logger LOG = Logger.getLogger(HugeGwasConverter.class); protected IdResolver rslv; /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public HugeGwasConverter(ItemWriter writer, Model model) { super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE); } /** * {@inheritDoc} */ public void process(Reader reader) throws Exception { if (rslv == null) { rslv = IdResolverService.getHumanIdResolver(); } Iterator<?> lineIter = FormattedTextParser.parseTabDelimitedReader(reader); boolean doneHeader = false; while (lineIter.hasNext()) { String[] line = (String[]) lineIter.next(); LOG.info("Line: " + line); if (line[0].startsWith(headerStart)) { doneHeader = true; continue; } if (!doneHeader) { continue; } if (line.length <= 1) { continue; } Set<String> rsNumbers = parseSnpRsNumbers(line[0]); if (rsNumbers.isEmpty()) { continue; } Set<String> geneIdentifiers = getGenes(line[1]); String phenotype = line[3]; String firstAuthor = line[4]; String year = line[6]; String pubIdentifier = getPub(line[7]); Map<String, String> samples = parseSamples(line[8]); String riskAlleleStr = line[9]; Double pValue = parsePValue(line[11]); // There may be multiple SNPs in one line, create a GWASResult per SNP. for (String rsNumber : rsNumbers) { Item result = createItem("GWASResult"); result.setReference("SNP", getSnpIdentifier(rsNumber)); if (!geneIdentifiers.isEmpty()) { result.setCollection("associatedGenes", new ArrayList<String>(geneIdentifiers)); } result.setAttribute("phenotype", phenotype); if (pValue != null) { result.setAttribute("pValue", pValue.toString()); } String studyIdentifier = getStudy(pubIdentifier, firstAuthor, year, phenotype, samples); result.setReference("study", studyIdentifier); // set risk allele details String[] alleleParts = riskAlleleStr.split("\\["); String alleleStr = alleleParts[0]; if (alleleStr.startsWith("rs")) { if (alleleStr.indexOf('-') >= 0) { String riskSnp = alleleStr.substring(0, alleleStr.indexOf('-')); if (riskSnp.equals(rsNumber)) { String allele = alleleStr.substring(alleleStr.indexOf('-') + 1); result.setAttribute("associatedVariantRiskAllele", allele); } } else { LOG.warn("ALLELE: no allele found in '" + alleleStr + "'."); } } else { result.setAttribute("associatedVariantRiskAllele", alleleParts[0]); } if (alleleParts.length > 1) { String freqStr = alleleParts[1]; try { Float freq = Float.parseFloat(freqStr.substring(0, freqStr.indexOf(']'))); result.setAttribute("riskAlleleFreqInControls", freq.toString()); } catch (NumberFormatException e) { // wasn't a valid float, probably "NR" } } store(result); } } } /** * Read a p-value from a String of the format 5x10-6. * @param s the input string, e.g. 5x10-6 * @return the extracted double or null if failed to parse */ protected Double parsePValue(String s) { s = s.replace("x10", "E"); try { double pValue = Double.parseDouble(s); // Postgres JDBC driver is allowing double values outside the permitted range to be // stored which are then unusable. This a hack to prevent it. if (pValue < MIN_POSTGRES_DOUBLE) { pValue = 0.0; } return pValue; } catch (NumberFormatException e) { return null; } } private Map<String, String> parseSamples(String fromFile) { Map<String, String> samples = new HashMap<String, String>(); String[] parts = fromFile.split("/"); samples.put("initial", parts[0]); if (parts.length == 1 || "NR".equals(parts[1])) { samples.put("replicate", "No replicate"); } else { samples.put("replicate", parts[1]); } return samples; } /** * Extract a SNP rs id from a string of the format rs11099864(4q31.3). * @param s the string read from the file * @return the SNP rs number */ protected String parseSnp(String s) { if (s.indexOf('(') > 0) { return s.substring(0, s.indexOf('(')).trim(); } return s.trim(); } private String getStudy(String pubIdentifier, String firstAuthor, String year, String phenotype, Map<String, String> samples) throws ObjectStoreException { String studyIdentifier = studies.get(pubIdentifier); if (studyIdentifier == null) { Item gwas = createItem("GWAS"); gwas.setAttribute("firstAuthor", firstAuthor); gwas.setAttribute("year", year); gwas.setAttribute("name", phenotype); gwas.setAttribute("initialSample", samples.get("initial")); gwas.setAttribute("replicateSample", samples.get("replicate")); gwas.setReference("publication", pubIdentifier); store(gwas); studyIdentifier = gwas.getIdentifier(); studies.put(pubIdentifier, studyIdentifier); } return studyIdentifier; } private String getPub(String pubMedId) throws ObjectStoreException { String pubIdentifier = pubs.get(pubMedId); if (pubIdentifier == null) { Item pub = createItem("Publication"); pub.setAttribute("pubMedId", pubMedId); store(pub); pubIdentifier = pub.getIdentifier(); pubs.put(pubMedId, pubIdentifier); } return pubIdentifier; } private Set<String> parseSnpRsNumbers(String fromFile) { Set<String> rsNumbers = new HashSet<String>(); for (String s : fromFile.split(",")) { String rsNumber = parseSnp(s); if (rsNumber.startsWith("rs")) { rsNumbers.add(rsNumber); } } return rsNumbers; } private String getSnpIdentifier(String rsNumber) throws ObjectStoreException { if (!snps.containsKey(rsNumber)) { Item snp = createItem("SNP"); snp.setAttribute("primaryIdentifier", rsNumber); snp.setReference("organism", getOrganism(HUMAN_TAXON)); store(snp); snps.put(rsNumber, snp.getIdentifier()); } return snps.get(rsNumber); } private Set<String> getGenes(String s) throws ObjectStoreException { Set<String> geneIdentifiers = new HashSet<String>(); for (String symbol : s.split(",")) { symbol = symbol.trim(); if (invalidGenes.contains(symbol.toLowerCase())) { continue; } symbol = resolveGene(symbol); if (symbol == null) { continue; } String geneIdentifier = genes.get(symbol); if (geneIdentifier == null) { Item gene = createItem("Gene"); gene.setAttribute("symbol", symbol); gene.setReference("organism", getOrganism(HUMAN_TAXON)); geneIdentifier = gene.getIdentifier(); store(gene); genes.put(symbol, geneIdentifier); } geneIdentifiers.add(geneIdentifier); } return geneIdentifiers; } /** * resolve old human symbol * @param taxonId id of organism for this gene * @param ih interactor holder * @throws ObjectStoreException */ private String resolveGene(String identifier) { String id = identifier; if (rslv != null && rslv.hasTaxon(HUMAN_TAXON)) { int resCount = rslv.countResolutions(HUMAN_TAXON, identifier); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + identifier + " count: " + resCount + " Human identifier: " + rslv.resolveId(HUMAN_TAXON, identifier)); return null; } id = rslv.resolveId(HUMAN_TAXON, identifier).iterator().next(); } return id; } }
bio/sources/human/huge-gwas/main/src/org/intermine/bio/dataconversion/HugeGwasConverter.java
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2013 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * Read the HuGE GWAS flat file and create GWAS items and GWASResults. * @author Richard Smith */ public class HugeGwasConverter extends BioFileConverter { // private static final String DATASET_TITLE = "HuGE GWAS Integrator"; private static final String DATA_SOURCE_NAME = "HuGE Navigator"; private String headerStart = "rs Number(region location)"; private Map<String, String> genes = new HashMap<String, String>(); private Map<String, String> pubs = new HashMap<String, String>(); private Map<String, String> snps = new HashMap<String, String>(); private Map<String, String> studies = new HashMap<String, String>(); private static final String HUMAN_TAXON = "9606"; private List<String> invalidGenes = Arrays.asList(new String[] {"nr", "intergenic"}); // approximately the minimum permitted double value in postgres private static final double MIN_POSTGRES_DOUBLE = 1.0E-307; private static final Logger LOG = Logger.getLogger(HugeGwasConverter.class); /** * Constructor * @param writer the ItemWriter used to handle the resultant items * @param model the Model */ public HugeGwasConverter(ItemWriter writer, Model model) { super(writer, model, DATA_SOURCE_NAME, DATASET_TITLE); } /** * {@inheritDoc} */ public void process(Reader reader) throws Exception { Iterator<?> lineIter = FormattedTextParser.parseTabDelimitedReader(reader); boolean doneHeader = false; while (lineIter.hasNext()) { String[] line = (String[]) lineIter.next(); LOG.info("Line: " + line); if (line[0].startsWith(headerStart)) { doneHeader = true; continue; } if (!doneHeader) { continue; } if (line.length <= 1) { continue; } Set<String> rsNumbers = parseSnpRsNumbers(line[0]); if (rsNumbers.isEmpty()) { continue; } Set<String> geneIdentifiers = getGenes(line[1]); String phenotype = line[3]; String firstAuthor = line[4]; String year = line[6]; String pubIdentifier = getPub(line[7]); Map<String, String> samples = parseSamples(line[8]); String riskAlleleStr = line[9]; Double pValue = parsePValue(line[11]); // There may be multiple SNPs in one line, create a GWASResult per SNP. for (String rsNumber : rsNumbers) { Item result = createItem("GWASResult"); result.setReference("SNP", getSnpIdentifier(rsNumber)); if (!geneIdentifiers.isEmpty()) { result.setCollection("associatedGenes", new ArrayList<String>(geneIdentifiers)); } result.setAttribute("phenotype", phenotype); if (pValue != null) { result.setAttribute("pValue", pValue.toString()); } String studyIdentifier = getStudy(pubIdentifier, firstAuthor, year, phenotype, samples); result.setReference("study", studyIdentifier); // set risk allele details String[] alleleParts = riskAlleleStr.split("\\["); String alleleStr = alleleParts[0]; if (alleleStr.startsWith("rs")) { if (alleleStr.indexOf('-') >= 0) { String riskSnp = alleleStr.substring(0, alleleStr.indexOf('-')); if (riskSnp.equals(rsNumber)) { String allele = alleleStr.substring(alleleStr.indexOf('-') + 1); result.setAttribute("associatedVariantRiskAllele", allele); } } else { LOG.warn("ALLELE: no allele found in '" + alleleStr + "'."); } } else { result.setAttribute("associatedVariantRiskAllele", alleleParts[0]); } if (alleleParts.length > 1) { String freqStr = alleleParts[1]; try { Float freq = Float.parseFloat(freqStr.substring(0, freqStr.indexOf(']'))); result.setAttribute("riskAlleleFreqInControls", freq.toString()); } catch (NumberFormatException e) { // wasn't a valid float, probably "NR" } } store(result); } } } /** * Read a p-value from a String of the format 5x10-6. * @param s the input string, e.g. 5x10-6 * @return the extracted double or null if failed to parse */ protected Double parsePValue(String s) { s = s.replace("x10", "E"); try { double pValue = Double.parseDouble(s); // Postgres JDBC driver is allowing double values outside the permitted range to be // stored which are then unusable. This a hack to prevent it. if (pValue < MIN_POSTGRES_DOUBLE) { pValue = 0.0; } return pValue; } catch (NumberFormatException e) { return null; } } private Map<String, String> parseSamples(String fromFile) { Map<String, String> samples = new HashMap<String, String>(); String[] parts = fromFile.split("/"); samples.put("initial", parts[0]); if (parts.length == 1 || "NR".equals(parts[1])) { samples.put("replicate", "No replicate"); } else { samples.put("replicate", parts[1]); } return samples; } /** * Extract a SNP rs id from a string of the format rs11099864(4q31.3). * @param s the string read from the file * @return the SNP rs number */ protected String parseSnp(String s) { if (s.indexOf('(') > 0) { return s.substring(0, s.indexOf('(')).trim(); } return s.trim(); } private String getStudy(String pubIdentifier, String firstAuthor, String year, String phenotype, Map<String, String> samples) throws ObjectStoreException { String studyIdentifier = studies.get(pubIdentifier); if (studyIdentifier == null) { Item gwas = createItem("GWAS"); gwas.setAttribute("firstAuthor", firstAuthor); gwas.setAttribute("year", year); gwas.setAttribute("name", phenotype); gwas.setAttribute("initialSample", samples.get("initial")); gwas.setAttribute("replicateSample", samples.get("replicate")); gwas.setReference("publication", pubIdentifier); store(gwas); studyIdentifier = gwas.getIdentifier(); studies.put(pubIdentifier, studyIdentifier); } return studyIdentifier; } private String getPub(String pubMedId) throws ObjectStoreException { String pubIdentifier = pubs.get(pubMedId); if (pubIdentifier == null) { Item pub = createItem("Publication"); pub.setAttribute("pubMedId", pubMedId); store(pub); pubIdentifier = pub.getIdentifier(); pubs.put(pubMedId, pubIdentifier); } return pubIdentifier; } private Set<String> parseSnpRsNumbers(String fromFile) { Set<String> rsNumbers = new HashSet<String>(); for (String s : fromFile.split(",")) { String rsNumber = parseSnp(s); if (rsNumber.startsWith("rs")) { rsNumbers.add(rsNumber); } } return rsNumbers; } private String getSnpIdentifier(String rsNumber) throws ObjectStoreException { if (!snps.containsKey(rsNumber)) { Item snp = createItem("SNP"); snp.setAttribute("primaryIdentifier", rsNumber); snp.setReference("organism", getOrganism(HUMAN_TAXON)); store(snp); snps.put(rsNumber, snp.getIdentifier()); } return snps.get(rsNumber); } private Set<String> getGenes(String s) throws ObjectStoreException { Set<String> geneIdentifiers = new HashSet<String>(); for (String symbol : s.split(",")) { symbol = symbol.trim(); if (invalidGenes.contains(symbol.toLowerCase())) { continue; } String geneIdentifier = genes.get(symbol); if (geneIdentifier == null) { Item gene = createItem("Gene"); gene.setAttribute("symbol", symbol); gene.setReference("organism", getOrganism(HUMAN_TAXON)); geneIdentifier = gene.getIdentifier(); store(gene); genes.put(symbol, geneIdentifier); } geneIdentifiers.add(geneIdentifier); } return geneIdentifiers; } }
HuGE - resolve old symbols of human #291 Former-commit-id: 842d1efb31fe9070ebf4d34406c269de0bcd5b43
bio/sources/human/huge-gwas/main/src/org/intermine/bio/dataconversion/HugeGwasConverter.java
HuGE - resolve old symbols of human #291
Java
lgpl-2.1
3811abb414b59b561b62a764e8d064be0ed24b51
0
tmyroadctfig/mpxj
/* * file: Props9.java * author: Jon Iles * copyright: Tapster Rock Limited * date: 07/11/2003 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.mpp; //import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; /** * This class represents the Props files found in Microsoft Project MPP9 files. */ final class Props9 extends Props { /** * Constructor, reads the property data from an input stream. * * @param is input stream for reading props data */ Props9 (InputStream is) throws IOException { //FileOutputStream fos = new FileOutputStream ("c:\\temp\\props9." + System.currentTimeMillis() + ".txt"); //PrintWriter pw = new PrintWriter (fos); byte[] header = new byte[16]; byte[] data; is.read(header); int headerCount = MPPUtility.getShort(header, 12); int foundCount = 0; int availableBytes = is.available(); while (foundCount < headerCount) { int itemSize = readInt(is); int itemKey = readInt(is); /*int attrib3 = */readInt(is); availableBytes -= 12; if (availableBytes < itemSize || itemSize < 1) { break; } data = new byte[itemSize]; is.read(data); availableBytes -= itemSize; m_map.put(new Integer (itemKey), data); //pw.println(foundCount + " "+ attrib2 + ": " + MPPUtility.hexdump(data, true)); ++foundCount; // // Align to two byte boundary // if (data.length % 2 != 0) { is.skip(1); } } //pw.flush(); //pw.close(); } /** * This method dumps the contents of this properties block as a String. * Note that this facility is provided as a debugging aid. * * @return formatted contents of this block */ public String toString () { StringWriter sw = new StringWriter (); PrintWriter pw = new PrintWriter (sw); pw.println ("BEGIN Props"); Iterator iter = m_map.keySet().iterator(); Integer key; while (iter.hasNext() == true) { key = (Integer)iter.next(); pw.println (" Key: " + key + " Value: "); pw.println (MPPUtility.hexdump((byte[])m_map.get(key), true, 16, " ")); } pw.println ("END Props"); pw.println (); pw.close(); return (sw.toString()); } }
net/sf/mpxj/mpp/Props9.java
/* * file: Props9.java * author: Jon Iles * copyright: Tapster Rock Limited * date: 07/11/2003 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.mpp; //import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; /** * This class represents the Props files found in Microsoft Project MPP9 files. */ final class Props9 extends Props { /** * Constructor, reads the property data from an input stream. * * @param is input stream for reading props data */ Props9 (InputStream is) throws IOException { //FileOutputStream fos = new FileOutputStream ("c:\\temp\\props9." + System.currentTimeMillis() + ".txt"); //PrintWriter pw = new PrintWriter (fos); byte[] header = new byte[16]; byte[] data; is.read(header); int headerCount = MPPUtility.getShort(header, 12); int foundCount = 0; int availableBytes = is.available(); while (foundCount < headerCount) { int attrib1 = readInt(is); int attrib2 = readInt(is); /*int attrib3 = */readInt(is); availableBytes -= 12; if (availableBytes < attrib1 || attrib1 < 1) { break; } data = new byte[attrib1]; is.read(data); availableBytes -= attrib1; m_map.put(new Integer (attrib2), data); //pw.println(foundCount + " "+ attrib2 + ": " + MPPUtility.hexdump(data, true)); ++foundCount; // // Align to two byte boundary // if (data.length % 2 != 0) { is.skip(1); } } //pw.flush(); //pw.close(); } /** * This method dumps the contents of this properties block as a String. * Note that this facility is provided as a debugging aid. * * @return formatted contents of this block */ public String toString () { StringWriter sw = new StringWriter (); PrintWriter pw = new PrintWriter (sw); pw.println ("BEGIN Props"); Iterator iter = m_map.keySet().iterator(); Integer key; while (iter.hasNext() == true) { key = (Integer)iter.next(); pw.println (" Key: " + key + " Value: "); pw.println (MPPUtility.hexdump((byte[])m_map.get(key), true, 16, " ")); } pw.println ("END Props"); pw.println (); pw.close(); return (sw.toString()); } }
Renamed variables for clarity.
net/sf/mpxj/mpp/Props9.java
Renamed variables for clarity.
Java
lgpl-2.1
59689f19d7017cd1be711992f09e884843a260bb
0
jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb
/* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration), * 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ package alma.contLogTest.LogLevelsImpl; import junit.framework.Assert; import junit.framework.TestCase; import si.ijs.maci.Administrator; import si.ijs.maci.AdministratorPOATie; import si.ijs.maci.Container; import si.ijs.maci.ContainerInfo; import si.ijs.maci.LoggingConfigurableHelper; import si.ijs.maci.LoggingConfigurableOperations; import alma.ACSErrTypeCommon.CouldntPerformActionEx; import alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx; import alma.JavaContainerError.wrappers.AcsJContainerEx; import alma.acs.component.client.ComponentClient; import alma.acs.component.client.ComponentClientTestCase; import alma.acs.container.AcsManagerProxy; import alma.contLogTest.LogLevels; import alma.maciErrType.NoPermissionEx; /** * Requires Java component "TESTLOG1" of type <code>alma.contLogTest.LogLevels</code> to be running. * * @author eallaert 30 October 2007 */ public class LogLevelsTest extends ComponentClientTestCase { private ComponentClient hlc = null; private LogLevels m_testlogComp; private static String component[]; /** * @param name * @throws java.lang.Exception */ public LogLevelsTest() throws Exception { super(LogLevelsTest.class.getName()); } /** * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); // if (false) { // String managerLoc = System.getProperty("ACS.manager"); // if (managerLoc == null) { // System.out // .println("Java property 'ACS.manager' must be set to the corbaloc of the ACS manager!"); // System.exit(-1); // } // /* // String clientName = "LogLevelsClient"; // try { // hlc = new ComponentClient(null, managerLoc, clientName); // m_logger.info("got LogLevel client"); // } catch (Exception e) { // try { // Logger logger = hlc.getContainerServices().getLogger(); // logger.log(Level.SEVERE, "Client application failure", e); // } catch (Exception e2) { // e.printStackTrace(System.err); // } // } // */ // } } /** * @see TestCase#tearDown() */ protected void tearDown() throws Exception { // if (hlc != null) // { // try // { // hlc.tearDown(); // } // catch (Exception e3) // { // // bad luck // e3.printStack Trace(); // } // } super.tearDown(); } // public void testGetLoggingConfigurableInterface() throws Exception { // LoggingConfigurableOperations containerLogConfig = getContainerLoggingIF("heikoContainer"); // String[] loggerNames = containerLogConfig.get_logger_names(); // assertNotNull(loggerNames); // } // public void testGetLevels() throws Exception { int levels[]; for (int i = 0; i < component.length; i++) { m_testlogComp = alma.contLogTest.LogLevelsHelper.narrow(getContainerServices().getComponent(component[i])); try { levels = m_testlogComp.getLevels(); } catch (CouldntPerformActionEx ex) { throw AcsJCouldntPerformActionEx.fromCouldntPerformActionEx(ex); } m_logger.info("levels from component's getLevels method (hardcoded remote, local, effective): " + levels[0] + ", " + levels[1] + ", " + levels[2] + ", " + levels[3] + ", " + levels[4]); // levels[0-4]: hardcoded remote, hardcoded local, AcsLogger, AcsLogHandler, StdoutConsoleHandler Assert.assertTrue(levels[3] != -1); Assert.assertTrue(levels[4] != -1); // The AcsLogger setting should be the minimum of the one for AcsLogHandler and StdoutConsoleHandler int minLevel = levels[3]; if (levels[3] > levels[4] || levels[3] == -1) minLevel = levels[4]; Assert.assertEquals(levels[2], minLevel); } } /** * Gets a reference to the LoggingConfigurableOperations interface of a container with a given name. * <p> * Note that only in test code like here we are allowed to talk directly with the manager. * For operational code, the ContainerServices methods must be used and extended if necessary. * * @param containerName */ public LoggingConfigurableOperations getContainerLoggingIF(String containerName) throws AcsJContainerEx, NoPermissionEx { AdministratorPOATie adminpoa = new AdministratorPOATie(new ManagerAdminClient(getName(), m_logger)); Administrator adminCorbaObj = adminpoa._this(getContainerServices().getAdvancedContainerServices().getORB()); // we need an new manager connection because the JUnit test does not have admin right. AcsManagerProxy adminProxy = m_acsManagerProxy.createInstance(); Container containerRef; try { adminProxy.loginToManager(adminCorbaObj, false); int adminManagerHandle = adminProxy.getManagerHandle(); assertTrue(adminManagerHandle > 0); // ask the manager for the container reference ContainerInfo[] containerInfos = adminProxy.getManager().get_container_info(adminManagerHandle, new int[0], containerName); assertEquals(1, containerInfos.length); containerRef = containerInfos[0].reference; } finally { // now that we got our reference, we can logout the manager client again. // Of course this is too dirty for operational code, because manager cannot keep track of // admin clients holding container references... adminProxy.logoutFromManager(); } // cast up to LoggingConfigurable interface return LoggingConfigurableHelper.narrow(containerRef); } /** * @TODO We usually don't require a main method for a JUnit test to run successfully. * Therefore instead of getting component names from the arg list, * they should be given in some Java property that can be evaluated in the setUp method. */ public static void main(String[] args) { component = new String[args.length]; for (int i = 0; i < args.length; i++) { component[i] = new String(args[i]); } junit.textui.TestRunner.run(LogLevelsTest.class); } }
LGPL/CommonSoftware/containerTests/contLogTest/test/alma/contLogTest/LogLevelsImpl/LogLevelsTest.java
/* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration), * 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ package alma.contLogTest.LogLevelsImpl; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import junit.framework.Assert; import alma.ACSErrTypeCommon.CouldntPerformActionEx; import alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx; import alma.acs.component.client.ComponentClient; import alma.acs.component.client.ComponentClientTestCase; import alma.contLogTest.LogLevels; import alma.maci.loggingconfig.LoggingConfig; /** * Requires Java component "TESTLOG1" of type <code>alma.contLogTest.LogLevels</code> to be running. * * @author eallaert 30 October 2007 */ public class LogLevelsTest extends ComponentClientTestCase { private ComponentClient hlc = null; private LogLevels m_testlogComp; private static String component[]; /** * @param name * @throws java.lang.Exception */ public LogLevelsTest() throws Exception { super(LogLevelsTest.class.getName()); } /** * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); if (false) { String managerLoc = System.getProperty("ACS.manager"); if (managerLoc == null) { System.out .println("Java property 'ACS.manager' must be set to the corbaloc of the ACS manager!"); System.exit(-1); } /* String clientName = "LogLevelsClient"; try { hlc = new ComponentClient(null, managerLoc, clientName); m_logger.info("got LogLevel client"); } catch (Exception e) { try { Logger logger = hlc.getContainerServices().getLogger(); logger.log(Level.SEVERE, "Client application failure", e); } catch (Exception e2) { e.printStackTrace(System.err); } } */ } } /** * @see TestCase#tearDown() */ protected void tearDown() throws Exception { if (hlc != null) { try { hlc.tearDown(); } catch (Exception e3) { // bad luck e3.printStackTrace(); } } super.tearDown(); } public void testGetLevels() throws Exception { int levels[]; for (int i = 0; i < component.length; i++) { m_testlogComp = alma.contLogTest.LogLevelsHelper.narrow(getContainerServices().getComponent(component[i])); try { levels = m_testlogComp.getLevels(); } catch (CouldntPerformActionEx ex) { throw AcsJCouldntPerformActionEx.fromCouldntPerformActionEx(ex); } m_logger.info("levels from component's getLevels method (hardcoded remote, local, effective): " + levels[0] + ", " + levels[1] + ", " + levels[2] + ", " + levels[3] + ", " + levels[4]); // levels[0-4]: hardcoded remote, hardcoded local, AcsLogger, AcsLogHandler, StdoutConsoleHandler Assert.assertTrue(levels[3] != -1); Assert.assertTrue(levels[4] != -1); // The AcsLogger setting should be the minimum of the one for AcsLogHandler and StdoutConsoleHandler int minLevel = levels[3]; if (levels[3] > levels[4] || levels[3] == -1) minLevel = levels[4]; Assert.assertEquals(levels[2], minLevel); } } public static void main(String[] args) { component = new String[args.length]; for (int i = 0; i < args.length; i++) { component[i] = new String(args[i]); } junit.textui.TestRunner.run(LogLevelsTest.class); } }
new helper method getContainerLoggingIF to allow direct logging API calls on all containers git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@79779 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/containerTests/contLogTest/test/alma/contLogTest/LogLevelsImpl/LogLevelsTest.java
new helper method getContainerLoggingIF to allow direct logging API calls on all containers
Java
apache-2.0
f596b4db71b69f49652351c3c0623552954fd78b
0
endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.gson.JsonSyntaxException; import org.apache.commons.csv.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.fhir.PeriodHelper; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.FileInfo; import org.endeavourhealth.common.utility.JsonSerializer; import org.endeavourhealth.common.utility.SlackHelper; import org.endeavourhealth.core.configuration.ConfigDeserialiser; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.configuration.QueueReaderConfiguration; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirStorageService; import org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.transform.barts.BartsCsvToFhirTransformer; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper; import org.hibernate.internal.SessionImpl; import org.hl7.fhir.instance.model.EpisodeOfCare; import org.hl7.fhir.instance.model.Patient; import org.hl7.fhir.instance.model.ResourceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.*; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { String configId = args[0]; LOG.info("Initialising config manager"); ConfigManager.initialize("queuereader", configId); /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEncounters")) { String table = args[1]; fixEncounters(table); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("CreateAdastraSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateVisionSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createVisionSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateTppSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createTppSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateBartsSubset")) { String sourceDirPath = args[1]; UUID serviceUuid = UUID.fromString(args[2]); UUID systemUuid = UUID.fromString(args[3]); String samplePatientsFile = args[4]; createBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsOrgs")) { String serviceId = args[1]; fixBartsOrgs(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestPreparedStatements")) { String url = args[1]; String user = args[2]; String pass = args[3]; String serviceId = args[4]; testPreparedStatements(url, user, pass, serviceId); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("ApplyEmisAdminCaches")) { applyEmisAdminCaches(); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixSubscribers")) { fixSubscriberDbs(); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("ConvertExchangeBody")) { String systemId = args[1]; convertExchangeBody(UUID.fromString(systemId)); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixReferrals")) { fixReferralRequests(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateNewSearchTable")) { String table = args[1]; populateNewSearchTable(table); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsEscapes")) { String filePath = args[1]; fixBartsEscapedFiles(filePath); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; String systemId = args[2]; String filePath = args[3]; postToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixDisabledExtract")) { String serviceId = args[1]; String systemId = args[2]; String sharedStoragePath = args[3]; String tempDir = args[4]; fixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestSlack")) { testSlack(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; boolean all = Boolean.parseBoolean(args[2]); postToInbound(UUID.fromString(serviceId), all); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixPatientSearch")) { String serviceId = args[1]; fixPatientSearch(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("Exit")) { String exitCode = args[1]; LOG.info("Exiting with error code " + exitCode); int exitCodeInt = Integer.parseInt(exitCode); System.exit(exitCodeInt); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("RunSql")) { String host = args[1]; String username = args[2]; String password = args[3]; String sqlFile = args[4]; runSql(host, username, password, sqlFile); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateProtocolQueue")) { String serviceId = null; if (args.length > 1) { serviceId = args[1]; } String startingExchangeId = null; if (args.length > 2) { startingExchangeId = args[2]; } populateProtocolQueue(serviceId, startingExchangeId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEncounterTerms")) { String path = args[1]; String outputPath = args[2]; findEncounterTerms(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEmisStartDates")) { String path = args[1]; String outputPath = args[2]; findEmisStartDates(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("ExportHl7Encounters")) { String sourceCsvPpath = args[1]; String outputPath = args[2]; exportHl7Encounters(sourceCsvPpath, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixExchangeBatches")) { fixExchangeBatches(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindCodes")) { findCodes(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindDeletedOrgs")) { findDeletedOrgs(); System.exit(0); }*/ if (args.length != 1) { LOG.error("Usage: queuereader config_id"); return; } LOG.info("--------------------------------------------------"); LOG.info("EDS Queue Reader " + configId); LOG.info("--------------------------------------------------"); LOG.info("Fetching queuereader configuration"); String configXml = ConfigManager.getConfiguration(configId); QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); /*LOG.info("Registering shutdown hook"); registerShutdownHook();*/ // Instantiate rabbit handler LOG.info("Creating EDS queue reader"); RabbitHandler rabbitHandler = new RabbitHandler(configuration, configId); // Begin consume rabbitHandler.start(); LOG.info("EDS Queue reader running (kill file location " + TransformConfig.instance().getKillFileLocation() + ")"); } private static void convertExchangeBody(UUID systemUuid) { try { LOG.info("Converting exchange bodies for system " + systemUuid); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE); if (exchanges.isEmpty()) { continue; } LOG.debug("doing " + service.getName() + " with " + exchanges.size() + " exchanges"); for (Exchange exchange: exchanges) { String exchangeBody = exchange.getBody(); try { //already done ExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class); continue; } catch (JsonSyntaxException ex) { //if the JSON can't be parsed, then it'll be the old format of body that isn't JSON } List<ExchangePayloadFile> newFiles = new ArrayList<>(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (String file: files) { ExchangePayloadFile fileObj = new ExchangePayloadFile(); String fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1); fileObj.setPath(fileWithoutSharedStorage); //size List<FileInfo> fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file); for (FileInfo info: fileInfos) { if (info.getFilePath().equals(file)) { long size = info.getSize(); fileObj.setSize(new Long(size)); } } //type if (systemUuid.toString().equalsIgnoreCase("991a9068-01d3-4ff2-86ed-249bd0541fb3") //live || systemUuid.toString().equalsIgnoreCase("55c08fa5-ef1e-4e94-aadc-e3d6adc80774")) { //dev //emis String name = FilenameUtils.getName(file); String[] toks = name.split("_"); String first = toks[1]; String second = toks[2]; fileObj.setType(first + "_" + second); } else if (systemUuid.toString().equalsIgnoreCase("e517fa69-348a-45e9-a113-d9b59ad13095") || systemUuid.toString().equalsIgnoreCase("b0277098-0b6c-4d9d-86ef-5f399fb25f34")) { //dev //cerner String name = FilenameUtils.getName(file); String type = BartsCsvToFhirTransformer.identifyFileType(name); fileObj.setType(type); } else { throw new Exception("Unknown system ID " + systemUuid); } newFiles.add(fileObj); } String json = JsonSerializer.serialize(newFiles); exchange.setBody(json); exchangeDal.save(exchange); } } LOG.info("Finished Converting exchange bodies for system " + systemUuid); } catch (Exception ex) { LOG.error("", ex); } } /*private static void fixBartsOrgs(String serviceId) { try { LOG.info("Fixing Barts orgs"); ResourceDalI dal = DalProvider.factoryResourceDal(); List<ResourceWrapper> wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString()); LOG.debug("Found " + wrappers.size() + " resources"); int done = 0; int fixed = 0; for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { List<ResourceWrapper> history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId()); ResourceWrapper mostRecent = history.get(0); String json = mostRecent.getResourceData(); Organization org = (Organization)FhirSerializationHelper.deserializeResource(json); String odsCode = IdentifierHelper.findOdsCode(org); if (Strings.isNullOrEmpty(odsCode) && org.hasIdentifier()) { boolean hasBeenFixed = false; for (Identifier identifier: org.getIdentifier()) { if (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE) && identifier.hasId()) { odsCode = identifier.getId(); identifier.setValue(odsCode); identifier.setId(null); hasBeenFixed = true; } } if (hasBeenFixed) { String newJson = FhirSerializationHelper.serializeResource(org); mostRecent.setResourceData(newJson); LOG.debug("Fixed Organization " + org.getId()); *//*LOG.debug(json); LOG.debug(newJson);*//* saveResourceWrapper(UUID.fromString(serviceId), mostRecent); fixed ++; } } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done + ", Fixed " + fixed); } } LOG.debug("Done " + done + ", Fixed " + fixed); LOG.info("Finished Barts orgs"); } catch (Throwable t) { LOG.error("", t); } }*/ /*private static void testPreparedStatements(String url, String user, String pass, String serviceId) { try { LOG.info("Testing Prepared Statements"); LOG.info("Url: " + url); LOG.info("user: " + user); LOG.info("pass: " + pass); //open connection Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); String sql = "SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?"; long start = System.currentTimeMillis(); for (int i=0; i<10000; i++) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, serviceId); ps.setString(2, "MILLPERSIDtoMRN"); ps.setString(3, UUID.randomUUID().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { //do nothing } } finally { if (ps != null) { ps.close(); } } } long end = System.currentTimeMillis(); LOG.info("Took " + (end-start) + " ms"); //close connection conn.close(); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixEncounters(String table) { LOG.info("Fixing encounters from " + table); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date cutoff = sdf.parse("2018-03-14 11:42"); EntityManager entityManager = ConnectionManager.getAdminEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<UUID> serviceIds = new ArrayList<>(); Map<UUID, UUID> hmSystems = new HashMap<>(); String sql = "SELECT service_id, system_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { UUID serviceId = UUID.fromString(rs.getString(1)); UUID systemId = UUID.fromString(rs.getString(2)); serviceIds.add(serviceId); hmSystems.put(serviceId, systemId); } rs.close(); statement.close(); entityManager.close(); for (UUID serviceId: serviceIds) { UUID systemId = hmSystems.get(serviceId); LOG.info("Doing service " + serviceId + " and system " + systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId); List<UUID> exchangeIdsToProcess = new ArrayList<>(); for (UUID exchangeId: exchangeIds) { List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { Date d = audit.getStarted(); if (d.after(cutoff)) { exchangeIdsToProcess.add(exchangeId); break; } } } Map<String, ReferenceList> consultationNewChildMap = new HashMap<>(); Map<String, ReferenceList> observationChildMap = new HashMap<>(); Map<String, ReferenceList> newProblemChildren = new HashMap<>(); for (UUID exchangeId: exchangeIdsToProcess) { Exchange exchange = exchangeDal.getExchange(exchangeId); String[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody()); String version = EmisCsvToFhirTransformer.determineVersion(files); List<String> interestingFiles = new ArrayList<>(); for (String file: files) { if (file.indexOf("CareRecord_Consultation") > -1 || file.indexOf("CareRecord_Observation") > -1 || file.indexOf("CareRecord_Diary") > -1 || file.indexOf("Prescribing_DrugRecord") > -1 || file.indexOf("Prescribing_IssueRecord") > -1 || file.indexOf("CareRecord_Problem") > -1) { interestingFiles.add(file); } } files = interestingFiles.toArray(new String[0]); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers); String dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true); Consultation consultationParser = (Consultation)parsers.get(Consultation.class); while (consultationParser.nextRecord()) { CsvCell consultationGuid = consultationParser.getConsultationGuid(); CsvCell patientGuid = consultationParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); consultationNewChildMap.put(sourceId, new ReferenceList()); } Problem problemParser = (Problem)parsers.get(Problem.class); while (problemParser.nextRecord()) { CsvCell problemGuid = problemParser.getObservationGuid(); CsvCell patientGuid = problemParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); newProblemChildren.put(sourceId, new ReferenceList()); } //run this pre-transformer to pre-cache some stuff in the csv helper, which //is needed when working out the resource type that each observation would be saved as ObservationPreTransformer.transform(version, parsers, null, csvHelper); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { CsvCell observationGuid = observationParser.getObservationGuid(); CsvCell patientGuid = observationParser.getPatientGuid(); String obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid); CsvCell codeId = observationParser.getCodeId(); if (codeId.isEmpty()) { continue; } ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); UUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId); if (obUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + resourceType + " and source ID " + obSourceId); //resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); } Reference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString()); CsvCell consultationGuid = observationParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell problemGuid = observationParser.getProblemGuid(); if (!problemGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell parentObGuid = observationParser.getParentObservationGuid(); if (!parentObGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid); ReferenceList referenceList = observationChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); observationChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } } Diary diaryParser = (Diary)parsers.get(Diary.class); while (diaryParser.nextRecord()) { CsvCell consultationGuid = diaryParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { CsvCell diaryGuid = diaryParser.getDiaryGuid(); CsvCell patientGuid = diaryParser.getPatientGuid(); String diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid); UUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId); if (diaryUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.ProcedureRequest + " and source ID " + diarySourceId); } Reference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(diaryReference); } } IssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class); while (issueRecordParser.nextRecord()) { CsvCell problemGuid = issueRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid(); CsvCell patientGuid = issueRecordParser.getPatientGuid(); String issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid); UUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId); if (issueRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationOrder + " and source ID " + issueRecordSourceId); } Reference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(issueRecordReference); } } DrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class); while (drugRecordParser.nextRecord()) { CsvCell problemGuid = drugRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid(); CsvCell patientGuid = drugRecordParser.getPatientGuid(); String drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid); UUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId); if (drugRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationStatement + " and source ID " + drugRecordSourceId); } Reference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(drugRecordReference); } } for (AbstractCsvParser parser : parsers.values()) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } ResourceDalI resourceDal = DalProvider.factoryResourceDal(); LOG.info("Found " + consultationNewChildMap.size() + " Encounters to fix"); for (String encounterSourceId: consultationNewChildMap.keySet()) { ReferenceList childReferences = consultationNewChildMap.get(encounterSourceId); //map to UUID UUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId); if (encounterId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Encounter " + encounterId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Encounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(encounter); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } LOG.info("Found " + observationChildMap.size() + " Parent Observations to fix"); for (String sourceId: observationChildMap.keySet()) { ReferenceList childReferences = observationChildMap.get(sourceId); //map to UUID ResourceType resourceType = null; UUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId); if (resourceId != null) { resourceType = ResourceType.Observation; } else { resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId); if (resourceId != null) { resourceType = ResourceType.DiagnosticReport; } else { continue; } } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); if (history.isEmpty()) { //throw new Exception("Empty history for " + resourceType + " " + resourceId); continue; } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (resourceType == ResourceType.Observation) { if (wrapper.getResourceData() != null) { Observation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (observation.hasRelated()) { for (Observation.ObservationRelatedComponent related : observation.getRelated()) { Reference reference = related.getTarget(); childReferences.add(reference); } } } } else { if (wrapper.getResourceData() != null) { DiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (report.hasResult()) { for (Reference reference : report.getResult()) { childReferences.add(reference); } } } } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData()); boolean changed = false; if (resourceType == ResourceType.Observation) { ObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addChildObservation(reference)) { changed = true; } } } else { DiagnosticReportBuilder resourceBuilder = new DiagnosticReportBuilder((DiagnosticReport)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addResult(reference)) { changed = true; } } } if (changed) { String newJson = FhirSerializationHelper.serializeResource(resource); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); }*//* } LOG.info("Found " + newProblemChildren.size() + " Problems to fix"); for (String sourceId: newProblemChildren.keySet()) { ReferenceList childReferences = newProblemChildren.get(sourceId); //map to UUID UUID conditionId = IdHelper.getEdsResourceId(serviceId, ResourceType.Condition, sourceId); if (conditionId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Condition " + conditionId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Condition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(condition); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } //mark as done String updateSql = "UPDATE " + table + " SET done = 1 WHERE service_id = '" + serviceId + "';"; entityManager = ConnectionManager.getAdminEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); } *//** * For each practice: Go through all files processed since 14 March Cache all links as above Cache all Encounters saved too For each Encounter referenced at all: Retrieve latest version from resource current Retrieve version prior to 14 March Update current version with old references plus new ones For each parent observation: Retrieve latest version (could be observation or diagnostic report) For each problem: Retrieve latest version from resource current Check if still a problem: Retrieve version prior to 14 March Update current version with old references plus new ones *//* LOG.info("Finished Fixing encounters from " + table); } catch (Throwable t) { LOG.error("", t); } }*/ private static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception { if (wrapper.getResourceData() != null) { long checksum = FhirStorageService.generateChecksum(wrapper.getResourceData()); wrapper.setResourceChecksum(new Long(checksum)); } EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); entityManager.getTransaction().begin(); String json = wrapper.getResourceData(); json = json.replace("'", "''"); json = json.replace("\\", "\\\\"); String patientId = ""; if (wrapper.getPatientId() != null) { patientId = wrapper.getPatientId().toString(); } String updateSql = "UPDATE resource_current" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE service_id = '" + wrapper.getServiceId() + "'" + " AND patient_id = '" + patientId + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" + " AND resource_id = '" + wrapper.getResourceId() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); //String createdAtStr = sdf.format(wrapper.getCreatedAt()); updateSql = "UPDATE resource_history" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE resource_id = '" + wrapper.getResourceId() + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" //+ " AND created_at = '" + createdAtStr + "'" + " AND version = '" + wrapper.getVersion() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); entityManager.getTransaction().commit(); } /*private static void populateNewSearchTable(String table) { LOG.info("Populating New Search Table"); try { EntityManager entityManager = ConnectionManager.getEdsEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<String> patientIds = new ArrayList<>(); Map<String, String> serviceIds = new HashMap<>(); String sql = "SELECT patient_id, service_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String patientId = rs.getString(1); String serviceId = rs.getString(2); patientIds.add(patientId); serviceIds.put(patientId, serviceId); } rs.close(); statement.close(); entityManager.close(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal(); LOG.info("Found " + patientIds.size() + " to do"); for (int i=0; i<patientIds.size(); i++) { String patientIdStr = patientIds.get(i); UUID patientId = UUID.fromString(patientIdStr); String serviceIdStr = serviceIds.get(patientIdStr); UUID serviceId = UUID.fromString(serviceIdStr); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientIdStr); if (patient != null) { patientSearchDal.update(serviceId, patient); //find episode of care List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { EpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); patientSearchDal.update(serviceId, episodeOfCare); } } } String updateSql = "UPDATE " + table + " SET done = 1 WHERE patient_id = '" + patientIdStr + "' AND service_id = '" + serviceIdStr + "';"; entityManager = ConnectionManager.getEdsEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); if (i % 5000 == 0) { LOG.info("Done " + (i+1) + " of " + patientIds.size()); } } entityManager.close(); LOG.info("Finished Populating New Search Table"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) { LOG.info("Creating Barts Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } createBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds); LOG.info("Finished Creating Barts Subset"); } catch (Throwable t) { LOG.error("", t); } } /*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { for (File sourceFile: sourceDir.listFiles()) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } LOG.info("Doing dir " + sourceFile); createBartsSubsetForFile(sourceFile, destFile, personIds); } else { //we have some bad partial files in, so ignore them String ext = FilenameUtils.getExtension(name); if (ext.equalsIgnoreCase("filepart")) { continue; } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String baseName = FilenameUtils.getBaseName(name); String fileType = BartsCsvToFhirTransformer.identifyFileType(baseName); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex ++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i=0; i<expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex+1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } }*/ private static void createBartsSubsetForFile(String sourceDir, UUID serviceUuid, UUID systemUuid, Set<String> personIds) throws Exception { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); for (Exchange exchange: exchanges) { List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile fileObj : files) { String filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1); String sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage); File sourceFile = new File(sourceFilePath); String destFilePath = fileObj.getPath(); File destFile = new File(destFilePath); File destDir = destFile.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String fileType = fileObj.getType(); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i = 0; i < expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex + 1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } } private static void copyFile(File src, File dst) throws Exception { FileInputStream fis = new FileInputStream(src); BufferedInputStream bis = new BufferedInputStream(fis); Files.copy(bis, dst.toPath()); bis.close(); } private static boolean isCerner22File(String fileType) throws Exception { if (fileType.equalsIgnoreCase("PPATI") || fileType.equalsIgnoreCase("PPREL") || fileType.equalsIgnoreCase("CDSEV") || fileType.equalsIgnoreCase("PPATH") || fileType.equalsIgnoreCase("RTTPE") || fileType.equalsIgnoreCase("AEATT") || fileType.equalsIgnoreCase("AEINV") || fileType.equalsIgnoreCase("AETRE") || fileType.equalsIgnoreCase("OPREF") || fileType.equalsIgnoreCase("OPATT") || fileType.equalsIgnoreCase("EALEN") || fileType.equalsIgnoreCase("EALSU") || fileType.equalsIgnoreCase("EALOF") || fileType.equalsIgnoreCase("HPSSP") || fileType.equalsIgnoreCase("IPEPI") || fileType.equalsIgnoreCase("IPWDS") || fileType.equalsIgnoreCase("DELIV") || fileType.equalsIgnoreCase("BIRTH") || fileType.equalsIgnoreCase("SCHAC") || fileType.equalsIgnoreCase("APPSL") || fileType.equalsIgnoreCase("DIAGN") || fileType.equalsIgnoreCase("PROCE") || fileType.equalsIgnoreCase("ORDER") || fileType.equalsIgnoreCase("DOCRP") || fileType.equalsIgnoreCase("DOCREF") || fileType.equalsIgnoreCase("CNTRQ") || fileType.equalsIgnoreCase("LETRS") || fileType.equalsIgnoreCase("LOREF") || fileType.equalsIgnoreCase("ORGREF") || fileType.equalsIgnoreCase("PRSNLREF") || fileType.equalsIgnoreCase("CVREF") || fileType.equalsIgnoreCase("NOMREF") || fileType.equalsIgnoreCase("EALIP") || fileType.equalsIgnoreCase("CLEVE") || fileType.equalsIgnoreCase("ENCNT") || fileType.equalsIgnoreCase("RESREF") || fileType.equalsIgnoreCase("PPNAM") || fileType.equalsIgnoreCase("PPADD") || fileType.equalsIgnoreCase("PPPHO") || fileType.equalsIgnoreCase("PPALI") || fileType.equalsIgnoreCase("PPINF") || fileType.equalsIgnoreCase("PPAGP") || fileType.equalsIgnoreCase("SURCC") || fileType.equalsIgnoreCase("SURCP") || fileType.equalsIgnoreCase("SURCA") || fileType.equalsIgnoreCase("SURCD") || fileType.equalsIgnoreCase("PDRES") || fileType.equalsIgnoreCase("PDREF") || fileType.equalsIgnoreCase("ABREF") || fileType.equalsIgnoreCase("CEPRS") || fileType.equalsIgnoreCase("ORDDT") || fileType.equalsIgnoreCase("STATREF") || fileType.equalsIgnoreCase("STATA") || fileType.equalsIgnoreCase("ENCINF") || fileType.equalsIgnoreCase("SCHDETAIL") || fileType.equalsIgnoreCase("SCHOFFER") || fileType.equalsIgnoreCase("PPGPORG") || fileType.equalsIgnoreCase("FAMILYHISTORY")) { return true; } else { return false; } } private static void fixSubscriberDbs() { LOG.info("Fixing Subscriber DBs"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-05-11"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info(" Posting exchange " + exchangeId + " with " + batches.size() + " batches"); List<UUID> batchIds = new ArrayList<>(); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); batchIds.add(batchId); } String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } LOG.info("Finished Fixing Subscriber DBs"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixReferralRequests() { LOG.info("Fixing Referral Requests"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-04-24"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; Set<UUID> patientIdsToPost = new HashSet<>(); for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info("Checking exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); List<ResourceWrapper> wrappers = resourceDal.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper wrapper: wrappers) { String resourceType = wrapper.getResourceType(); if (!resourceType.equals(ResourceType.ReferralRequest.toString()) || wrapper.isDeleted()) { continue; } String json = wrapper.getResourceData(); ReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json); *//*if (!referral.hasServiceRequested()) { continue; } CodeableConcept reason = referral.getServiceRequested().get(0); referral.setReason(reason); referral.getServiceRequested().clear();*//* if (!referral.hasReason()) { continue; } CodeableConcept reason = referral.getReason(); referral.setReason(null); referral.addServiceRequested(reason); json = FhirSerializationHelper.serializeResource(referral); wrapper.setResourceData(json); saveResourceWrapper(serviceId, wrapper); //add to the set of patients we know need sending on to the protocol queue patientIdsToPost.add(patientId); LOG.info("Fixed " + resourceType + " " + wrapper.getResourceId() + " in batch " + batchId); } //if our patient has just been fixed or was fixed before, post onto the protocol queue if (patientIdsToPost.contains(patientId)) { List<UUID> batchIds = new ArrayList<>(); batchIds.add(batchId); String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } } LOG.info("Finished Fixing Referral Requests"); } catch (Throwable t) { LOG.error("", t); } }*/ private static void applyEmisAdminCaches() { LOG.info("Applying Emis Admin Caches"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } if (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) { LOG.info(" Service not started, so skipping"); continue; } //get exchanges List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); if (exchangeIds.isEmpty()) { LOG.info(" No exchanges found, so skipping"); continue; } UUID firstExchangeId = exchangeIds.get(0); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(firstExchangeId); boolean appliedAdminCache = false; for (ExchangeEvent event: events) { if (event.getEventDesc().equals("Applied Emis Admin Resource Cache")) { appliedAdminCache = true; } } if (appliedAdminCache) { LOG.info(" Have already applied admin cache, so skipping"); continue; } Exchange exchange = exchangeDal.getExchange(firstExchangeId); String body = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(body); if (files.length == 0) { LOG.info(" No files in exchange " + firstExchangeId + " so skipping"); continue; } String firstFilePath = files[0]; String name = FilenameUtils.getBaseName(firstFilePath); //file name without extension String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + firstFilePath); } String sharingAgreementGuid = toks[4]; List<UUID> batchIds = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds); EmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(), fhirResourceFiler.getExchangeId(), sharingAgreementGuid, true); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(endpointSystemId); transformAudit.setExchangeId(firstExchangeId); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); LOG.info(" Going to apply admin resource cache"); csvHelper.applyAdminResourceCache(fhirResourceFiler); fhirResourceFiler.waitToFinish(); for (UUID batchId: batchIds) { LOG.info(" Created batch ID " + batchId + " for exchange " + firstExchangeId); } transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIds.size())); boolean hadError = false; if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); hadError = true; } exchangeDal.save(transformAudit); //clear down the cache of reference mappings since they won't be of much use for the next Exchange IdHelper.clearCache(); if (hadError) { LOG.error(" <<<<<<Error applying resource cache!"); continue; } //add the event to say we've applied the cache AuditWriter.writeExchangeEvent(firstExchangeId, "Applied Emis Admin Resource Cache"); //post that ONE new batch ID onto the protocol queue String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } LOG.info("Finished Applying Emis Admin Caches"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixBartsEscapedFiles(String filePath) { LOG.info("Fixing Barts Escaped Files in " + filePath); try { fixBartsEscapedFilesInDir(new File(filePath)); LOG.info("Finished fixing Barts Escaped Files in " + filePath); } catch (Throwable t) { LOG.error("", t); } } /** * fixes Emis extract(s) when a practice was disabled then subsequently re-bulked, by * replacing the "delete" extracts with newly generated deltas that can be processed * before the re-bulk is done */ private static void fixDisabledEmisExtract(String serviceId, String systemId, String sharedStoragePath, String tempDir) { LOG.info("Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); try { /*File tempDirLast = new File(tempDir, "last"); if (!tempDirLast.exists()) { if (!tempDirLast.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirLast); } tempDirLast.mkdirs(); } File tempDirEmpty = new File(tempDir, "empty"); if (!tempDirEmpty.exists()) { if (!tempDirEmpty.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirEmpty); } tempDirEmpty.mkdirs(); }*/ UUID serviceUuid = UUID.fromString(serviceId); UUID systemUuid = UUID.fromString(systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); //get all the exchanges, which are returned in reverse order, so reverse for simplicity List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); //sorting by timestamp seems unreliable when exchanges were posted close together? List<Exchange> tmp = new ArrayList<>(); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); tmp.add(exchange); } exchanges = tmp; /*exchanges.sort((o1, o2) -> { Date d1 = o1.getTimestamp(); Date d2 = o2.getTimestamp(); return d1.compareTo(d2); });*/ LOG.info("Found " + exchanges.size() + " exchanges"); //continueOrQuit(); //find the files for each exchange Map<Exchange, List<String>> hmExchangeFiles = new HashMap<>(); Map<Exchange, List<String>> hmExchangeFilesWithoutStoragePrefix = new HashMap<>(); for (Exchange exchange: exchanges) { //populate a map of the files with the shared storage prefix String exchangeBody = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); List<String> fileList = Lists.newArrayList(files); hmExchangeFiles.put(exchange, fileList); //populate a map of the same files without the prefix files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (int i=0; i<files.length; i++) { String file = files[i].substring(sharedStoragePath.length() + 1); files[i] = file; } fileList = Lists.newArrayList(files); hmExchangeFilesWithoutStoragePrefix.put(exchange, fileList); } LOG.info("Cached files for each exchange"); int indexDisabled = -1; int indexRebulked = -1; int indexOriginallyBulked = -1; //go back through them to find the extract where the re-bulk is and when it was disabled for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { indexDisabled = i; } else { if (indexDisabled == -1) { indexRebulked = i; } else { //if we've found a non-disabled extract older than the disabled ones, //then we've gone far enough back break; } } } //go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled) for (int i=indexDisabled-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { break; } indexOriginallyBulked = i; } if (indexDisabled == -1 || indexRebulked == -1 || indexOriginallyBulked == -1) { throw new Exception("Failed to find exchanges for disabling (" + indexDisabled + "), re-bulking (" + indexRebulked + ") or original bulk (" + indexOriginallyBulked + ")"); } Exchange exchangeDisabled = exchanges.get(indexDisabled); LOG.info("Disabled on " + findExtractDate(exchangeDisabled, hmExchangeFiles) + " " + exchangeDisabled.getId()); Exchange exchangeRebulked = exchanges.get(indexRebulked); LOG.info("Rebulked on " + findExtractDate(exchangeRebulked, hmExchangeFiles) + " " + exchangeRebulked.getId()); Exchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked); LOG.info("Originally bulked on " + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + " " + exchangeOriginallyBulked.getId()); //continueOrQuit(); List<String> rebulkFiles = hmExchangeFiles.get(exchangeRebulked); List<String> tempFilesCreated = new ArrayList<>(); Set<String> patientGuidsDeletedOrTooOld = new HashSet<>(); for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (!isPatientFile(fileType)) { continue; } LOG.info("Doing " + fileType); String guidColumnName = getGuidColumnName(fileType); //find all the guids in the re-bulk Set<String> idsInRebulk = new HashSet<>(); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); String[] headers = null; try { headers = CsvHelper.getHeaderMapAsArray(csvParser); Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); //get the patient and row guid out of the file and cache in our set String id = record.get("PatientGuid"); if (!Strings.isNullOrEmpty(guidColumnName)) { id += "//" + record.get(guidColumnName); } idsInRebulk.add(id); } } finally { csvParser.close(); } LOG.info("Found " + idsInRebulk.size() + " IDs in re-bulk file: " + rebulkFile); //create a replacement file for the exchange the service was disabled String replacementDisabledFile = null; List<String> disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled); for (String s: disabledFiles) { String disabledFileType = findFileType(s); if (disabledFileType.equals(fileType)) { replacementDisabledFile = FilenameUtils.concat(tempDir, s); File dir = new File(replacementDisabledFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } tempFilesCreated.add(s); LOG.info("Created replacement file " + replacementDisabledFile); } } FileWriter fileWriter = new FileWriter(replacementDisabledFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); Set<String> pastIdsProcessed = new HashSet<>(); //now go through all files of the same type PRIOR to the service was disabled //to find any rows that we'll need to explicitly delete because they were deleted while //the extract was disabled for (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) { Exchange exchange = exchanges.get(i); String originalFile = null; List<String> files = hmExchangeFiles.get(exchange); for (String s: files) { String originalFileType = findFileType(s); if (originalFileType.equals(fileType)) { originalFile = s; break; } } if (originalFile == null) { continue; } LOG.info(" Reading " + originalFile); reader = FileHelper.readFileReaderFromSharedStorage(originalFile); csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientGuid = record.get("PatientGuid"); //get the patient and row guid out of the file and cache in our set String uniqueId = patientGuid; if (!Strings.isNullOrEmpty(guidColumnName)) { uniqueId += "//" + record.get(guidColumnName); } //if we're already handled this record in a more recent extract, then skip it if (pastIdsProcessed.contains(uniqueId)) { continue; } pastIdsProcessed.add(uniqueId); //if this ID isn't deleted and isn't in the re-bulk then it means //it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted //from Emis Web while the extract feed was disabled //if the record is deleted, then we won't expect it in the re-bulk boolean deleted = Boolean.parseBoolean(record.get("Deleted")); if (deleted) { //if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes if (fileType.equals("Admin_Patient")) { patientGuidsDeletedOrTooOld.add(patientGuid); } continue; } //if it's not the patient file and we refer to a patient that we know //has been deleted, then skip this row, since we know we're deleting the entire patient record if (patientGuidsDeletedOrTooOld.contains(patientGuid)) { continue; } //if the re-bulk contains a record matching this one, then it's OK if (idsInRebulk.contains(uniqueId)) { continue; } //the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago), //so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped if (fileType.equals("Admin_Patient")) { //retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid); Patient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString()); if (patientResource.hasDeceased()) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } UUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too EpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString()); if (episodeResource.hasPeriod() && !PeriodHelper.isActive(episodeResource.getPeriod())) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } } //create a new CSV record, carrying over the GUIDs from the original but marking as deleted String[] newRecord = new String[headers.length]; for (int j=0; j<newRecord.length; j++) { String header = headers[j]; if (header.equals("PatientGuid") || header.equals("OrganisationGuid") || (!Strings.isNullOrEmpty(guidColumnName) && header.equals(guidColumnName))) { String val = record.get(header); newRecord[j] = val; } else if (header.equals("Deleted")) { newRecord[j] = "true"; } else { newRecord[j] = ""; } } csvPrinter.printRecord((Object[])newRecord); csvPrinter.flush(); //log out the raw record that's missing from the original StringBuffer sb = new StringBuffer(); sb.append("Record not in re-bulk: "); for (int j=0; j<record.size(); j++) { if (j > 0) { sb.append(","); } sb.append(record.get(j)); } LOG.info(sb.toString()); } } finally { csvParser.close(); } } csvPrinter.flush(); csvPrinter.close(); //also create a version of the CSV file with just the header and nothing else in for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals(fileType)) { String emptyTempFile = FilenameUtils.concat(tempDir, s); File dir = new File(emptyTempFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } fileWriter = new FileWriter(emptyTempFile); bufferedWriter = new BufferedWriter(fileWriter); csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); csvPrinter.close(); tempFilesCreated.add(s); LOG.info("Created empty file " + emptyTempFile); } } } } //we also need to copy the restored sharing agreement file to replace all the period it was disabled String rebulkedSharingAgreementFile = null; for (String s: rebulkFiles) { String fileType = findFileType(s); if (fileType.equals("Agreements_SharingOrganisation")) { rebulkedSharingAgreementFile = s; } } for (int i=indexDisabled; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals("Agreements_SharingOrganisation")) { String replacementFile = FilenameUtils.concat(tempDir, s); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile); Files.copy(inputStream, new File(replacementFile).toPath()); inputStream.close(); tempFilesCreated.add(s); } } } //create a script to copy the files into S3 List<String> copyScript = new ArrayList<>(); copyScript.add("#!/bin/bash"); copyScript.add(""); for (String s: tempFilesCreated) { String localFile = FilenameUtils.concat(tempDir, s); copyScript.add("sudo aws s3 cp " + localFile + " s3://discoverysftplanding/endeavour/" + s); } String scriptFile = FilenameUtils.concat(tempDir, "copy.sh"); FileUtils.writeLines(new File(scriptFile), copyScript); /*continueOrQuit(); //back up every file where the service was disabled for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { //first download from S3 to the local temp dir InputStream inputStream = FileHelper.readFileFromSharedStorage(file); String fileName = FilenameUtils.getName(file); String tempPath = FilenameUtils.concat(tempDir, fileName); File downloadDestination = new File(tempPath); Files.copy(inputStream, downloadDestination.toPath()); //then write back to S3 in a sub-dir of the original file String backupPath = FilenameUtils.getPath(file); backupPath = FilenameUtils.concat(backupPath, "Original"); backupPath = FilenameUtils.concat(backupPath, fileName); FileHelper.writeFileToSharedStorage(backupPath, downloadDestination); LOG.info("Backed up " + file + " -> " + backupPath); //delete from temp dir downloadDestination.delete(); } } continueOrQuit(); //copy the new CSV files into the dir where it was disabled List<String> disabledFiles = hmExchangeFiles.get(exchangeDisabled); for (String disabledFile: disabledFiles) { String fileType = findFileType(disabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected temp file " + f); } FileHelper.writeFileToSharedStorage(disabledFile, f); LOG.info("Copied " + tempFile + " -> " + disabledFile); } continueOrQuit(); //empty the patient files for any extracts while the service was disabled for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange otherExchangeDisabled = exchanges.get(i); List<String> otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled); for (String otherDisabledFile: otherDisabledFiles) { String fileType = findFileType(otherDisabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(otherDisabledFile, f); LOG.info("Copied " + tempFile + " -> " + otherDisabledFile); } } continueOrQuit(); //copy the content of the sharing agreement file from when it was re-bulked for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File downloadDestination = new File(tempFile); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile); Files.copy(inputStream, downloadDestination.toPath()); tempFilesCreated.add(tempFile); } } //replace the sharing agreement file for all disabled extracts with the non-disabled one for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(file, f); LOG.info("Copied " + tempFile + " -> " + file); } } } LOG.info("Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); continueOrQuit(); for (String tempFileCreated: tempFilesCreated) { File f = new File(tempFileCreated); if (f.exists()) { f.delete(); } }*/ } catch (Exception ex) { LOG.error("", ex); } } private static String findExtractDate(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); String name = FilenameUtils.getBaseName(file); String[] toks = name.split("_"); return toks[3]; } private static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); CSVRecord record = iterator.next(); String s = record.get("Disabled"); boolean disabled = Boolean.parseBoolean(s); return disabled; } finally { csvParser.close(); } } private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char)bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } private static String getGuidColumnName(String fileType) { if (fileType.equals("Admin_Patient")) { //patient file just has patient GUID, nothing extra return null; } else if (fileType.equals("CareRecord_Consultation")) { return "ConsultationGuid"; } else if (fileType.equals("CareRecord_Diary")) { return "DiaryGuid"; } else if (fileType.equals("CareRecord_Observation")) { return "ObservationGuid"; } else if (fileType.equals("CareRecord_Problem")) { //there is no separate problem GUID, as it's just a modified observation return "ObservationGuid"; } else if (fileType.equals("Prescribing_DrugRecord")) { return "DrugRecordGuid"; } else if (fileType.equals("Prescribing_IssueRecord")) { return "IssueRecordGuid"; } else { throw new IllegalArgumentException(fileType); } } private static String findFileType(String filePath) { String fileName = FilenameUtils.getName(filePath); String[] toks = fileName.split("_"); String domain = toks[1]; String name = toks[2]; return domain + "_" + name; } private static boolean isPatientFile(String fileType) { if (fileType.equals("Admin_Patient") || fileType.equals("CareRecord_Consultation") || fileType.equals("CareRecord_Diary") || fileType.equals("CareRecord_Observation") || fileType.equals("CareRecord_Problem") || fileType.equals("Prescribing_DrugRecord") || fileType.equals("Prescribing_IssueRecord")) { //note the referral file doesn't have a Deleted column, so isn't in this list return true; } else { return false; } } private static String findSharingAgreementFile(List<String> files) throws Exception { for (String file : files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { return file; } } throw new Exception("Failed to find sharing agreement file in " + files.get(0)); } private static void testSlack() { LOG.info("Testing slack"); try { SlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, "Test Message from Queue Reader"); LOG.info("Finished testing slack"); } catch (Exception ex) { LOG.error("", ex); } } private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); LOG.info("Posting to inbound exchange for " + service.getName() + " from file " + filePath); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); auditRepository.save(audit); } count ++; exchangeIdBatch.add(exchangeId); if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); LOG.info("Done " + count); } br.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); } /*private static void postToInbound(UUID serviceId, boolean all) { LOG.info("Posting to inbound for " + serviceId); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); List<UUID> systemIds = findSystemIds(service); UUID systemId = systemIds.get(0); ExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId); for (UUID exchangeId: errorState.getExchangeIdsInError()) { //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); //skip any exchange IDs we've already re-queued up to be processed again if (audit.isResubmitted()) { LOG.debug("Not re-posting " + audit.getExchangeId() + " as it's already been resubmitted"); continue; } LOG.debug("Re-posting " + audit.getExchangeId()); audit.setResubmitted(true); auditRepository.save(audit); //then re-submit the exchange to Rabbit MQ for the queue reader to pick up QueueHelper.postToExchange(exchangeId, "EdsInbound", null, false); if (!all) { LOG.info("Posted first exchange, so stopping"); break; } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); }*/ /*private static void fixPatientSearch(String serviceId) { LOG.info("Fixing patient search for " + serviceId); try { UUID serviceUuid = UUID.fromString(serviceId); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ParserPool parser = new ParserPool(); Set<UUID> patientsDone = new HashSet<>(); List<UUID> exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid); LOG.info("Found " + exchanges.size() + " exchanges"); for (UUID exchangeId: exchanges) { List<ExchangeBatch> batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); LOG.info("Found " + batches.size() + " batches in exchange " + exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } if (patientsDone.contains(patientId)) { continue; } ResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (wrapper != null) { String json = wrapper.getResourceData(); if (!Strings.isNullOrEmpty(json)) { Patient fhirPatient = (Patient) parser.parse(json); UUID systemUuid = wrapper.getSystemId(); patientSearchDal.update(serviceUuid, systemUuid, fhirPatient); } } patientsDone.add(patientId); if (patientsDone.size() % 1000 == 0) { LOG.info("Done " + patientsDone.size()); } } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished fixing patient search for " + serviceId); }*/ private static void runSql(String host, String username, String password, String sqlFile) { LOG.info("Running SQL on " + host + " from " + sqlFile); Connection conn = null; Statement statement = null; try { File f = new File(sqlFile); if (!f.exists()) { LOG.error("" + f + " doesn't exist"); return; } List<String> lines = FileUtils.readLines(f); /*String combined = String.join("\n", lines); LOG.info("Going to run SQL"); LOG.info(combined);*/ //load driver Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", username); props.setProperty("password", password); conn = DriverManager.getConnection(host, props); LOG.info("Opened connection"); statement = conn.createStatement(); long totalStart = System.currentTimeMillis(); for (String sql: lines) { sql = sql.trim(); if (sql.startsWith("--") || sql.startsWith("/*") || Strings.isNullOrEmpty(sql)) { continue; } LOG.info(""); LOG.info(sql); long start = System.currentTimeMillis(); boolean hasResultSet = statement.execute(sql); long end = System.currentTimeMillis(); LOG.info("SQL took " + (end - start) + "ms"); if (hasResultSet) { while (true) { ResultSet rs = statement.getResultSet(); int cols = rs.getMetaData().getColumnCount(); List<String> colHeaders = new ArrayList<>(); for (int i = 0; i < cols; i++) { String header = rs.getMetaData().getColumnName(i + 1); colHeaders.add(header); } String colHeaderStr = String.join(", ", colHeaders); LOG.info(colHeaderStr); while (rs.next()) { List<String> row = new ArrayList<>(); for (int i = 0; i < cols; i++) { Object o = rs.getObject(i + 1); if (rs.wasNull()) { row.add("<null>"); } else { row.add(o.toString()); } } String rowStr = String.join(", ", row); LOG.info(rowStr); } if (!statement.getMoreResults()) { break; } } } else { int updateCount = statement.getUpdateCount(); LOG.info("Updated " + updateCount + " Row(s)"); } } long totalEnd = System.currentTimeMillis(); LOG.info(""); LOG.info("Total time taken " + (totalEnd - totalStart) + "ms"); } catch (Throwable t) { LOG.error("", t); } finally { if (statement != null) { try { statement.close(); } catch (Exception ex) { } } if (conn != null) { try { conn.close(); } catch (Exception ex) { } } LOG.info("Closed connection"); } LOG.info("Finished Testing DB Size Limit"); } /*private static void fixExchangeBatches() { LOG.info("Starting Fixing Exchange Batches"); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); List<Service> services = serviceDalI.getAll(); for (Service service: services) { LOG.info("Doing " + service.getName()); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId()); for (UUID exchangeId: exchangeIds) { LOG.info(" Exchange " + exchangeId); List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } List<ResourceWrapper> resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId()); if (resources.isEmpty()) { continue; } ResourceWrapper first = resources.get(0); UUID patientId = first.getPatientId(); if (patientId != null) { exchangeBatch.setEdsPatientId(patientId); exchangeBatchDalI.save(exchangeBatch); LOG.info("Fixed batch " + exchangeBatch.getBatchId() + " -> " + exchangeBatch.getEdsPatientId()); } } } } LOG.info("Finished Fixing Exchange Batches"); } catch (Exception ex) { LOG.error("", ex); } }*/ /** * exports ADT Encounters for patients based on a CSV file produced using the below SQL --USE EDS DATABASE -- barts b5a08769-cbbe-4093-93d6-b696cd1da483 -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a create table adt_patients ( service_id character(36), system_id character(36), nhs_number character varying(10), patient_id character(36) ); -- delete from adt_patients; select * from patient_search limit 10; select * from patient_link limit 10; insert into adt_patients select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id from patient_search ps join patient_link pl on pl.patient_id = ps.patient_id join patient_link pl2 on pl.person_id = pl2.person_id join patient_search ps2 on ps2.patient_id = pl2.patient_id where ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a') and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a'); select count(1) from adt_patients limit 100; select * from adt_patients limit 100; ---MOVE TABLE TO HL7 RECEIVER DB select count(1) from adt_patients; -- top 1000 patients with messages select * from mapping.resource_uuid where resource_type = 'Patient' limit 10; select * from log.message limit 10; create table adt_patient_counts ( nhs_number character varying(100), count int ); insert into adt_patient_counts select pid1, count(1) from log.message where pid1 is not null and pid1 <> '' group by pid1; select * from adt_patient_counts order by count desc limit 100; alter table adt_patients add count int; update adt_patients set count = adt_patient_counts.count from adt_patient_counts where adt_patients.nhs_number = adt_patient_counts.nhs_number; select count(1) from adt_patients where nhs_number is null; select * from adt_patients where nhs_number is not null and count is not null order by count desc limit 1000; */ /*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) { LOG.info("Exporting HL7 Encounters from " + sourceCsvPath + " to " + outputPath); try { File sourceFile = new File(sourceCsvPath); CSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); //"service_id","system_id","nhs_number","patient_id","count" int count = 0; HashMap<UUID, List<UUID>> serviceAndSystemIds = new HashMap<>(); HashMap<UUID, Integer> patientIds = new HashMap<>(); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); count ++; String serviceId = csvRecord.get("service_id"); String systemId = csvRecord.get("system_id"); String patientId = csvRecord.get("patient_id"); UUID serviceUuid = UUID.fromString(serviceId); List<UUID> systemIds = serviceAndSystemIds.get(serviceUuid); if (systemIds == null) { systemIds = new ArrayList<>(); serviceAndSystemIds.put(serviceUuid, systemIds); } systemIds.add(UUID.fromString(systemId)); patientIds.put(UUID.fromString(patientId), new Integer(count)); } csvParser.close(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ParserPool parser = new ParserPool(); Map<Integer, List<Object[]>> patientRows = new HashMap<>(); SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (UUID serviceId: serviceAndSystemIds.keySet()) { //List<UUID> systemIds = serviceAndSystemIds.get(serviceId); Service service = serviceDalI.getById(serviceId); String serviceName = service.getName(); LOG.info("Doing service " + serviceId + " " + serviceName); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId); LOG.info("Got " + exchangeIds.size() + " exchange IDs to scan"); int exchangeCount = 0; for (UUID exchangeId: exchangeIds) { exchangeCount ++; if (exchangeCount % 1000 == 0) { LOG.info("Done " + exchangeCount + " exchanges"); } List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { UUID patientId = exchangeBatch.getEdsPatientId(); if (patientId != null && !patientIds.containsKey(patientId)) { continue; } Integer patientIdInt = patientIds.get(patientId); //get encounters for exchange batch UUID batchId = exchangeBatch.getBatchId(); List<ResourceWrapper> resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper resourceWrapper: resourceWrappers) { if (resourceWrapper.isDeleted()) { continue; } String resourceType = resourceWrapper.getResourceType(); if (!resourceType.equals(ResourceType.Encounter.toString())) { continue; } LOG.info("Processing " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId()); String json = resourceWrapper.getResourceData(); Encounter fhirEncounter = (Encounter)parser.parse(json); Date date = null; if (fhirEncounter.hasPeriod()) { Period period = fhirEncounter.getPeriod(); if (period.hasStart()) { date = period.getStart(); } } String episodeId = null; if (fhirEncounter.hasEpisodeOfCare()) { Reference episodeReference = fhirEncounter.getEpisodeOfCare().get(0); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference); EpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirEpisode != null) { if (fhirEpisode.hasIdentifier()) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID); if (Strings.isNullOrEmpty(episodeId)) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID); } } } } String adtType = null; String adtCode = null; Extension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (extension != null) { CodeableConcept codeableConcept = (CodeableConcept) extension.getValue(); Coding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE); if (hl7MessageTypeCoding != null) { adtType = hl7MessageTypeCoding.getDisplay(); adtCode = hl7MessageTypeCoding.getCode(); } } else { //for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body try { Exchange exchange = exchangeDalI.getExchange(exchangeId); String exchangeBody = exchange.getBody(); Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody); for (Bundle.BundleEntryComponent entry: bundle.getEntry()) { if (entry.getResource() != null && entry.getResource() instanceof MessageHeader) { MessageHeader header = (MessageHeader)entry.getResource(); if (header.hasEvent()) { Coding coding = header.getEvent(); adtType = coding.getDisplay(); adtCode = coding.getCode(); } } } } catch (Exception ex) { //if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them } } String cls = null; if (fhirEncounter.hasClass_()) { Encounter.EncounterClass encounterClass = fhirEncounter.getClass_(); if (encounterClass == Encounter.EncounterClass.OTHER && fhirEncounter.hasClass_Element() && fhirEncounter.getClass_Element().hasExtension()) { for (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) { if (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) { //not 100% of the type of the value, so just append to a String cls = "" + classExtension.getValue(); } } } if (Strings.isNullOrEmpty(cls)) { cls = encounterClass.toCode(); } } String type = null; if (fhirEncounter.hasType()) { //only seem to ever have one type CodeableConcept codeableConcept = fhirEncounter.getType().get(0); type = codeableConcept.getText(); } String status = null; if (fhirEncounter.hasStatus()) { Encounter.EncounterState encounterState = fhirEncounter.getStatus(); status = encounterState.toCode(); } String location = null; String locationType = null; if (fhirEncounter.hasLocation()) { //first location is always the current location Encounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0); if (encounterLocation.hasLocation()) { Reference locationReference = encounterLocation.getLocation(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference); Location fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirLocation != null) { if (fhirLocation.hasName()) { location = fhirLocation.getName(); } if (fhirLocation.hasType()) { CodeableConcept typeCodeableConcept = fhirLocation.getType(); if (typeCodeableConcept.hasCoding()) { Coding coding = typeCodeableConcept.getCoding().get(0); locationType = coding.getDisplay(); } } } } } String clinician = null; if (fhirEncounter.hasParticipant()) { //first participant seems to be the interesting one Encounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0); if (encounterParticipant.hasIndividual()) { Reference practitionerReference = encounterParticipant.getIndividual(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference); Practitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirPractitioner != null) { if (fhirPractitioner.hasName()) { HumanName name = fhirPractitioner.getName(); clinician = name.getText(); if (Strings.isNullOrEmpty(clinician)) { clinician = ""; for (StringType s: name.getPrefix()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getGiven()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getFamily()) { clinician += s.getValueNotNull(); clinician += " "; } clinician = clinician.trim(); } } } } } Object[] row = new Object[12]; row[0] = serviceName; row[1] = patientIdInt.toString(); row[2] = sdfOutput.format(date); row[3] = episodeId; row[4] = adtCode; row[5] = adtType; row[6] = cls; row[7] = type; row[8] = status; row[9] = location; row[10] = locationType; row[11] = clinician; List<Object[]> rows = patientRows.get(patientIdInt); if (rows == null) { rows = new ArrayList<>(); patientRows.put(patientIdInt, rows); } rows.add(row); } } } } String[] outputColumnHeaders = new String[] {"Source", "Patient", "Date", "Episode ID", "ADT Message Code", "ADT Message Type", "Class", "Type", "Status", "Location", "Location Type", "Clinician"}; FileWriter fileWriter = new FileWriter(outputPath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader(outputColumnHeaders) .withQuote('"'); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); for (int i=0; i <= count; i++) { Integer patientIdInt = new Integer(i); List<Object[]> rows = patientRows.get(patientIdInt); if (rows != null) { for (Object[] row: rows) { csvPrinter.printRecord(row); } } } csvPrinter.close(); bufferedWriter.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Exporting Encounters from " + sourceCsvPath + " to " + outputPath); }*/ /*private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info(""); try { Thread.sleep(5000); } catch (Throwable ex) { LOG.error("", ex); } LOG.info("Done"); } }); }*/ private static void findEmisStartDates(String path, String outputPath) { LOG.info("Finding EMIS Start Dates in " + path + ", writing to " + outputPath); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm.ss"); Map<String, Date> startDates = new HashMap<>(); Map<String, String> servers = new HashMap<>(); Map<String, String> names = new HashMap<>(); Map<String, String> odsCodes = new HashMap<>(); Map<String, String> cdbNumbers = new HashMap<>(); Map<String, Set<String>> distinctPatients = new HashMap<>(); File root = new File(path); for (File sftpRoot: root.listFiles()) { LOG.info("Checking " + sftpRoot); Map<Date, File> extracts = new HashMap<>(); List<Date> extractDates = new ArrayList<>(); for (File extractRoot: sftpRoot.listFiles()) { Date d = sdf.parse(extractRoot.getName()); //LOG.info("" + extractRoot.getName() + " -> " + d); extracts.put(d, extractRoot); extractDates.add(d); } Collections.sort(extractDates); for (Date extractDate: extractDates) { File extractRoot = extracts.get(extractDate); LOG.info("Checking " + extractRoot); //read the sharing agreements file //e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv File sharingAgreementsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("agreements_sharingorganisation") > -1 && name.endsWith(".csv")) { sharingAgreementsFile = f; break; } } if (sharingAgreementsFile == null) { LOG.info("Null agreements file for " + extractRoot); continue; } CSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String activated = csvRecord.get("IsActivated"); String disabled = csvRecord.get("Disabled"); servers.put(orgGuid, sftpRoot.getName()); if (activated.equalsIgnoreCase("true")) { if (disabled.equalsIgnoreCase("false")) { Date d = sdf.parse(extractRoot.getName()); Date existingDate = startDates.get(orgGuid); if (existingDate == null) { startDates.put(orgGuid, d); } } else { if (startDates.containsKey(orgGuid)) { startDates.put(orgGuid, null); } } } } } finally { csvParser.close(); } //go through orgs file to get name, ods and cdb codes File orgsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_organisation_") > -1 && name.endsWith(".csv")) { orgsFile = f; break; } } csvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String name = csvRecord.get("OrganisationName"); String odsCode = csvRecord.get("ODSCode"); String cdb = csvRecord.get("CDB"); names.put(orgGuid, name); odsCodes.put(orgGuid, odsCode); cdbNumbers.put(orgGuid, cdb); } } finally { csvParser.close(); } //go through patients file to get count File patientFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_patient_") > -1 && name.endsWith(".csv")) { patientFile = f; break; } } csvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String patientGuid = csvRecord.get("PatientGuid"); String deleted = csvRecord.get("Deleted"); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); if (distinctPatientSet == null) { distinctPatientSet = new HashSet<>(); distinctPatients.put(orgGuid, distinctPatientSet); } if (deleted.equalsIgnoreCase("true")) { distinctPatientSet.remove(patientGuid); } else { distinctPatientSet.add(patientGuid); } } } finally { csvParser.close(); } } } SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd"); StringBuilder sb = new StringBuilder(); sb.append("Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients"); for (String orgGuid: startDates.keySet()) { Date startDate = startDates.get(orgGuid); String server = servers.get(orgGuid); String name = names.get(orgGuid); String odsCode = odsCodes.get(orgGuid); String cdbNumber = cdbNumbers.get(orgGuid); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); String startDateDesc = null; if (startDate != null) { startDateDesc = sdfOutput.format(startDate); } Long countDistinctPatients = null; if (distinctPatientSet != null) { countDistinctPatients = new Long(distinctPatientSet.size()); } sb.append("\n"); sb.append("\"" + name + "\""); sb.append(","); sb.append("\"" + odsCode + "\""); sb.append(","); sb.append("\"" + cdbNumber + "\""); sb.append(","); sb.append("\"" + orgGuid + "\""); sb.append(","); sb.append(startDateDesc); sb.append(","); sb.append("\"" + server + "\""); sb.append(","); sb.append(countDistinctPatients); } LOG.info(sb.toString()); FileUtils.writeStringToFile(new File(outputPath), sb.toString()); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Finding Start Dates in " + path + ", writing to " + outputPath); } private static void findEncounterTerms(String path, String outputPath) { LOG.info("Finding Encounter Terms from " + path); Map<String, Long> hmResults = new HashMap<>(); //source term, source term snomed ID, source term snomed term - count try { File root = new File(path); File[] files = root.listFiles(); for (File readerRoot: files) { //emis001 LOG.info("Finding terms in " + readerRoot); //first read in all the coding files to build up our map of codes Map<String, String> hmCodes = new HashMap<>(); for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for codes in " + dateFolder); File f = findFile(dateFolder, "Coding_ClinicalCode"); if (f == null) { LOG.error("Failed to find coding file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String codeId = csvRecord.get("CodeId"); String term = csvRecord.get("Term"); String snomed = csvRecord.get("SnomedCTConceptId"); hmCodes.put(codeId, snomed + ",\"" + term + "\""); } csvParser.close(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date cutoff = dateFormat.parse("2017-01-01"); //now process the consultation files themselves for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for consultations in " + dateFolder); File f = findFile(dateFolder, "CareRecord_Consultation"); if (f == null) { LOG.error("Failed to find consultation file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String term = csvRecord.get("ConsultationSourceTerm"); String codeId = csvRecord.get("ConsultationSourceCodeId"); if (Strings.isNullOrEmpty(term) && Strings.isNullOrEmpty(codeId)) { continue; } String date = csvRecord.get("EffectiveDate"); if (Strings.isNullOrEmpty(date)) { continue; } Date d = dateFormat.parse(date); if (d.before(cutoff)) { continue; } String line = "\"" + term + "\","; if (!Strings.isNullOrEmpty(codeId)) { String codeLookup = hmCodes.get(codeId); if (codeLookup == null) { LOG.error("Failed to find lookup for codeID " + codeId); continue; } line += codeLookup; } else { line += ","; } Long count = hmResults.get(line); if (count == null) { count = new Long(1); } else { count = new Long(count.longValue() + 1); } hmResults.put(line, count); } csvParser.close(); } } //save results to file StringBuilder output = new StringBuilder(); output.append("\"consultation term\",\"snomed concept ID\",\"snomed term\",\"count\""); output.append("\r\n"); for (String line: hmResults.keySet()) { Long count = hmResults.get(line); String combined = line + "," + count; output.append(combined); output.append("\r\n"); } LOG.info("FInished"); LOG.info(output.toString()); FileUtils.writeStringToFile(new File(outputPath), output.toString()); LOG.info("written output to " + outputPath); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished finding Encounter Terms from " + path); } private static File findFile(File root, String token) throws Exception { for (File f: root.listFiles()) { String s = f.getName(); if (s.indexOf(token) > -1) { return f; } } return null; } /*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) { LOG.info("Starting Populating Protocol Queue for " + serviceIdStr); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); if (serviceIdStr.equalsIgnoreCase("All")) { serviceIdStr = null; } try { List<Service> services = new ArrayList<>(); if (Strings.isNullOrEmpty(serviceIdStr)) { services = serviceRepository.getAll(); } else { UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); services.add(service); } for (Service service: services) { List<UUID> exchangeIds = auditRepository.getExchangeIdsForService(service.getId()); LOG.info("Found " + exchangeIds.size() + " exchangeIds for " + service.getName()); if (startingExchangeId != null) { UUID startingExchangeUuid = UUID.fromString(startingExchangeId); if (exchangeIds.contains(startingExchangeUuid)) { //if in the list, remove everything up to and including the starting exchange int index = exchangeIds.indexOf(startingExchangeUuid); LOG.info("Found starting exchange " + startingExchangeId + " at " + index + " so removing up to this point"); for (int i=index; i>=0; i--) { exchangeIds.remove(i); } startingExchangeId = null; } else { //if not in the list, skip all these exchanges LOG.info("List doesn't contain starting exchange " + startingExchangeId + " so skipping"); continue; } } QueueHelper.postToExchange(exchangeIds, "edsProtocol", null, true); } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Populating Protocol Queue for " + serviceIdStr); }*/ /*private static void findDeletedOrgs() { LOG.info("Starting finding deleted orgs"); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); List<Service> services = new ArrayList<>(); try { for (Service service: serviceRepository.getAll()) { services.add(service); } } catch (Exception ex) { LOG.error("", ex); } services.sort((o1, o2) -> { String name1 = o1.getName(); String name2 = o2.getName(); return name1.compareToIgnoreCase(name2); }); for (Service service: services) { try { UUID serviceUuid = service.getId(); List<Exchange> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date()); LOG.info("Service: " + service.getName() + " " + service.getLocalId()); if (exchangeByServices.isEmpty()) { LOG.info(" no exchange found!"); continue; } Exchange exchangeByService = exchangeByServices.get(0); UUID exchangeId = exchangeByService.getId(); Exchange exchange = auditRepository.getExchange(exchangeId); Map<String, String> headers = exchange.getHeaders(); String systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid); UUID systemUuid = UUID.fromString(systemUuidStr); int batches = countBatches(exchangeId, serviceUuid, systemUuid); LOG.info(" Most recent exchange had " + batches + " batches"); if (batches > 1 && batches < 2000) { continue; } //go back until we find the FIRST exchange where it broke exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date()); for (int i=0; i<exchangeByServices.size(); i++) { exchangeByService = exchangeByServices.get(i); exchangeId = exchangeByService.getId(); batches = countBatches(exchangeId, serviceUuid, systemUuid); exchange = auditRepository.getExchange(exchangeId); Date timestamp = exchange.getTimestamp(); if (batches < 1 || batches > 2000) { LOG.info(" " + timestamp + " had " + batches); } if (batches > 1 && batches < 2000) { LOG.info(" " + timestamp + " had " + batches); break; } } } catch (Exception ex) { LOG.error("", ex); } } LOG.info("Finished finding deleted orgs"); }*/ private static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception { int batches = 0; ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { if (audit.getNumberBatchesCreated() != null) { batches += audit.getNumberBatchesCreated(); } } return batches; } /*private static void fixExchanges(UUID justThisService) { LOG.info("Fixing exchanges"); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId : exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } boolean changed = false; String body = exchange.getBody(); String[] files = body.split("\n"); if (files.length == 0) { continue; } for (int i=0; i<files.length; i++) { String original = files[i]; //remove /r characters String trimmed = original.trim(); //add the new prefix if (!trimmed.startsWith("sftpreader/EMIS001/")) { trimmed = "sftpreader/EMIS001/" + trimmed; } if (!original.equals(trimmed)) { files[i] = trimmed; changed = true; } } if (changed) { LOG.info("Fixed exchange " + exchangeId); LOG.info(body); body = String.join("\n", files); exchange.setBody(body); AuditWriter.writeExchange(exchange); } } } LOG.info("Fixed exchanges"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void deleteDataForService(UUID serviceId) { Service dbService = new ServiceRepository().getById(serviceId); //the delete will take some time, so do the delete in a separate thread LOG.info("Deleting all data for service " + dbService.getName() + " " + dbService.getId()); FhirDeletionService deletor = new FhirDeletionService(dbService); try { deletor.deleteData(); LOG.info("Completed deleting all data for service " + dbService.getName() + " " + dbService.getId()); } catch (Exception ex) { LOG.error("Error deleting service " + dbService.getName() + " " + dbService.getId(), ex); } }*/ /*private static void fixProblems(UUID serviceId, String sharedStoragePath, boolean testMode) { LOG.info("Fixing problems for service " + serviceId); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); List<ExchangeByService> exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE); //go backwards as the most recent is first for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); UUID exchangeId = exchangeByService.getExchangeId(); LOG.info("Doing exchange " + exchangeId); EmisCsvHelper helper = null; try { Exchange exchange = AuditWriter.readExchange(exchangeId); String exchangeBody = exchange.getBody(); String[] files = exchangeBody.split(java.lang.System.lineSeparator()); File orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files); Map<Class, AbstractCsvParser> allParsers = new HashMap<>(); String properVersion = null; String[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4}; for (String version: versions) { try { List<AbstractCsvParser> parsers = new ArrayList<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers); for (AbstractCsvParser parser: parsers) { Class cls = parser.getClass(); allParsers.put(cls, parser); } properVersion = version; } catch (Exception ex) { //ignore } } if (allParsers.isEmpty()) { throw new Exception("Failed to open parsers for exchange " + exchangeId + " in folder " + orgDirectory); } UUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid); //FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10); if (helper == null) { helper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values()))); } ObservationPreTransformer.transform(properVersion, allParsers, null, helper); IssueRecordPreTransformer.transform(properVersion, allParsers, null, helper); DrugRecordPreTransformer.transform(properVersion, allParsers, null, helper); Map<String, List<String>> problemChildren = helper.getProblemChildMap(); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (Map.Entry<String, List<String>> entry : problemChildren.entrySet()) { String patientLocallyUniqueId = entry.getKey().split(":")[0]; UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId); if (edsPatientId == null) { throw new Exception("Failed to find edsPatientId for local Patient ID " + patientLocallyUniqueId + " in exchange " + exchangeId); } //find the batch ID for our patient UUID batchId = null; for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null && exchangeBatch.getEdsPatientId().equals(edsPatientId)) { batchId = exchangeBatch.getBatchId(); break; } } if (batchId == null) { throw new Exception("Failed to find batch ID for eds Patient ID " + edsPatientId + " in exchange " + exchangeId); } //find the EDS ID for our problem UUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey()); if (edsProblemId == null) { LOG.warn("No edsProblemId found for local ID " + entry.getKey() + " - assume bad data referring to non-existing problem?"); //throw new Exception("Failed to find edsProblemId for local Patient ID " + problemLocallyUniqueId + " in exchange " + exchangeId); } //convert our child IDs to EDS references List<Reference> references = new ArrayList<>(); HashSet<String> contentsSet = new HashSet<>(); contentsSet.addAll(entry.getValue()); for (String referenceValue : contentsSet) { Reference reference = ReferenceHelper.createReference(referenceValue); ReferenceComponents components = ReferenceHelper.getReferenceComponents(reference); String locallyUniqueId = components.getId(); ResourceType resourceType = components.getResourceType(); UUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); Reference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString()); references.add(globallyUniqueReference); } //find the resource for the problem itself ResourceByExchangeBatch problemResourceByExchangeBatch = null; List<ResourceByExchangeBatch> resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString()); for (ResourceByExchangeBatch resourceByExchangeBatch: resources) { if (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) { problemResourceByExchangeBatch = resourceByExchangeBatch; break; } } if (problemResourceByExchangeBatch == null) { throw new Exception("Problem not found for edsProblemId " + edsProblemId + " for exchange " + exchangeId); } if (problemResourceByExchangeBatch.getIsDeleted()) { LOG.warn("Problem " + edsProblemId + " is deleted, so not adding to it for exchange " + exchangeId); continue; } String json = problemResourceByExchangeBatch.getResourceData(); Condition fhirProblem = (Condition)PARSER_POOL.parse(json); //update the problems if (fhirProblem.hasContained()) { if (fhirProblem.getContained().size() > 1) { throw new Exception("Problem " + edsProblemId + " is has " + fhirProblem.getContained().size() + " contained resources for exchange " + exchangeId); } fhirProblem.getContained().clear(); } List_ list = new List_(); list.setId("Items"); fhirProblem.getContained().add(list); Extension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE); if (extension == null) { Reference listReference = ReferenceHelper.createInternalReference("Items"); fhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference)); } for (Reference reference : references) { list.addEntry().setItem(reference); } String newJson = FhirSerializationHelper.serializeResource(fhirProblem); if (newJson.equals(json)) { LOG.warn("Skipping edsProblemId " + edsProblemId + " as JSON hasn't changed"); continue; } problemResourceByExchangeBatch.setResourceData(newJson); String resourceType = problemResourceByExchangeBatch.getResourceType(); UUID versionUuid = problemResourceByExchangeBatch.getVersion(); ResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid); problemResourceHistory.setResourceData(newJson); problemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); ResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId); if (problemResourceByService.getResourceData() == null) { problemResourceByService = null; LOG.warn("Not updating edsProblemId " + edsProblemId + " for exchange " + exchangeId + " as it's been subsequently delrted"); } else { problemResourceByService.setResourceData(newJson); } //save back to THREE tables if (!testMode) { resourceRepository.save(problemResourceByExchangeBatch); resourceRepository.save(problemResourceHistory); if (problemResourceByService != null) { resourceRepository.save(problemResourceByService); } LOG.info("Fixed edsProblemId " + edsProblemId + " for exchange Id " + exchangeId); } else { LOG.info("Would change edsProblemId " + edsProblemId + " to new JSON"); LOG.info(newJson); } } } catch (Exception ex) { LOG.error("Failed on exchange " + exchangeId, ex); break; } } LOG.info("Finished fixing problems for service " + serviceId); } private static String findDataSharingAgreementGuid(List<AbstractCsvParser> parsers) throws Exception { //we need a file name to work out the data sharing agreement ID, so just the first file we can find File f = parsers .iterator() .next() .getFile(); String name = Files.getNameWithoutExtension(f.getName()); String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + f.getName()); } return toks[4]; } private static void closeParsers(Collection<AbstractCsvParser> parsers) { for (AbstractCsvParser parser : parsers) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } private static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception { String organisationDir = null; for (String file: files) { File f = new File(sharedStoragePath, file); if (!f.exists()) { LOG.error("Failed to find file {} in shared storage {}", file, sharedStoragePath); throw new FileNotFoundException("" + f + " doesn't exist"); } //LOG.info("Successfully found file {} in shared storage {}", file, sharedStoragePath); try { File orgDir = f.getParentFile(); if (organisationDir == null) { organisationDir = orgDir.getAbsolutePath(); } else { if (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) { throw new Exception(); } } } catch (Exception ex) { throw new FileNotFoundException("" + f + " isn't in the expected directory structure within " + organisationDir); } } return new File(organisationDir); }*/ /*private static void testLogging() { while (true) { System.out.println("Checking logging at " + System.currentTimeMillis()); try { Thread.sleep(4000); } catch (Exception e) { e.printStackTrace(); } LOG.trace("trace logging"); LOG.debug("debug logging"); LOG.info("info logging"); LOG.warn("warn logging"); LOG.error("error logging"); } } */ /*private static void fixExchangeProtocols() { LOG.info("Fixing exchange protocols"); AuditRepository auditRepository = new AuditRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.Exchange LIMIT 1000;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); LOG.info("Processing exchange " + exchangeId); Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); List<String> newIds = new ArrayList<>(); String protocolJson = headers.get(HeaderKeys.Protocols); if (!headers.containsKey(HeaderKeys.Protocols)) { try { List<LibraryItem> libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr); // Get protocols where service is publisher newIds = libraryItemList.stream() .filter( libraryItem -> libraryItem.getProtocol().getServiceContract().stream() .anyMatch(sc -> sc.getType().equals(ServiceContractType.PUBLISHER) && sc.getService().getUuid().equals(serviceIdStr))) .map(t -> t.getUuid().toString()) .collect(Collectors.toList()); } catch (Exception e) { LOG.error("Failed to find protocols for exchange " + exchange.getExchangeId(), e); continue; } } else { try { JsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson); for (int i = 0; i < node.size(); i++) { JsonNode libraryItemNode = node.get(i); JsonNode idNode = libraryItemNode.get("uuid"); String id = idNode.asText(); newIds.add(id); } } catch (Exception e) { LOG.error("Failed to read Json from " + protocolJson + " for exchange " + exchange.getExchangeId(), e); continue; } } try { if (newIds.isEmpty()) { headers.remove(HeaderKeys.Protocols); } else { String protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray()); headers.put(HeaderKeys.Protocols, protocolsJson); } } catch (JsonProcessingException e) { LOG.error("Unable to serialize protocols to JSON for exchange " + exchange.getExchangeId(), e); continue; } try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); } catch (JsonProcessingException e) { LOG.error("Failed to write exchange headers to Json for exchange " + exchange.getExchangeId(), e); continue; } auditRepository.save(exchange); } LOG.info("Finished fixing exchange protocols"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } if (headers.containsKey(HeaderKeys.SenderLocalIdentifier) && headers.containsKey(HeaderKeys.SenderOrganisationUuid)) { continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); Map<UUID, String> orgMap = service.getOrganisations(); if (orgMap.size() != 1) { LOG.error("Wrong number of orgs in service " + serviceId + " for exchange " + exchange.getExchangeId()); continue; } UUID orgId = orgMap .keySet() .stream() .collect(StreamExtension.firstOrNullCollector()); Organisation organisation = organisationRepository.getById(orgId); String odsCode = organisation.getNationalId(); headers.put(HeaderKeys.SenderLocalIdentifier, odsCode); headers.put(HeaderKeys.SenderOrganisationUuid, orgId.toString()); try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Creating exchange " + exchange.getExchangeId()); } LOG.info("Finished fixing exchange headers"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); LibraryRepository libraryRepository = new LibraryRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } boolean changed = false; UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); try { List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint : endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface : system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid())) { if (!headers.containsKey(HeaderKeys.SourceSystem)) { headers.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat()); changed = true; } if (!headers.containsKey(HeaderKeys.SystemVersion)) { headers.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion()); changed = true; } if (!headers.containsKey(HeaderKeys.SenderSystemUuid)) { headers.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString()); changed = true; } } } } } catch (Exception e) { LOG.error("Failed to find endpoint details for " + exchange.getExchangeId()); continue; } if (changed) { try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Fixed exchange " + exchange.getExchangeId()); } } LOG.info("Finished fixing exchange headers"); }*/ /*private static void testConnection(String configName) { try { JsonNode config = ConfigManager.getConfigurationAsJson(configName, "enterprise"); String driverClass = config.get("driverClass").asText(); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName(driverClass); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void testConnection() { try { JsonNode config = ConfigManager.getConfigurationAsJson("postgres", "enterprise"); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception { LOG.info("Starting Enterprise Streaming for " + serviceId + " using " + configName + " starting from exchange " + exchangeIdStartFrom + " and batch " + batchIdStartFrom); LOG.info("Testing database connection"); testConnection(configName); Service service = new ServiceRepository().getById(serviceId); List<UUID> orgIds = new ArrayList<>(service.getOrganisations().keySet()); UUID orgId = orgIds.get(0); List<ExchangeByService> exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE); for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); //for (ExchangeByService exchangeByService: exchangeByServiceList) { UUID exchangeId = exchangeByService.getExchangeId(); if (exchangeIdStartFrom != null) { if (!exchangeIdStartFrom.equals(exchangeId)) { continue; } else { //once we have a match, set to null so we don't skip any subsequent ones exchangeIdStartFrom = null; } } Exchange exchange = AuditWriter.readExchange(exchangeId); String senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid); UUID senderOrgUuid = UUID.fromString(senderOrgUuidStr); //this one had 90,000 batches and doesn't need doing again *//*if (exchangeId.equals(UUID.fromString("b9b93be0-afd8-11e6-8c16-c1d5a00342f3"))) { LOG.info("Skipping exchange " + exchangeId); continue; }*//* List<ExchangeBatch> exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId); LOG.info("Processing exchange " + exchangeId + " with " + exchangeBatches.size() + " batches"); for (int j=0; j<exchangeBatches.size(); j++) { ExchangeBatch exchangeBatch = exchangeBatches.get(j); UUID batchId = exchangeBatch.getBatchId(); if (batchIdStartFrom != null) { if (!batchIdStartFrom.equals(batchId)) { continue; } else { batchIdStartFrom = null; } } LOG.info("Processing exchange " + exchangeId + " and batch " + batchId + " " + (j+1) + "/" + exchangeBatches.size()); try { String outbound = FhirToEnterpriseCsvTransformer.transformFromFhir(senderOrgUuid, batchId, null); if (!Strings.isNullOrEmpty(outbound)) { EnterpriseFiler.file(outbound, configName); } } catch (Exception ex) { throw new PipelineException("Failed to process exchange " + exchangeId + " and batch " + batchId, ex); } } } }*/ /*private static void fixMissingExchanges() { LOG.info("Fixing missing exchanges"); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id, batch_id, inserted_at FROM ehr.exchange_batch LIMIT 600000;"); stmt.setFetchSize(100); Set<UUID> exchangeIdsDone = new HashSet<>(); AuditRepository auditRepository = new AuditRepository(); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); UUID batchId = row.get(1, UUID.class); Date date = row.getTimestamp(2); //LOG.info("Exchange " + exchangeId + " batch " + batchId + " date " + date); if (exchangeIdsDone.contains(exchangeId)) { continue; } if (auditRepository.getExchange(exchangeId) != null) { continue; } UUID serviceId = findServiceId(batchId, session); if (serviceId == null) { continue; } Exchange exchange = new Exchange(); ExchangeByService exchangeByService = new ExchangeByService(); ExchangeEvent exchangeEvent = new ExchangeEvent(); Map<String, String> headers = new HashMap<>(); headers.put(HeaderKeys.SenderServiceUuid, serviceId.toString()); String headersJson = null; try { headersJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setBody("Body not available, as exchange re-created"); exchange.setExchangeId(exchangeId); exchange.setHeaders(headersJson); exchange.setTimestamp(date); exchangeByService.setExchangeId(exchangeId); exchangeByService.setServiceId(serviceId); exchangeByService.setTimestamp(date); exchangeEvent.setEventDesc("Created_By_Conversion"); exchangeEvent.setExchangeId(exchangeId); exchangeEvent.setTimestamp(new Date()); auditRepository.save(exchange); auditRepository.save(exchangeEvent); auditRepository.save(exchangeByService); exchangeIdsDone.add(exchangeId); LOG.info("Creating exchange " + exchangeId); } LOG.info("Finished exchange fix"); } private static UUID findServiceId(UUID batchId, Session session) { Statement stmt = new SimpleStatement("select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = " + batchId + " LIMIT 1;"); ResultSet rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_by_exchange_batch for batch_id " + batchId); return null; } Row row = rs.one(); String resourceType = row.getString(0); UUID resourceId = row.get(1, UUID.class); stmt = new SimpleStatement("select service_id from ehr.resource_history where resource_type = '" + resourceType + "' and resource_id = " + resourceId + " LIMIT 1;"); rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_history for resource_type " + resourceType + " and resource_id " + resourceId); return null; } row = rs.one(); UUID serviceId = row.get(0, UUID.class); return serviceId; }*/ /*private static void fixExchangeEvents() { List<ExchangeEvent> events = new AuditRepository().getAllExchangeEvents(); for (ExchangeEvent event: events) { if (event.getEventDesc() != null) { continue; } String eventDesc = ""; int eventType = event.getEvent().intValue(); switch (eventType) { case 1: eventDesc = "Receive"; break; case 2: eventDesc = "Validate"; break; case 3: eventDesc = "Transform_Start"; break; case 4: eventDesc = "Transform_End"; break; case 5: eventDesc = "Send"; break; default: eventDesc = "??? " + eventType; } event.setEventDesc(eventDesc); new AuditRepository().save(null, event); } }*/ /*private static void fixExchanges() { AuditRepository auditRepository = new AuditRepository(); Map<UUID, Set<UUID>> existingOnes = new HashMap(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); List<Exchange> exchanges = auditRepository.getAllExchanges(); for (Exchange exchange: exchanges) { UUID exchangeUuid = exchange.getExchangeId(); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeUuid + " and Json " + headerJson); continue; } *//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid); if (serviceId == null) { LOG.warn("No service ID found for exchange " + exchange.getExchangeId()); continue; } UUID serviceUuid = UUID.fromString(serviceId); Set<UUID> exchangeIdsDone = existingOnes.get(serviceUuid); if (exchangeIdsDone == null) { exchangeIdsDone = new HashSet<>(); List<ExchangeByService> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE); for (ExchangeByService exchangeByService: exchangeByServices) { exchangeIdsDone.add(exchangeByService.getExchangeId()); } existingOnes.put(serviceUuid, exchangeIdsDone); } //create the exchange by service entity if (!exchangeIdsDone.contains(exchangeUuid)) { Date timestamp = exchange.getTimestamp(); ExchangeByService newOne = new ExchangeByService(); newOne.setExchangeId(exchangeUuid); newOne.setServiceId(serviceUuid); newOne.setTimestamp(timestamp); auditRepository.save(newOne); }*//* try { headers.remove(HeaderKeys.BatchIdsJson); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } if (!headers.containsKey(HeaderKeys.BatchIdsJson)) { //fix the batch IDs not being in the exchange List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid); if (!batches.isEmpty()) { List<UUID> batchUuids = batches .stream() .map(t -> t.getBatchId()) .collect(Collectors.toList()); try { String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray()); headers.put(HeaderKeys.BatchIdsJson, batchUuidsStr); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange, null); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } } //} } }*/ /*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException { List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); LibraryRepository libraryRepository = new LibraryRepository(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface: system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid()) && technicalInterface.getMessageFormat().equalsIgnoreCase(software) && technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) { return endpointSystemId; } } } } catch (Exception e) { throw new PipelineException("Failed to process endpoints from service " + service.getId()); } return null; } */ /*private static void addSystemIdToExchangeHeaders() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) { LOG.info("Skipping exchange " + exchangeId + " as no service UUID"); continue; } if (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " as already got system UUID"); continue; } try { //work out service ID String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); UUID serviceId = UUID.fromString(serviceIdStr); String software = headers.get(HeaderKeys.SourceSystem); String version = headers.get(HeaderKeys.SystemVersion); Service service = serviceRepository.getById(serviceId); UUID systemUuid = findSystemId(service, software, version); headers.put(HeaderKeys.SenderSystemUuid, systemUuid.toString()); //work out protocol IDs try { String newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr); headers.put(HeaderKeys.ProtocolIds, newProtocolIdsJson); } catch (Exception ex) { LOG.error("Failed to recalculate protocols for " + exchangeId + ": " + ex.getMessage()); } //save to DB headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); auditRepository.save(exchange); } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); }*/ /*private static void populateExchangeBatchPatients() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); //ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid)) || Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " because no service or system in header"); continue; } try { UUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid)); UUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid)); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch : exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } UUID batchId = exchangeBatch.getBatchId(); List<ResourceByExchangeBatch> resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString()); if (resourceWrappers.isEmpty()) { continue; } List<UUID> patientIds = new ArrayList<>(); for (ResourceByExchangeBatch resourceWrapper : resourceWrappers) { UUID patientId = resourceWrapper.getResourceId(); if (resourceWrapper.getIsDeleted()) { deleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId); } if (!patientIds.contains(patientId)) { patientIds.add(patientId); } } if (patientIds.size() != 1) { LOG.info("Skipping exchange " + exchangeId + " and batch " + batchId + " because found " + patientIds.size() + " patient IDs"); continue; } UUID patientId = patientIds.get(0); exchangeBatch.setEdsPatientId(patientId); exchangeBatchRepository.save(exchangeBatch); } } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); } private static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception { FhirStorageService storageService = new FhirStorageService(serviceId, systemId); ResourceRepository resourceRepository = new ResourceRepository(); List<ResourceByPatient> resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId); for (ResourceByPatient resourceWrapper: resourceWrappers) { String json = resourceWrapper.getResourceData(); Resource resource = new JsonParser().parse(json); storageService.exchangeBatchDelete(exchangeId, batchId, resource); } }*/ /*private static void convertPatientSearch() { LOG.info("Converting Patient Search"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { EpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData()); String patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient()); ResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId)); if (Strings.isNullOrEmpty(patientWrapper.getResourceData())) { continue; } Patient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData()); PatientSearchHelper.update(serviceId, systemId, patient); PatientSearchHelper.update(serviceId, systemId, episodeOfCare); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Search"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static List<UUID> findSystemIds(Service service) throws Exception { List<UUID> ret = new ArrayList<>(); List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); ret.add(endpointSystemId); } } catch (Exception e) { throw new Exception("Failed to process endpoints from service " + service.getId()); } return ret; } /*private static void convertPatientLink() { LOG.info("Converting Patient Link"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { Patient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData()); PatientLinkHelper.updatePersonId(patient); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Link"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, ResourceHistory> resourcesFixed = new HashMap<>(); Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Set<UUID> batchIdsToPutInProtocolQueue = new HashSet<>(); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); ResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); ProblemPreTransformer.transform(version, parsers, filer, helper); ObservationPreTransformer.transform(version, parsers, filer, helper); DrugRecordPreTransformer.transform(version, parsers, filer, helper); IssueRecordPreTransformer.transform(version, parsers, filer, helper); DiaryPreTransformer.transform(version, parsers, filer, helper); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() && !patientParser.getDeleted()) { PatientTransformer.createResource(patientParser, filer, helper, version); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { ConsultationTransformer.createResource(consultationParser, filer, helper, version); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { ObservationTransformer.createResource(observationParser, filer, helper, version); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { DiaryTransformer.createResource(diaryParser, filer, helper, version); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { DrugRecordTransformer.createResource(drugRecordParser, filer, helper, version); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { IssueRecordTransformer.createResource(issueRecordParser, filer, helper, version); } } issueRecordParser.close(); filer.waitToFinish(); //just to close the thread pool, even though it's not been used List<Resource> resources = filer.getNewResources(); for (Resource resource: resources) { String patientId = IdHelper.getPatientId(resource); UUID edsPatientId = UUID.fromString(patientId); ResourceType resourceType = resource.getResourceType(); UUID resourceId = UUID.fromString(resource.getId()); boolean foundResourceInDbBatch = false; List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds != null) { for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; } foundResourceInDbBatch = true; for (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (!Strings.isNullOrEmpty(json)) { LOG.warn("JSON already in resource " + resourceType + " " + resourceId); } else { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); LOG.info("Saved resource by batch " + resourceType + " " + resourceId + " in batch " + batchId); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + resourceId + " and version " + versionUuid); } resourceHistory.setIsDeleted(false); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceHistory.setSchemaVersion("0.1"); resourceRepository.save(resourceByExchangeBatch); resourceRepository.save(resourceHistory); batchIdsToPutInProtocolQueue.add(batchId); String key = resourceType.toString() + ":" + resourceId; resourcesFixed.put(key, resourceHistory); } //if a patient became confidential, we will have deleted all resources for that //patient, so we need to undo that too //to undelete WHOLE patient record //1. if THIS resource is a patient //2. get all other deletes from the same exchange batch //3. delete those from resource_by_exchange_batch (the deleted ones only) //4. delete same ones from resource_history //5. retrieve most recent resource_history //6. if not deleted, add to resources fixed if (resourceType == ResourceType.Patient) { List<ResourceByExchangeBatch> resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId); LOG.info("Undeleting " + resourcesInSameBatch.size() + " resources for batch " + batchId); for (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) { if (!resourceInSameBatch.getIsDeleted()) { continue; } //patient and episode resources will be restored by the above stuff, so don't try //to do it again if (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString()) || resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion()); mapperResourceByExchangeBatch.delete(resourceInSameBatch); mapperResourceHistory.delete(deletedResourceHistory); batchIdsToPutInProtocolQueue.add(batchId); //check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table ResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId()); if (mostRecentDeletedResourceHistory != null && !mostRecentDeletedResourceHistory.getIsDeleted()) { String key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + ":" + mostRecentDeletedResourceHistory.getResourceId(); resourcesFixed.put(key2, mostRecentDeletedResourceHistory); } } } } } } //if we didn't find records in the DB to update, then if (!foundResourceInDbBatch) { //we can't generate a back-dated time UUID, but we need one so the resource_history //table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange, //and the batch ID is actually a time UUID that was allocated around the right time ExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId); //if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange //and we'll pick up the same patient data in a following exchange if (firstBatch == null) { continue; } UUID versionUuid = firstBatch.getBatchId(); //find suitable batch ID UUID batchId = null; if (batchIds != null && batchIds.size() > 0) { batchId = batchIds.get(batchIds.size()-1); } else { //create new batch ID if not found ExchangeBatch exchangeBatch = new ExchangeBatch(); exchangeBatch.setBatchId(UUIDs.timeBased()); exchangeBatch.setExchangeId(exchangeId); exchangeBatch.setInsertedAt(new Date()); exchangeBatch.setEdsPatientId(edsPatientId); exchangeBatchRepository.save(exchangeBatch); batchId = exchangeBatch.getBatchId(); //add to map for next resource if (batchIds == null) { batchIds = new ArrayList<>(); } batchIds.add(batchId); batchesPerPatient.put(edsPatientId, batchIds); } String json = parserPool.composeString(resource); ResourceHistory resourceHistory = new ResourceHistory(); resourceHistory.setResourceId(resourceId); resourceHistory.setResourceType(resourceType.toString()); resourceHistory.setVersion(versionUuid); resourceHistory.setCreatedAt(new Date()); resourceHistory.setServiceId(serviceId); resourceHistory.setSystemId(systemId); resourceHistory.setIsDeleted(false); resourceHistory.setSchemaVersion("0.1"); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); ResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch(); resourceByExchangeBatch.setBatchId(batchId); resourceByExchangeBatch.setExchangeId(exchangeId); resourceByExchangeBatch.setResourceType(resourceType.toString()); resourceByExchangeBatch.setResourceId(resourceId); resourceByExchangeBatch.setVersion(versionUuid); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); resourceByExchangeBatch.setResourceData(json); resourceRepository.save(resourceHistory); resourceRepository.save(resourceByExchangeBatch); batchIdsToPutInProtocolQueue.add(batchId); } } if (!batchIdsToPutInProtocolQueue.isEmpty()) { exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue); } } //update the resource_by_service table (and the resource_by_patient view) for (ResourceHistory resourceHistory: resourcesFixed.values()) { UUID latestVersionUpdatedUuid = resourceHistory.getVersion(); ResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId()); UUID latestVersionUuid = latestVersion.getVersion(); //if there have been subsequent updates to the resource, then skip it if (!latestVersionUuid.equals(latestVersionUpdatedUuid)) { continue; } Resource resource = parserPool.parse(resourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment)metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(resourceHistory.getServiceId()); resourceByService.setSystemId(resourceHistory.getSystemId()); resourceByService.setResourceType(resourceHistory.getResourceType()); resourceByService.setResourceId(resourceHistory.getResourceId()); resourceByService.setCurrentVersion(resourceHistory.getVersion()); resourceByService.setUpdatedAt(resourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(resourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(resourceHistory.getResourceData()); resourceRepository.save(resourceByService); //call out to our patient search and person matching services if (resource instanceof Patient) { PatientLinkHelper.updatePersonId((Patient)resource); PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource); } else if (resource instanceof EpisodeOfCare) { PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource); } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Fixing Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) { LOG.info("Fixing Deleted Appointments using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers); //find any deleted patients List<UUID> deletedPatientUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getDeleted()) { //find the EDS patient ID for this local guid String patientGuid = patientParser.getPatientGuid(); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } deletedPatientUuids.add(edsPatientId); } } patientParser.close(); //go through the appts file to find properly deleted appt GUIDS List<UUID> deletedApptUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class); while (apptParser.nextRecord()) { if (apptParser.getDeleted()) { String patientGuid = apptParser.getPatientGuid(); String slotGuid = apptParser.getSlotGuid(); if (!Strings.isNullOrEmpty(patientGuid)) { String uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid); UUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId); deletedApptUuids.add(edsApptId); } } } apptParser.close(); for (UUID edsPatientId : deletedPatientUuids) { List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; } for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString()); for (ResourceByExchangeBatch apptWrapper : apptWrappers) { //ignore non-deleted appts if (!apptWrapper.getIsDeleted()) { continue; } //if the appt was deleted legitamately, then skip it UUID apptId = apptWrapper.getResourceId(); if (deletedApptUuids.contains(apptId)) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion()); if (saveChanges) { mapperResourceByExchangeBatch.delete(apptWrapper); mapperResourceHistory.delete(deletedResourceHistory); } LOG.info("Un-deleted " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " in batch " + batchId + " patient " + edsPatientId); //now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table ResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId()); if (mostRecentResourceHistory != null && !mostRecentResourceHistory.getIsDeleted()) { Resource resource = parserPool.parse(mostRecentResourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment) metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(mostRecentResourceHistory.getServiceId()); resourceByService.setSystemId(mostRecentResourceHistory.getSystemId()); resourceByService.setResourceType(mostRecentResourceHistory.getResourceType()); resourceByService.setResourceId(mostRecentResourceHistory.getResourceId()); resourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion()); resourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(mostRecentResourceHistory.getResourceData()); if (saveChanges) { resourceRepository.save(resourceByService); } LOG.info("Restored " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " to resource_by_service table"); } } } } } } LOG.info("Finished Deleted Appointments Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixReviews(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Reviews using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, Long> problemCodes = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); LOG.info("Doing Emis CSV exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (problemParser.nextRecord()) { String patientGuid = problemParser.getPatientGuid(); String observationGuid = problemParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (!problemCodes.containsKey(key)) { problemCodes.put(key, null); } } problemParser.close(); while (observationParser.nextRecord()) { String patientGuid = observationParser.getPatientGuid(); String observationGuid = observationParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (problemCodes.containsKey(key)) { Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } problemCodes.put(key, codeId); } } observationParser.close(); LOG.info("Found " + problemCodes.size() + " problem codes so far"); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); while (observationParser.nextRecord()) { String problemGuid = observationParser.getProblemGuid(); if (!Strings.isNullOrEmpty(problemGuid)) { String patientGuid = observationParser.getPatientGuid(); Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } String key = patientGuid + ":" + problemGuid; Long problemCodeId = problemCodes.get(key); if (problemCodeId == null || problemCodeId.longValue() != codeId.longValue()) { continue; } //if here, our code is the same as the problem, so it's a review String locallyUniqueId = patientGuid + ":" + observationParser.getObservationGuid(); ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper); for (UUID systemId: systemIds) { UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } UUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); if (edsObservationId == null) { //try observations as diagnostic reports, because it could be one of those instead if (resourceType == ResourceType.Observation) { resourceType = ResourceType.DiagnosticReport; edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); } if (edsObservationId == null) { throw new Exception("Failed to find observation ID for service " + serviceId + " system " + systemId + " resourceType " + resourceType + " local ID " + locallyUniqueId); } } List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; //throw new Exception("Failed to find batch ID for patient " + edsPatientId + " in exchange " + exchangeId + " for resource " + resourceType + " " + edsObservationId); } for (UUID batchId: batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; //throw new Exception("No resources found for batch " + batchId + " resource type " + resourceType + " and resource id " + edsObservationId); } for (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (Strings.isNullOrEmpty(json)) { throw new Exception("No JSON in resource " + resourceType + " " + edsObservationId + " in batch " + batchId); } Resource resource = parserPool.parse(json); if (addReviewExtension((DomainResource)resource)) { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); LOG.info("Changed " + resourceType + " " + edsObservationId + " to have extension in batch " + batchId); resourceRepository.save(resourceByExchangeBatch); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + edsObservationId + " and version " + versionUuid); } resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceRepository.save(resourceHistory); ResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId); if (resourceByService != null) { UUID serviceVersionUuid = resourceByService.getCurrentVersion(); if (serviceVersionUuid.equals(versionUuid)) { resourceByService.setResourceData(json); resourceRepository.save(resourceByService); } } } else { LOG.info("" + resourceType + " " + edsObservationId + " already has extension"); } } } } //1. find out resource type originall saved from //2. retrieve from resource_by_exchange_batch //3. update resource in resource_by_exchange_batch //4. retrieve from resource_history //5. update resource_history //6. retrieve record from resource_by_service //7. if resource_by_service version UUID matches the resource_history updated, then update that too } } observationParser.close(); } } LOG.info("Finished Fixing Reviews"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static boolean addReviewExtension(DomainResource resource) { if (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) { return false; } Extension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true)); resource.addExtension(extension); return true; }*/ /*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Running Protocols for Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } //once we match the servce, set this to null to do all other services justThisService = null; LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<String> interestingPatientGuids = new ArrayList<>(); Map<UUID, Map<UUID, List<UUID>>> batchesPerPatientPerExchange = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } batchesPerPatientPerExchange.put(exchangeId, batchesPerPatient); File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() || patientParser.getDeleted()) { interestingPatientGuids.add(patientParser.getPatientGuid()); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { interestingPatientGuids.add(consultationParser.getPatientGuid()); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { interestingPatientGuids.add(observationParser.getPatientGuid()); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { interestingPatientGuids.add(diaryParser.getPatientGuid()); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { interestingPatientGuids.add(drugRecordParser.getPatientGuid()); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { interestingPatientGuids.add(issueRecordParser.getPatientGuid()); } } issueRecordParser.close(); } Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); for (String interestingPatientGuid: interestingPatientGuids) { if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + interestingPatientGuid); } for (UUID exchangeId: batchesPerPatientPerExchange.keySet()) { Map<UUID, List<UUID>> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId); List<UUID> batches = batchesPerPatient.get(edsPatientId); if (batches != null) { Set<UUID> batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId); if (batchesForExchange == null) { batchesForExchange = new HashSet<>(); exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange); } batchesForExchange.addAll(batches); } } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Running Protocols for Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixOrgs() { LOG.info("Posting orgs to protocol queue"); String[] orgIds = new String[]{ "332f31a2-7b28-47cb-af6f-18f65440d43d", "c893d66b-eb89-4657-9f53-94c5867e7ed9"}; ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); Map<UUID, Set<UUID>> exchangeBatches = new HashMap<>(); for (String orgId: orgIds) { LOG.info("Doing org ID " + orgId); UUID orgUuid = UUID.fromString(orgId); try { //select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING; ResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid); UUID batchId = resourceByExchangeBatch.getBatchId(); //select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING; ExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId); UUID exchangeId = exchangeBatch.getExchangeId(); Set<UUID> list = exchangeBatches.get(exchangeId); if (list == null) { list = new HashSet<>(); exchangeBatches.put(exchangeId, list); } list.add(batchId); } catch (Exception ex) { LOG.error("", ex); break; } } try { //find the config for our protocol queue (which is in the inbound config) String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatches.keySet()) { Set<UUID> batchIds = exchangeBatches.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } catch (Exception ex) { LOG.error("", ex); return; } LOG.info("Finished posting orgs to protocol queue"); }*/ /*private static void findCodes() { LOG.info("Finding missing codes"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID serviceId = row.get(0, UUID.class); UUID systemId = row.get(1, UUID.class); UUID exchangeId = row.get(2, UUID.class); UUID version = row.get(3, UUID.class); ExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version); String xml = audit.getErrorXml(); if (xml == null) { continue; } String codePrefix = "Failed to find clinical code CodeableConcept for codeId "; int codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " clinical code " + code + " from " + audit.getStarted()); continue; } codePrefix = "Failed to find medication CodeableConcept for codeId "; codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " drug code " + code + " from " + audit.getStarted()); continue; } } LOG.info("Finished finding missing codes"); }*/ private static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating TPP Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createTppSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating TPP Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createTppSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } //LOG.info("Doing dir " + sourceFile); createTppSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader(); CSVParser parser = new CSVParser(br, format); String filterColumn = null; Map<String, Integer> headerMap = parser.getHeaderMap(); if (headerMap.containsKey("IDPatient")) { filterColumn = "IDPatient"; } else if (name.equalsIgnoreCase("SRPatient.csv")) { filterColumn = "RowIdentifier"; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); /*} else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); copyFile(sourceFile, destFile); }*/ } } } private static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Vision Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createVisionSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating Vision Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createVisionSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createVisionSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; if (name.contains("encounter_data") || name.contains("journal_data") || name.contains("patient_data") || name.contains("referral_data")) { filterColumn = 0; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Adastra Subset"); try { Set<String> caseIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } //adastra extract files are all keyed on caseId caseIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createAdastraSubsetForFile(sourceDir, destDir, caseIds); LOG.info("Finished Creating Adastra Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createAdastraSubsetForFile(File sourceDir, File destDir, Set<String> caseIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createAdastraSubsetForFile(sourceFile, destFile, caseIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withDelimiter('|'); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //CaseRef column at 0 if (name.contains("NOTES") || name.contains("CASEQUESTIONS") || name.contains("OUTCOMES") || name.contains("CONSULTATION") || name.contains("CLINICALCODES") || name.contains("PRESCRIPTIONS") || name.contains("PATIENT")) { filterColumn = 0; } else if (name.contains("CASE")) { //CaseRef column at 2 filterColumn = 2; } else if (name.contains("PROVIDER")) { //CaseRef column at 7 filterColumn = 7; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String caseId = csvRecord.get(filterColumn); if (caseIds.contains(caseId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } } /*class ResourceFiler extends FhirResourceFiler { public ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError, List<UUID> batchIdsCreated, int maxFilingThreads) { super(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads); } private List<Resource> newResources = new ArrayList<>(); public List<Resource> getNewResources() { return newResources; } @Override public void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling saveAdminResource"); } @Override public void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deleteAdminResource"); } @Override public void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { for (Resource resource: resources) { if (mapIds) { IdHelper.mapIds(getServiceId(), getSystemId(), resource); } newResources.add(resource); } } @Override public void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deletePatientResource"); } }*/
src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.gson.JsonSyntaxException; import org.apache.commons.csv.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.fhir.PeriodHelper; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.FileInfo; import org.endeavourhealth.common.utility.JsonSerializer; import org.endeavourhealth.common.utility.SlackHelper; import org.endeavourhealth.core.configuration.ConfigDeserialiser; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.configuration.QueueReaderConfiguration; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirStorageService; import org.endeavourhealth.core.fhirStorage.JsonServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.transform.barts.BartsCsvToFhirTransformer; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.emis.csv.helpers.EmisCsvHelper; import org.hibernate.internal.SessionImpl; import org.hl7.fhir.instance.model.EpisodeOfCare; import org.hl7.fhir.instance.model.Patient; import org.hl7.fhir.instance.model.ResourceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.*; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws Exception { String configId = args[0]; LOG.info("Initialising config manager"); ConfigManager.initialize("queuereader", configId); /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixEncounters")) { String table = args[1]; fixEncounters(table); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("CreateAdastraSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createAdastraSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateVisionSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createVisionSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateTppSubset")) { String sourceDirPath = args[1]; String destDirPath = args[2]; String samplePatientsFile = args[3]; createTppSubset(sourceDirPath, destDirPath, samplePatientsFile); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("CreateBartsSubset")) { String sourceDirPath = args[1]; UUID serviceUuid = UUID.fromString(args[2]); UUID systemUuid = UUID.fromString(args[3]); String samplePatientsFile = args[4]; createBartsSubset(sourceDirPath, serviceUuid, systemUuid, samplePatientsFile); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsOrgs")) { String serviceId = args[1]; fixBartsOrgs(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestPreparedStatements")) { String url = args[1]; String user = args[2]; String pass = args[3]; String serviceId = args[4]; testPreparedStatements(url, user, pass, serviceId); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("ApplyEmisAdminCaches")) { applyEmisAdminCaches(); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixSubscribers")) { fixSubscriberDbs(); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("ConvertExchangeBody")) { String systemId = args[1]; convertExchangeBody(UUID.fromString(systemId)); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixReferrals")) { fixReferralRequests(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateNewSearchTable")) { String table = args[1]; populateNewSearchTable(table); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixBartsEscapes")) { String filePath = args[1]; fixBartsEscapedFiles(filePath); System.exit(0); }*/ if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; String systemId = args[2]; String filePath = args[3]; postToInboundFromFile(UUID.fromString(serviceId), UUID.fromString(systemId), filePath); System.exit(0); } if (args.length >= 1 && args[0].equalsIgnoreCase("FixDisabledExtract")) { String serviceId = args[1]; String systemId = args[2]; String sharedStoragePath = args[3]; String tempDir = args[4]; fixDisabledEmisExtract(serviceId, systemId, sharedStoragePath, tempDir); System.exit(0); } /*if (args.length >= 1 && args[0].equalsIgnoreCase("TestSlack")) { testSlack(); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PostToInbound")) { String serviceId = args[1]; boolean all = Boolean.parseBoolean(args[2]); postToInbound(UUID.fromString(serviceId), all); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixPatientSearch")) { String serviceId = args[1]; fixPatientSearch(serviceId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("Exit")) { String exitCode = args[1]; LOG.info("Exiting with error code " + exitCode); int exitCodeInt = Integer.parseInt(exitCode); System.exit(exitCodeInt); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("RunSql")) { String host = args[1]; String username = args[2]; String password = args[3]; String sqlFile = args[4]; runSql(host, username, password, sqlFile); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("PopulateProtocolQueue")) { String serviceId = null; if (args.length > 1) { serviceId = args[1]; } String startingExchangeId = null; if (args.length > 2) { startingExchangeId = args[2]; } populateProtocolQueue(serviceId, startingExchangeId); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEncounterTerms")) { String path = args[1]; String outputPath = args[2]; findEncounterTerms(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FindEmisStartDates")) { String path = args[1]; String outputPath = args[2]; findEmisStartDates(path, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("ExportHl7Encounters")) { String sourceCsvPpath = args[1]; String outputPath = args[2]; exportHl7Encounters(sourceCsvPpath, outputPath); System.exit(0); }*/ /*if (args.length >= 1 && args[0].equalsIgnoreCase("FixExchangeBatches")) { fixExchangeBatches(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindCodes")) { findCodes(); System.exit(0); }*/ /*if (args.length >= 0 && args[0].equalsIgnoreCase("FindDeletedOrgs")) { findDeletedOrgs(); System.exit(0); }*/ if (args.length != 1) { LOG.error("Usage: queuereader config_id"); return; } LOG.info("--------------------------------------------------"); LOG.info("EDS Queue Reader " + configId); LOG.info("--------------------------------------------------"); LOG.info("Fetching queuereader configuration"); String configXml = ConfigManager.getConfiguration(configId); QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); /*LOG.info("Registering shutdown hook"); registerShutdownHook();*/ // Instantiate rabbit handler LOG.info("Creating EDS queue reader"); RabbitHandler rabbitHandler = new RabbitHandler(configuration, configId); // Begin consume rabbitHandler.start(); LOG.info("EDS Queue reader running (kill file location " + TransformConfig.instance().getKillFileLocation() + ")"); } private static void convertExchangeBody(UUID systemUuid) { try { LOG.info("Converting exchange bodies for system " + systemUuid); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemUuid, Integer.MAX_VALUE); if (exchanges.isEmpty()) { continue; } LOG.debug("doing " + service.getName() + " with " + exchanges.size() + " exchanges"); for (Exchange exchange: exchanges) { String exchangeBody = exchange.getBody(); try { //already done ExchangePayloadFile[] files = JsonSerializer.deserialize(exchangeBody, ExchangePayloadFile[].class); continue; } catch (JsonSyntaxException ex) { //if the JSON can't be parsed, then it'll be the old format of body that isn't JSON } List<ExchangePayloadFile> newFiles = new ArrayList<>(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (String file: files) { ExchangePayloadFile fileObj = new ExchangePayloadFile(); String fileWithoutSharedStorage = file.substring(TransformConfig.instance().getSharedStoragePath().length()+1); fileObj.setPath(fileWithoutSharedStorage); //size List<FileInfo> fileInfos = FileHelper.listFilesInSharedStorageWithInfo(file); for (FileInfo info: fileInfos) { if (info.getFilePath().equals(file)) { long size = info.getSize(); fileObj.setSize(new Long(size)); } } //type if (systemUuid.toString().equalsIgnoreCase("991a9068-01d3-4ff2-86ed-249bd0541fb3") //live || systemUuid.toString().equalsIgnoreCase("55c08fa5-ef1e-4e94-aadc-e3d6adc80774")) { //dev //emis String name = FilenameUtils.getName(file); String[] toks = name.split("_"); String first = toks[1]; String second = toks[2]; fileObj.setType(first + "_" + second); } else if (systemUuid.toString().equalsIgnoreCase("e517fa69-348a-45e9-a113-d9b59ad13095")) { //cerner String name = FilenameUtils.getName(file); String type = BartsCsvToFhirTransformer.identifyFileType(name); fileObj.setType(type); } else { throw new Exception("Unknown system ID " + systemUuid); } newFiles.add(fileObj); } String json = JsonSerializer.serialize(newFiles); exchange.setBody(json); exchangeDal.save(exchange); } } LOG.info("Finished Converting exchange bodies for system " + systemUuid); } catch (Exception ex) { LOG.error("", ex); } } /*private static void fixBartsOrgs(String serviceId) { try { LOG.info("Fixing Barts orgs"); ResourceDalI dal = DalProvider.factoryResourceDal(); List<ResourceWrapper> wrappers = dal.getResourcesByService(UUID.fromString(serviceId), ResourceType.Organization.toString()); LOG.debug("Found " + wrappers.size() + " resources"); int done = 0; int fixed = 0; for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { List<ResourceWrapper> history = dal.getResourceHistory(UUID.fromString(serviceId), wrapper.getResourceType(), wrapper.getResourceId()); ResourceWrapper mostRecent = history.get(0); String json = mostRecent.getResourceData(); Organization org = (Organization)FhirSerializationHelper.deserializeResource(json); String odsCode = IdentifierHelper.findOdsCode(org); if (Strings.isNullOrEmpty(odsCode) && org.hasIdentifier()) { boolean hasBeenFixed = false; for (Identifier identifier: org.getIdentifier()) { if (identifier.getSystem().equals(FhirIdentifierUri.IDENTIFIER_SYSTEM_ODS_CODE) && identifier.hasId()) { odsCode = identifier.getId(); identifier.setValue(odsCode); identifier.setId(null); hasBeenFixed = true; } } if (hasBeenFixed) { String newJson = FhirSerializationHelper.serializeResource(org); mostRecent.setResourceData(newJson); LOG.debug("Fixed Organization " + org.getId()); *//*LOG.debug(json); LOG.debug(newJson);*//* saveResourceWrapper(UUID.fromString(serviceId), mostRecent); fixed ++; } } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done + ", Fixed " + fixed); } } LOG.debug("Done " + done + ", Fixed " + fixed); LOG.info("Finished Barts orgs"); } catch (Throwable t) { LOG.error("", t); } }*/ /*private static void testPreparedStatements(String url, String user, String pass, String serviceId) { try { LOG.info("Testing Prepared Statements"); LOG.info("Url: " + url); LOG.info("user: " + user); LOG.info("pass: " + pass); //open connection Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", user); props.setProperty("password", pass); Connection conn = DriverManager.getConnection(url, props); String sql = "SELECT * FROM internal_id_map WHERE service_id = ? AND id_type = ? AND source_id = ?"; long start = System.currentTimeMillis(); for (int i=0; i<10000; i++) { PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1, serviceId); ps.setString(2, "MILLPERSIDtoMRN"); ps.setString(3, UUID.randomUUID().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { //do nothing } } finally { if (ps != null) { ps.close(); } } } long end = System.currentTimeMillis(); LOG.info("Took " + (end-start) + " ms"); //close connection conn.close(); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixEncounters(String table) { LOG.info("Fixing encounters from " + table); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date cutoff = sdf.parse("2018-03-14 11:42"); EntityManager entityManager = ConnectionManager.getAdminEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<UUID> serviceIds = new ArrayList<>(); Map<UUID, UUID> hmSystems = new HashMap<>(); String sql = "SELECT service_id, system_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { UUID serviceId = UUID.fromString(rs.getString(1)); UUID systemId = UUID.fromString(rs.getString(2)); serviceIds.add(serviceId); hmSystems.put(serviceId, systemId); } rs.close(); statement.close(); entityManager.close(); for (UUID serviceId: serviceIds) { UUID systemId = hmSystems.get(serviceId); LOG.info("Doing service " + serviceId + " and system " + systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, systemId); List<UUID> exchangeIdsToProcess = new ArrayList<>(); for (UUID exchangeId: exchangeIds) { List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { Date d = audit.getStarted(); if (d.after(cutoff)) { exchangeIdsToProcess.add(exchangeId); break; } } } Map<String, ReferenceList> consultationNewChildMap = new HashMap<>(); Map<String, ReferenceList> observationChildMap = new HashMap<>(); Map<String, ReferenceList> newProblemChildren = new HashMap<>(); for (UUID exchangeId: exchangeIdsToProcess) { Exchange exchange = exchangeDal.getExchange(exchangeId); String[] files = ExchangeHelper.parseExchangeBodyIntoFileList(exchange.getBody()); String version = EmisCsvToFhirTransformer.determineVersion(files); List<String> interestingFiles = new ArrayList<>(); for (String file: files) { if (file.indexOf("CareRecord_Consultation") > -1 || file.indexOf("CareRecord_Observation") > -1 || file.indexOf("CareRecord_Diary") > -1 || file.indexOf("Prescribing_DrugRecord") > -1 || file.indexOf("Prescribing_IssueRecord") > -1 || file.indexOf("CareRecord_Problem") > -1) { interestingFiles.add(file); } } files = interestingFiles.toArray(new String[0]); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.createParsers(serviceId, systemId, exchangeId, files, version, parsers); String dataSharingAgreementGuid = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(parsers); EmisCsvHelper csvHelper = new EmisCsvHelper(serviceId, systemId, exchangeId, dataSharingAgreementGuid, true); Consultation consultationParser = (Consultation)parsers.get(Consultation.class); while (consultationParser.nextRecord()) { CsvCell consultationGuid = consultationParser.getConsultationGuid(); CsvCell patientGuid = consultationParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); consultationNewChildMap.put(sourceId, new ReferenceList()); } Problem problemParser = (Problem)parsers.get(Problem.class); while (problemParser.nextRecord()) { CsvCell problemGuid = problemParser.getObservationGuid(); CsvCell patientGuid = problemParser.getPatientGuid(); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); newProblemChildren.put(sourceId, new ReferenceList()); } //run this pre-transformer to pre-cache some stuff in the csv helper, which //is needed when working out the resource type that each observation would be saved as ObservationPreTransformer.transform(version, parsers, null, csvHelper); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { CsvCell observationGuid = observationParser.getObservationGuid(); CsvCell patientGuid = observationParser.getPatientGuid(); String obSourceId = EmisCsvHelper.createUniqueId(patientGuid, observationGuid); CsvCell codeId = observationParser.getCodeId(); if (codeId.isEmpty()) { continue; } ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); UUID obUuid = IdHelper.getEdsResourceId(serviceId, resourceType, obSourceId); if (obUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + resourceType + " and source ID " + obSourceId); //resourceType = ObservationTransformer.getTargetResourceType(observationParser, csvHelper); } Reference obReference = ReferenceHelper.createReference(resourceType, obUuid.toString()); CsvCell consultationGuid = observationParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell problemGuid = observationParser.getProblemGuid(); if (!problemGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(obReference); } CsvCell parentObGuid = observationParser.getParentObservationGuid(); if (!parentObGuid.isEmpty()) { String sourceId = EmisCsvHelper.createUniqueId(patientGuid, parentObGuid); ReferenceList referenceList = observationChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); observationChildMap.put(sourceId, referenceList); } referenceList.add(obReference); } } Diary diaryParser = (Diary)parsers.get(Diary.class); while (diaryParser.nextRecord()) { CsvCell consultationGuid = diaryParser.getConsultationGuid(); if (!consultationGuid.isEmpty()) { CsvCell diaryGuid = diaryParser.getDiaryGuid(); CsvCell patientGuid = diaryParser.getPatientGuid(); String diarySourceId = EmisCsvHelper.createUniqueId(patientGuid, diaryGuid); UUID diaryUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.ProcedureRequest, diarySourceId); if (diaryUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.ProcedureRequest + " and source ID " + diarySourceId); } Reference diaryReference = ReferenceHelper.createReference(ResourceType.ProcedureRequest, diaryUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, consultationGuid); ReferenceList referenceList = consultationNewChildMap.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); consultationNewChildMap.put(sourceId, referenceList); } referenceList.add(diaryReference); } } IssueRecord issueRecordParser = (IssueRecord)parsers.get(IssueRecord.class); while (issueRecordParser.nextRecord()) { CsvCell problemGuid = issueRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell issueRecordGuid = issueRecordParser.getIssueRecordGuid(); CsvCell patientGuid = issueRecordParser.getPatientGuid(); String issueRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, issueRecordGuid); UUID issueRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationOrder, issueRecordSourceId); if (issueRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationOrder + " and source ID " + issueRecordSourceId); } Reference issueRecordReference = ReferenceHelper.createReference(ResourceType.MedicationOrder, issueRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(issueRecordReference); } } DrugRecord drugRecordParser = (DrugRecord)parsers.get(DrugRecord.class); while (drugRecordParser.nextRecord()) { CsvCell problemGuid = drugRecordParser.getProblemObservationGuid(); if (!problemGuid.isEmpty()) { CsvCell drugRecordGuid = drugRecordParser.getDrugRecordGuid(); CsvCell patientGuid = drugRecordParser.getPatientGuid(); String drugRecordSourceId = EmisCsvHelper.createUniqueId(patientGuid, drugRecordGuid); UUID drugRecordUuid = IdHelper.getEdsResourceId(serviceId, ResourceType.MedicationStatement, drugRecordSourceId); if (drugRecordUuid == null) { continue; //LOG.error("Null observation UUID for resource type " + ResourceType.MedicationStatement + " and source ID " + drugRecordSourceId); } Reference drugRecordReference = ReferenceHelper.createReference(ResourceType.MedicationStatement, drugRecordUuid.toString()); String sourceId = EmisCsvHelper.createUniqueId(patientGuid, problemGuid); ReferenceList referenceList = newProblemChildren.get(sourceId); if (referenceList == null) { referenceList = new ReferenceList(); newProblemChildren.put(sourceId, referenceList); } referenceList.add(drugRecordReference); } } for (AbstractCsvParser parser : parsers.values()) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } ResourceDalI resourceDal = DalProvider.factoryResourceDal(); LOG.info("Found " + consultationNewChildMap.size() + " Encounters to fix"); for (String encounterSourceId: consultationNewChildMap.keySet()) { ReferenceList childReferences = consultationNewChildMap.get(encounterSourceId); //map to UUID UUID encounterId = IdHelper.getEdsResourceId(serviceId, ResourceType.Encounter, encounterSourceId); if (encounterId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Encounter.toString(), encounterId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Encounter " + encounterId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Encounter encounter = (Encounter) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Encounter encounter = (Encounter)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); EncounterBuilder encounterBuilder = new EncounterBuilder(encounter); ContainedListBuilder containedListBuilder = new ContainedListBuilder(encounterBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(encounter); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } LOG.info("Found " + observationChildMap.size() + " Parent Observations to fix"); for (String sourceId: observationChildMap.keySet()) { ReferenceList childReferences = observationChildMap.get(sourceId); //map to UUID ResourceType resourceType = null; UUID resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.Observation, sourceId); if (resourceId != null) { resourceType = ResourceType.Observation; } else { resourceId = IdHelper.getEdsResourceId(serviceId, ResourceType.DiagnosticReport, sourceId); if (resourceId != null) { resourceType = ResourceType.DiagnosticReport; } else { continue; } } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); if (history.isEmpty()) { //throw new Exception("Empty history for " + resourceType + " " + resourceId); continue; } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (resourceType == ResourceType.Observation) { if (wrapper.getResourceData() != null) { Observation observation = (Observation) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (observation.hasRelated()) { for (Observation.ObservationRelatedComponent related : observation.getRelated()) { Reference reference = related.getTarget(); childReferences.add(reference); } } } } else { if (wrapper.getResourceData() != null) { DiagnosticReport report = (DiagnosticReport) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); if (report.hasResult()) { for (Reference reference : report.getResult()) { childReferences.add(reference); } } } } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Resource resource = FhirSerializationHelper.deserializeResource(currentState.getResourceData()); boolean changed = false; if (resourceType == ResourceType.Observation) { ObservationBuilder resourceBuilder = new ObservationBuilder((Observation)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addChildObservation(reference)) { changed = true; } } } else { DiagnosticReportBuilder resourceBuilder = new DiagnosticReportBuilder((DiagnosticReport)resource); for (int i=0; i<childReferences.size(); i++) { Reference reference = childReferences.getReference(i); if (resourceBuilder.addResult(reference)) { changed = true; } } } if (changed) { String newJson = FhirSerializationHelper.serializeResource(resource); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); }*//* } LOG.info("Found " + newProblemChildren.size() + " Problems to fix"); for (String sourceId: newProblemChildren.keySet()) { ReferenceList childReferences = newProblemChildren.get(sourceId); //map to UUID UUID conditionId = IdHelper.getEdsResourceId(serviceId, ResourceType.Condition, sourceId); if (conditionId == null) { continue; } //get history, which is most recent FIRST List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, ResourceType.Condition.toString(), conditionId); if (history.isEmpty()) { continue; //throw new Exception("Empty history for Condition " + conditionId); } ResourceWrapper currentState = history.get(0); if (currentState.isDeleted()) { continue; } //find last instance prior to cutoff and get its linked children for (ResourceWrapper wrapper: history) { Date d = wrapper.getCreatedAt(); if (!d.after(cutoff)) { if (wrapper.getResourceData() != null) { Condition previousVersion = (Condition) FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(previousVersion); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); List<Reference> previousChildren = containedListBuilder.getContainedListItems(); childReferences.add(previousChildren); } break; } } if (childReferences.size() == 0) { continue; } String json = currentState.getResourceData(); Resource resource = FhirSerializationHelper.deserializeResource(json); String newJson = FhirSerializationHelper.serializeResource(resource); if (!json.equals(newJson)) { currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState); } *//*Condition condition = (Condition)FhirSerializationHelper.deserializeResource(currentState.getResourceData()); ConditionBuilder conditionBuilder = new ConditionBuilder(condition); ContainedListBuilder containedListBuilder = new ContainedListBuilder(conditionBuilder); containedListBuilder.addReferences(childReferences); String newJson = FhirSerializationHelper.serializeResource(condition); currentState.setResourceData(newJson); currentState.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); saveResourceWrapper(serviceId, currentState);*//* } //mark as done String updateSql = "UPDATE " + table + " SET done = 1 WHERE service_id = '" + serviceId + "';"; entityManager = ConnectionManager.getAdminEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); } *//** * For each practice: Go through all files processed since 14 March Cache all links as above Cache all Encounters saved too For each Encounter referenced at all: Retrieve latest version from resource current Retrieve version prior to 14 March Update current version with old references plus new ones For each parent observation: Retrieve latest version (could be observation or diagnostic report) For each problem: Retrieve latest version from resource current Check if still a problem: Retrieve version prior to 14 March Update current version with old references plus new ones *//* LOG.info("Finished Fixing encounters from " + table); } catch (Throwable t) { LOG.error("", t); } }*/ private static void saveResourceWrapper(UUID serviceId, ResourceWrapper wrapper) throws Exception { if (wrapper.getResourceData() != null) { long checksum = FhirStorageService.generateChecksum(wrapper.getResourceData()); wrapper.setResourceChecksum(new Long(checksum)); } EntityManager entityManager = ConnectionManager.getEhrEntityManager(serviceId); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); entityManager.getTransaction().begin(); String json = wrapper.getResourceData(); json = json.replace("'", "''"); json = json.replace("\\", "\\\\"); String patientId = ""; if (wrapper.getPatientId() != null) { patientId = wrapper.getPatientId().toString(); } String updateSql = "UPDATE resource_current" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE service_id = '" + wrapper.getServiceId() + "'" + " AND patient_id = '" + patientId + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" + " AND resource_id = '" + wrapper.getResourceId() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS"); //String createdAtStr = sdf.format(wrapper.getCreatedAt()); updateSql = "UPDATE resource_history" + " SET resource_data = '" + json + "'," + " resource_checksum = " + wrapper.getResourceChecksum() + " WHERE resource_id = '" + wrapper.getResourceId() + "'" + " AND resource_type = '" + wrapper.getResourceType() + "'" //+ " AND created_at = '" + createdAtStr + "'" + " AND version = '" + wrapper.getVersion() + "'"; statement.executeUpdate(updateSql); //LOG.debug(updateSql); entityManager.getTransaction().commit(); } /*private static void populateNewSearchTable(String table) { LOG.info("Populating New Search Table"); try { EntityManager entityManager = ConnectionManager.getEdsEntityManager(); SessionImpl session = (SessionImpl)entityManager.getDelegate(); Connection connection = session.connection(); Statement statement = connection.createStatement(); List<String> patientIds = new ArrayList<>(); Map<String, String> serviceIds = new HashMap<>(); String sql = "SELECT patient_id, service_id FROM " + table + " WHERE done = 0"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String patientId = rs.getString(1); String serviceId = rs.getString(2); patientIds.add(patientId); serviceIds.put(patientId, serviceId); } rs.close(); statement.close(); entityManager.close(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearch2Dal(); LOG.info("Found " + patientIds.size() + " to do"); for (int i=0; i<patientIds.size(); i++) { String patientIdStr = patientIds.get(i); UUID patientId = UUID.fromString(patientIdStr); String serviceIdStr = serviceIds.get(patientIdStr); UUID serviceId = UUID.fromString(serviceIdStr); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientIdStr); if (patient != null) { patientSearchDal.update(serviceId, patient); //find episode of care List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(serviceId, null, patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (!wrapper.isDeleted()) { EpisodeOfCare episodeOfCare = (EpisodeOfCare)FhirSerializationHelper.deserializeResource(wrapper.getResourceData()); patientSearchDal.update(serviceId, episodeOfCare); } } } String updateSql = "UPDATE " + table + " SET done = 1 WHERE patient_id = '" + patientIdStr + "' AND service_id = '" + serviceIdStr + "';"; entityManager = ConnectionManager.getEdsEntityManager(); session = (SessionImpl)entityManager.getDelegate(); connection = session.connection(); statement = connection.createStatement(); entityManager.getTransaction().begin(); statement.executeUpdate(updateSql); entityManager.getTransaction().commit(); if (i % 5000 == 0) { LOG.info("Done " + (i+1) + " of " + patientIds.size()); } } entityManager.close(); LOG.info("Finished Populating New Search Table"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static void createBartsSubset(String sourceDir, UUID serviceUuid, UUID systemUuid, String samplePatientsFile) { LOG.info("Creating Barts Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } createBartsSubsetForFile(sourceDir, serviceUuid, systemUuid, personIds); LOG.info("Finished Creating Barts Subset"); } catch (Throwable t) { LOG.error("", t); } } /*private static void createBartsSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { for (File sourceFile: sourceDir.listFiles()) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } LOG.info("Doing dir " + sourceFile); createBartsSubsetForFile(sourceFile, destFile, personIds); } else { //we have some bad partial files in, so ignore them String ext = FilenameUtils.getExtension(name); if (ext.equalsIgnoreCase("filepart")) { continue; } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String baseName = FilenameUtils.getBaseName(name); String fileType = BartsCsvToFhirTransformer.identifyFileType(baseName); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex ++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i=0; i<expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex+1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } }*/ private static void createBartsSubsetForFile(String sourceDir, UUID serviceUuid, UUID systemUuid, Set<String> personIds) throws Exception { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); for (Exchange exchange: exchanges) { List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile fileObj : files) { String filePathWithoutSharedStorage = fileObj.getPath().substring(TransformConfig.instance().getSharedStoragePath().length()+1); String sourceFilePath = FilenameUtils.concat(sourceDir, filePathWithoutSharedStorage); File sourceFile = new File(sourceFilePath); String destFilePath = fileObj.getPath(); File destFile = new File(destFilePath); File destDir = destFile.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } //if the file is empty, we still need the empty file in the filtered directory, so just copy it if (sourceFile.length() == 0) { LOG.info("Copying empty file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } continue; } String fileType = fileObj.getType(); if (isCerner22File(fileType)) { LOG.info("Checking 2.2 file " + sourceFile); if (destFile.exists()) { destFile.delete(); } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); int lineIndex = -1; PrintWriter pw = null; int personIdColIndex = -1; int expectedCols = -1; while (true) { String line = br.readLine(); if (line == null) { break; } lineIndex++; if (lineIndex == 0) { if (fileType.equalsIgnoreCase("FAMILYHISTORY")) { //this file has no headers, so needs hard-coding personIdColIndex = 5; } else { //check headings for PersonID col String[] toks = line.split("\\|", -1); expectedCols = toks.length; for (int i = 0; i < expectedCols; i++) { String col = toks[i]; if (col.equalsIgnoreCase("PERSON_ID") || col.equalsIgnoreCase("#PERSON_ID")) { personIdColIndex = i; break; } } //if no person ID, then just copy the entire file if (personIdColIndex == -1) { br.close(); br = null; LOG.info(" Copying 2.2 file to " + destFile); copyFile(sourceFile, destFile); break; } else { LOG.info(" Filtering 2.2 file to " + destFile + ", person ID col at " + personIdColIndex); } } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } else { //filter on personID String[] toks = line.split("\\|", -1); if (expectedCols != -1 && toks.length != expectedCols) { throw new Exception("Line " + (lineIndex + 1) + " has " + toks.length + " cols but expecting " + expectedCols); } else { String personId = toks[personIdColIndex]; if (!Strings.isNullOrEmpty(personId) //always carry over rows with empty person ID, as Cerner won't send the person ID for deletes && !personIds.contains(personId)) { continue; } } } pw.println(line); } if (br != null) { br.close(); } if (pw != null) { pw.flush(); pw.close(); } } else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); if (!destFile.exists()) { copyFile(sourceFile, destFile); } } } } } private static void copyFile(File src, File dst) throws Exception { FileInputStream fis = new FileInputStream(src); BufferedInputStream bis = new BufferedInputStream(fis); Files.copy(bis, dst.toPath()); bis.close(); } private static boolean isCerner22File(String fileType) throws Exception { if (fileType.equalsIgnoreCase("PPATI") || fileType.equalsIgnoreCase("PPREL") || fileType.equalsIgnoreCase("CDSEV") || fileType.equalsIgnoreCase("PPATH") || fileType.equalsIgnoreCase("RTTPE") || fileType.equalsIgnoreCase("AEATT") || fileType.equalsIgnoreCase("AEINV") || fileType.equalsIgnoreCase("AETRE") || fileType.equalsIgnoreCase("OPREF") || fileType.equalsIgnoreCase("OPATT") || fileType.equalsIgnoreCase("EALEN") || fileType.equalsIgnoreCase("EALSU") || fileType.equalsIgnoreCase("EALOF") || fileType.equalsIgnoreCase("HPSSP") || fileType.equalsIgnoreCase("IPEPI") || fileType.equalsIgnoreCase("IPWDS") || fileType.equalsIgnoreCase("DELIV") || fileType.equalsIgnoreCase("BIRTH") || fileType.equalsIgnoreCase("SCHAC") || fileType.equalsIgnoreCase("APPSL") || fileType.equalsIgnoreCase("DIAGN") || fileType.equalsIgnoreCase("PROCE") || fileType.equalsIgnoreCase("ORDER") || fileType.equalsIgnoreCase("DOCRP") || fileType.equalsIgnoreCase("DOCREF") || fileType.equalsIgnoreCase("CNTRQ") || fileType.equalsIgnoreCase("LETRS") || fileType.equalsIgnoreCase("LOREF") || fileType.equalsIgnoreCase("ORGREF") || fileType.equalsIgnoreCase("PRSNLREF") || fileType.equalsIgnoreCase("CVREF") || fileType.equalsIgnoreCase("NOMREF") || fileType.equalsIgnoreCase("EALIP") || fileType.equalsIgnoreCase("CLEVE") || fileType.equalsIgnoreCase("ENCNT") || fileType.equalsIgnoreCase("RESREF") || fileType.equalsIgnoreCase("PPNAM") || fileType.equalsIgnoreCase("PPADD") || fileType.equalsIgnoreCase("PPPHO") || fileType.equalsIgnoreCase("PPALI") || fileType.equalsIgnoreCase("PPINF") || fileType.equalsIgnoreCase("PPAGP") || fileType.equalsIgnoreCase("SURCC") || fileType.equalsIgnoreCase("SURCP") || fileType.equalsIgnoreCase("SURCA") || fileType.equalsIgnoreCase("SURCD") || fileType.equalsIgnoreCase("PDRES") || fileType.equalsIgnoreCase("PDREF") || fileType.equalsIgnoreCase("ABREF") || fileType.equalsIgnoreCase("CEPRS") || fileType.equalsIgnoreCase("ORDDT") || fileType.equalsIgnoreCase("STATREF") || fileType.equalsIgnoreCase("STATA") || fileType.equalsIgnoreCase("ENCINF") || fileType.equalsIgnoreCase("SCHDETAIL") || fileType.equalsIgnoreCase("SCHOFFER") || fileType.equalsIgnoreCase("PPGPORG") || fileType.equalsIgnoreCase("FAMILYHISTORY")) { return true; } else { return false; } } private static void fixSubscriberDbs() { LOG.info("Fixing Subscriber DBs"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-05-11"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info(" Posting exchange " + exchangeId + " with " + batches.size() + " batches"); List<UUID> batchIds = new ArrayList<>(); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); batchIds.add(batchId); } String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } LOG.info("Finished Fixing Subscriber DBs"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixReferralRequests() { LOG.info("Fixing Referral Requests"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); Date dateError = new SimpleDateFormat("yyyy-MM-dd").parse("2018-04-24"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); boolean needsFixing = false; Set<UUID> patientIdsToPost = new HashSet<>(); for (UUID exchangeId: exchangeIds) { if (!needsFixing) { List<ExchangeTransformAudit> transformAudits = exchangeDal.getAllExchangeTransformAudits(serviceId, endpointSystemId, exchangeId); for (ExchangeTransformAudit audit: transformAudits) { Date transfromStart = audit.getStarted(); if (!transfromStart.before(dateError)) { needsFixing = true; break; } } } if (!needsFixing) { continue; } List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); LOG.info("Checking exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } UUID batchId = batch.getBatchId(); List<ResourceWrapper> wrappers = resourceDal.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper wrapper: wrappers) { String resourceType = wrapper.getResourceType(); if (!resourceType.equals(ResourceType.ReferralRequest.toString()) || wrapper.isDeleted()) { continue; } String json = wrapper.getResourceData(); ReferralRequest referral = (ReferralRequest)FhirSerializationHelper.deserializeResource(json); *//*if (!referral.hasServiceRequested()) { continue; } CodeableConcept reason = referral.getServiceRequested().get(0); referral.setReason(reason); referral.getServiceRequested().clear();*//* if (!referral.hasReason()) { continue; } CodeableConcept reason = referral.getReason(); referral.setReason(null); referral.addServiceRequested(reason); json = FhirSerializationHelper.serializeResource(referral); wrapper.setResourceData(json); saveResourceWrapper(serviceId, wrapper); //add to the set of patients we know need sending on to the protocol queue patientIdsToPost.add(patientId); LOG.info("Fixed " + resourceType + " " + wrapper.getResourceId() + " in batch " + batchId); } //if our patient has just been fixed or was fixed before, post onto the protocol queue if (patientIdsToPost.contains(patientId)) { List<UUID> batchIds = new ArrayList<>(); batchIds.add(batchId); String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } } LOG.info("Finished Fixing Referral Requests"); } catch (Throwable t) { LOG.error("", t); } }*/ private static void applyEmisAdminCaches() { LOG.info("Applying Emis Admin Caches"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); UUID emisSystem = UUID.fromString("991a9068-01d3-4ff2-86ed-249bd0541fb3"); UUID emisSystemDev = UUID.fromString("55c08fa5-ef1e-4e94-aadc-e3d6adc80774"); List<Service> services = serviceDal.getAll(); for (Service service: services) { String endpointsJson = service.getEndpoints(); if (Strings.isNullOrEmpty(endpointsJson)) { continue; } UUID serviceId = service.getId(); LOG.info("Checking " + service.getName() + " " + serviceId); List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); if (!endpointSystemId.equals(emisSystem) && !endpointSystemId.equals(emisSystemDev)) { LOG.info(" Skipping system ID " + endpointSystemId + " as not Emis"); continue; } if (!exchangeDal.isServiceStarted(serviceId, endpointSystemId)) { LOG.info(" Service not started, so skipping"); continue; } //get exchanges List<UUID> exchangeIds = exchangeDal.getExchangeIdsForService(serviceId, endpointSystemId); if (exchangeIds.isEmpty()) { LOG.info(" No exchanges found, so skipping"); continue; } UUID firstExchangeId = exchangeIds.get(0); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(firstExchangeId); boolean appliedAdminCache = false; for (ExchangeEvent event: events) { if (event.getEventDesc().equals("Applied Emis Admin Resource Cache")) { appliedAdminCache = true; } } if (appliedAdminCache) { LOG.info(" Have already applied admin cache, so skipping"); continue; } Exchange exchange = exchangeDal.getExchange(firstExchangeId); String body = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(body); if (files.length == 0) { LOG.info(" No files in exchange " + firstExchangeId + " so skipping"); continue; } String firstFilePath = files[0]; String name = FilenameUtils.getBaseName(firstFilePath); //file name without extension String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + firstFilePath); } String sharingAgreementGuid = toks[4]; List<UUID> batchIds = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler fhirResourceFiler = new FhirResourceFiler(firstExchangeId, serviceId, endpointSystemId, transformError, batchIds); EmisCsvHelper csvHelper = new EmisCsvHelper(fhirResourceFiler.getServiceId(), fhirResourceFiler.getSystemId(), fhirResourceFiler.getExchangeId(), sharingAgreementGuid, true); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(endpointSystemId); transformAudit.setExchangeId(firstExchangeId); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); LOG.info(" Going to apply admin resource cache"); csvHelper.applyAdminResourceCache(fhirResourceFiler); fhirResourceFiler.waitToFinish(); for (UUID batchId: batchIds) { LOG.info(" Created batch ID " + batchId + " for exchange " + firstExchangeId); } transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIds.size())); boolean hadError = false; if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); hadError = true; } exchangeDal.save(transformAudit); //clear down the cache of reference mappings since they won't be of much use for the next Exchange IdHelper.clearCache(); if (hadError) { LOG.error(" <<<<<<Error applying resource cache!"); continue; } //add the event to say we've applied the cache AuditWriter.writeExchangeEvent(firstExchangeId, "Applied Emis Admin Resource Cache"); //post that ONE new batch ID onto the protocol queue String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchIds.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchUuidsStr); PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } LOG.info("Finished Applying Emis Admin Caches"); } catch (Throwable t) { LOG.error("", t); } } /*private static void fixBartsEscapedFiles(String filePath) { LOG.info("Fixing Barts Escaped Files in " + filePath); try { fixBartsEscapedFilesInDir(new File(filePath)); LOG.info("Finished fixing Barts Escaped Files in " + filePath); } catch (Throwable t) { LOG.error("", t); } } /** * fixes Emis extract(s) when a practice was disabled then subsequently re-bulked, by * replacing the "delete" extracts with newly generated deltas that can be processed * before the re-bulk is done */ private static void fixDisabledEmisExtract(String serviceId, String systemId, String sharedStoragePath, String tempDir) { LOG.info("Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); try { /*File tempDirLast = new File(tempDir, "last"); if (!tempDirLast.exists()) { if (!tempDirLast.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirLast); } tempDirLast.mkdirs(); } File tempDirEmpty = new File(tempDir, "empty"); if (!tempDirEmpty.exists()) { if (!tempDirEmpty.mkdirs()) { throw new Exception("Failed to create temp dir " + tempDirEmpty); } tempDirEmpty.mkdirs(); }*/ UUID serviceUuid = UUID.fromString(serviceId); UUID systemUuid = UUID.fromString(systemId); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); //get all the exchanges, which are returned in reverse order, so reverse for simplicity List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceUuid, systemUuid, Integer.MAX_VALUE); //sorting by timestamp seems unreliable when exchanges were posted close together? List<Exchange> tmp = new ArrayList<>(); for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); tmp.add(exchange); } exchanges = tmp; /*exchanges.sort((o1, o2) -> { Date d1 = o1.getTimestamp(); Date d2 = o2.getTimestamp(); return d1.compareTo(d2); });*/ LOG.info("Found " + exchanges.size() + " exchanges"); //continueOrQuit(); //find the files for each exchange Map<Exchange, List<String>> hmExchangeFiles = new HashMap<>(); Map<Exchange, List<String>> hmExchangeFilesWithoutStoragePrefix = new HashMap<>(); for (Exchange exchange: exchanges) { //populate a map of the files with the shared storage prefix String exchangeBody = exchange.getBody(); String[] files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); List<String> fileList = Lists.newArrayList(files); hmExchangeFiles.put(exchange, fileList); //populate a map of the same files without the prefix files = ExchangeHelper.parseExchangeBodyOldWay(exchangeBody); for (int i=0; i<files.length; i++) { String file = files[i].substring(sharedStoragePath.length() + 1); files[i] = file; } fileList = Lists.newArrayList(files); hmExchangeFilesWithoutStoragePrefix.put(exchange, fileList); } LOG.info("Cached files for each exchange"); int indexDisabled = -1; int indexRebulked = -1; int indexOriginallyBulked = -1; //go back through them to find the extract where the re-bulk is and when it was disabled for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { indexDisabled = i; } else { if (indexDisabled == -1) { indexRebulked = i; } else { //if we've found a non-disabled extract older than the disabled ones, //then we've gone far enough back break; } } } //go back from when disabled to find the previous bulk load (i.e. the first one or one after it was previously not disabled) for (int i=indexDisabled-1; i>=0; i--) { Exchange exchange = exchanges.get(i); boolean disabled = isDisabledInSharingAgreementFile(exchange, hmExchangeFiles); if (disabled) { break; } indexOriginallyBulked = i; } if (indexDisabled == -1 || indexRebulked == -1 || indexOriginallyBulked == -1) { throw new Exception("Failed to find exchanges for disabling (" + indexDisabled + "), re-bulking (" + indexRebulked + ") or original bulk (" + indexOriginallyBulked + ")"); } Exchange exchangeDisabled = exchanges.get(indexDisabled); LOG.info("Disabled on " + findExtractDate(exchangeDisabled, hmExchangeFiles) + " " + exchangeDisabled.getId()); Exchange exchangeRebulked = exchanges.get(indexRebulked); LOG.info("Rebulked on " + findExtractDate(exchangeRebulked, hmExchangeFiles) + " " + exchangeRebulked.getId()); Exchange exchangeOriginallyBulked = exchanges.get(indexOriginallyBulked); LOG.info("Originally bulked on " + findExtractDate(exchangeOriginallyBulked, hmExchangeFiles) + " " + exchangeOriginallyBulked.getId()); //continueOrQuit(); List<String> rebulkFiles = hmExchangeFiles.get(exchangeRebulked); List<String> tempFilesCreated = new ArrayList<>(); Set<String> patientGuidsDeletedOrTooOld = new HashSet<>(); for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (!isPatientFile(fileType)) { continue; } LOG.info("Doing " + fileType); String guidColumnName = getGuidColumnName(fileType); //find all the guids in the re-bulk Set<String> idsInRebulk = new HashSet<>(); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(rebulkFile); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); String[] headers = null; try { headers = CsvHelper.getHeaderMapAsArray(csvParser); Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); //get the patient and row guid out of the file and cache in our set String id = record.get("PatientGuid"); if (!Strings.isNullOrEmpty(guidColumnName)) { id += "//" + record.get(guidColumnName); } idsInRebulk.add(id); } } finally { csvParser.close(); } LOG.info("Found " + idsInRebulk.size() + " IDs in re-bulk file: " + rebulkFile); //create a replacement file for the exchange the service was disabled String replacementDisabledFile = null; List<String> disabledFiles = hmExchangeFilesWithoutStoragePrefix.get(exchangeDisabled); for (String s: disabledFiles) { String disabledFileType = findFileType(s); if (disabledFileType.equals(fileType)) { replacementDisabledFile = FilenameUtils.concat(tempDir, s); File dir = new File(replacementDisabledFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } tempFilesCreated.add(s); LOG.info("Created replacement file " + replacementDisabledFile); } } FileWriter fileWriter = new FileWriter(replacementDisabledFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); Set<String> pastIdsProcessed = new HashSet<>(); //now go through all files of the same type PRIOR to the service was disabled //to find any rows that we'll need to explicitly delete because they were deleted while //the extract was disabled for (int i=indexDisabled-1; i>=indexOriginallyBulked; i--) { Exchange exchange = exchanges.get(i); String originalFile = null; List<String> files = hmExchangeFiles.get(exchange); for (String s: files) { String originalFileType = findFileType(s); if (originalFileType.equals(fileType)) { originalFile = s; break; } } if (originalFile == null) { continue; } LOG.info(" Reading " + originalFile); reader = FileHelper.readFileReaderFromSharedStorage(originalFile); csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String patientGuid = record.get("PatientGuid"); //get the patient and row guid out of the file and cache in our set String uniqueId = patientGuid; if (!Strings.isNullOrEmpty(guidColumnName)) { uniqueId += "//" + record.get(guidColumnName); } //if we're already handled this record in a more recent extract, then skip it if (pastIdsProcessed.contains(uniqueId)) { continue; } pastIdsProcessed.add(uniqueId); //if this ID isn't deleted and isn't in the re-bulk then it means //it WAS deleted in Emis Web but we didn't receive the delete, because it was deleted //from Emis Web while the extract feed was disabled //if the record is deleted, then we won't expect it in the re-bulk boolean deleted = Boolean.parseBoolean(record.get("Deleted")); if (deleted) { //if it's the Patient file, stick the patient GUID in a set so we know full patient record deletes if (fileType.equals("Admin_Patient")) { patientGuidsDeletedOrTooOld.add(patientGuid); } continue; } //if it's not the patient file and we refer to a patient that we know //has been deleted, then skip this row, since we know we're deleting the entire patient record if (patientGuidsDeletedOrTooOld.contains(patientGuid)) { continue; } //if the re-bulk contains a record matching this one, then it's OK if (idsInRebulk.contains(uniqueId)) { continue; } //the rebulk won't contain any data for patients that are now too old (i.e. deducted or deceased > 2 yrs ago), //so any patient ID in the original files but not in the rebulk can be treated like this and any data for them can be skipped if (fileType.equals("Admin_Patient")) { //retrieve the Patient and EpisodeOfCare resource for the patient so we can confirm they are deceased or deducted ResourceDalI resourceDal = DalProvider.factoryResourceDal(); UUID patientUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.Patient, patientGuid); Patient patientResource = (Patient)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.Patient, patientUuid.toString()); if (patientResource.hasDeceased()) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } UUID episodeUuid = IdHelper.getEdsResourceId(serviceUuid, ResourceType.EpisodeOfCare, patientGuid); //we use the patient GUID for the episode too EpisodeOfCare episodeResource = (EpisodeOfCare)resourceDal.getCurrentVersionAsResource(serviceUuid, ResourceType.EpisodeOfCare, episodeUuid.toString()); if (episodeResource.hasPeriod() && !PeriodHelper.isActive(episodeResource.getPeriod())) { patientGuidsDeletedOrTooOld.add(patientGuid); continue; } } //create a new CSV record, carrying over the GUIDs from the original but marking as deleted String[] newRecord = new String[headers.length]; for (int j=0; j<newRecord.length; j++) { String header = headers[j]; if (header.equals("PatientGuid") || header.equals("OrganisationGuid") || (!Strings.isNullOrEmpty(guidColumnName) && header.equals(guidColumnName))) { String val = record.get(header); newRecord[j] = val; } else if (header.equals("Deleted")) { newRecord[j] = "true"; } else { newRecord[j] = ""; } } csvPrinter.printRecord((Object[])newRecord); csvPrinter.flush(); //log out the raw record that's missing from the original StringBuffer sb = new StringBuffer(); sb.append("Record not in re-bulk: "); for (int j=0; j<record.size(); j++) { if (j > 0) { sb.append(","); } sb.append(record.get(j)); } LOG.info(sb.toString()); } } finally { csvParser.close(); } } csvPrinter.flush(); csvPrinter.close(); //also create a version of the CSV file with just the header and nothing else in for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals(fileType)) { String emptyTempFile = FilenameUtils.concat(tempDir, s); File dir = new File(emptyTempFile).getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { throw new Exception("Failed to create directory " + dir); } } fileWriter = new FileWriter(emptyTempFile); bufferedWriter = new BufferedWriter(fileWriter); csvPrinter = new CSVPrinter(bufferedWriter, EmisCsvToFhirTransformer.CSV_FORMAT.withHeader(headers)); csvPrinter.flush(); csvPrinter.close(); tempFilesCreated.add(s); LOG.info("Created empty file " + emptyTempFile); } } } } //we also need to copy the restored sharing agreement file to replace all the period it was disabled String rebulkedSharingAgreementFile = null; for (String s: rebulkFiles) { String fileType = findFileType(s); if (fileType.equals("Agreements_SharingOrganisation")) { rebulkedSharingAgreementFile = s; } } for (int i=indexDisabled; i<indexRebulked; i++) { Exchange ex = exchanges.get(i); List<String> exchangeFiles = hmExchangeFilesWithoutStoragePrefix.get(ex); for (String s: exchangeFiles) { String exchangeFileType = findFileType(s); if (exchangeFileType.equals("Agreements_SharingOrganisation")) { String replacementFile = FilenameUtils.concat(tempDir, s); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkedSharingAgreementFile); Files.copy(inputStream, new File(replacementFile).toPath()); inputStream.close(); tempFilesCreated.add(s); } } } //create a script to copy the files into S3 List<String> copyScript = new ArrayList<>(); copyScript.add("#!/bin/bash"); copyScript.add(""); for (String s: tempFilesCreated) { String localFile = FilenameUtils.concat(tempDir, s); copyScript.add("sudo aws s3 cp " + localFile + " s3://discoverysftplanding/endeavour/" + s); } String scriptFile = FilenameUtils.concat(tempDir, "copy.sh"); FileUtils.writeLines(new File(scriptFile), copyScript); /*continueOrQuit(); //back up every file where the service was disabled for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { //first download from S3 to the local temp dir InputStream inputStream = FileHelper.readFileFromSharedStorage(file); String fileName = FilenameUtils.getName(file); String tempPath = FilenameUtils.concat(tempDir, fileName); File downloadDestination = new File(tempPath); Files.copy(inputStream, downloadDestination.toPath()); //then write back to S3 in a sub-dir of the original file String backupPath = FilenameUtils.getPath(file); backupPath = FilenameUtils.concat(backupPath, "Original"); backupPath = FilenameUtils.concat(backupPath, fileName); FileHelper.writeFileToSharedStorage(backupPath, downloadDestination); LOG.info("Backed up " + file + " -> " + backupPath); //delete from temp dir downloadDestination.delete(); } } continueOrQuit(); //copy the new CSV files into the dir where it was disabled List<String> disabledFiles = hmExchangeFiles.get(exchangeDisabled); for (String disabledFile: disabledFiles) { String fileType = findFileType(disabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirLast.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected temp file " + f); } FileHelper.writeFileToSharedStorage(disabledFile, f); LOG.info("Copied " + tempFile + " -> " + disabledFile); } continueOrQuit(); //empty the patient files for any extracts while the service was disabled for (int i=indexDisabled+1; i<indexRebulked; i++) { Exchange otherExchangeDisabled = exchanges.get(i); List<String> otherDisabledFiles = hmExchangeFiles.get(otherExchangeDisabled); for (String otherDisabledFile: otherDisabledFiles) { String fileType = findFileType(otherDisabledFile); if (!isPatientFile(fileType)) { continue; } String tempFile = FilenameUtils.concat(tempDirEmpty.getAbsolutePath(), fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(otherDisabledFile, f); LOG.info("Copied " + tempFile + " -> " + otherDisabledFile); } } continueOrQuit(); //copy the content of the sharing agreement file from when it was re-bulked for (String rebulkFile: rebulkFiles) { String fileType = findFileType(rebulkFile); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File downloadDestination = new File(tempFile); InputStream inputStream = FileHelper.readFileFromSharedStorage(rebulkFile); Files.copy(inputStream, downloadDestination.toPath()); tempFilesCreated.add(tempFile); } } //replace the sharing agreement file for all disabled extracts with the non-disabled one for (int i=indexDisabled; i<indexRebulked; i++) { Exchange exchange = exchanges.get(i); List<String> files = hmExchangeFiles.get(exchange); for (String file: files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { String tempFile = FilenameUtils.concat(tempDir, fileType + ".csv"); File f = new File(tempFile); if (!f.exists()) { throw new Exception("Failed to find expected empty file " + f); } FileHelper.writeFileToSharedStorage(file, f); LOG.info("Copied " + tempFile + " -> " + file); } } } LOG.info("Finished Fixing Disabled Emis Extracts Prior to Re-bulk for service " + serviceId); continueOrQuit(); for (String tempFileCreated: tempFilesCreated) { File f = new File(tempFileCreated); if (f.exists()) { f.delete(); } }*/ } catch (Exception ex) { LOG.error("", ex); } } private static String findExtractDate(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); String name = FilenameUtils.getBaseName(file); String[] toks = name.split("_"); return toks[3]; } private static boolean isDisabledInSharingAgreementFile(Exchange exchange, Map<Exchange, List<String>> fileMap) throws Exception { List<String> files = fileMap.get(exchange); String file = findSharingAgreementFile(files); InputStreamReader reader = FileHelper.readFileReaderFromSharedStorage(file); CSVParser csvParser = new CSVParser(reader, EmisCsvToFhirTransformer.CSV_FORMAT); try { Iterator<CSVRecord> iterator = csvParser.iterator(); CSVRecord record = iterator.next(); String s = record.get("Disabled"); boolean disabled = Boolean.parseBoolean(s); return disabled; } finally { csvParser.close(); } } private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char)bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } private static String getGuidColumnName(String fileType) { if (fileType.equals("Admin_Patient")) { //patient file just has patient GUID, nothing extra return null; } else if (fileType.equals("CareRecord_Consultation")) { return "ConsultationGuid"; } else if (fileType.equals("CareRecord_Diary")) { return "DiaryGuid"; } else if (fileType.equals("CareRecord_Observation")) { return "ObservationGuid"; } else if (fileType.equals("CareRecord_Problem")) { //there is no separate problem GUID, as it's just a modified observation return "ObservationGuid"; } else if (fileType.equals("Prescribing_DrugRecord")) { return "DrugRecordGuid"; } else if (fileType.equals("Prescribing_IssueRecord")) { return "IssueRecordGuid"; } else { throw new IllegalArgumentException(fileType); } } private static String findFileType(String filePath) { String fileName = FilenameUtils.getName(filePath); String[] toks = fileName.split("_"); String domain = toks[1]; String name = toks[2]; return domain + "_" + name; } private static boolean isPatientFile(String fileType) { if (fileType.equals("Admin_Patient") || fileType.equals("CareRecord_Consultation") || fileType.equals("CareRecord_Diary") || fileType.equals("CareRecord_Observation") || fileType.equals("CareRecord_Problem") || fileType.equals("Prescribing_DrugRecord") || fileType.equals("Prescribing_IssueRecord")) { //note the referral file doesn't have a Deleted column, so isn't in this list return true; } else { return false; } } private static String findSharingAgreementFile(List<String> files) throws Exception { for (String file : files) { String fileType = findFileType(file); if (fileType.equals("Agreements_SharingOrganisation")) { return file; } } throw new Exception("Failed to find sharing agreement file in " + files.get(0)); } private static void testSlack() { LOG.info("Testing slack"); try { SlackHelper.sendSlackMessage(SlackHelper.Channel.QueueReaderAlerts, "Test Message from Queue Reader"); LOG.info("Finished testing slack"); } catch (Exception ex) { LOG.error("", ex); } } private static void postToInboundFromFile(UUID serviceId, UUID systemId, String filePath) { try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); LOG.info("Posting to inbound exchange for " + service.getName() + " from file " + filePath); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); auditRepository.save(audit); } count ++; exchangeIdBatch.add(exchangeId); if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false); LOG.info("Done " + count); } br.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); } /*private static void postToInbound(UUID serviceId, boolean all) { LOG.info("Posting to inbound for " + serviceId); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); Service service = serviceDalI.getById(serviceId); List<UUID> systemIds = findSystemIds(service); UUID systemId = systemIds.get(0); ExchangeTransformErrorState errorState = auditRepository.getErrorState(serviceId, systemId); for (UUID exchangeId: errorState.getExchangeIdsInError()) { //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = auditRepository.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); //skip any exchange IDs we've already re-queued up to be processed again if (audit.isResubmitted()) { LOG.debug("Not re-posting " + audit.getExchangeId() + " as it's already been resubmitted"); continue; } LOG.debug("Re-posting " + audit.getExchangeId()); audit.setResubmitted(true); auditRepository.save(audit); //then re-submit the exchange to Rabbit MQ for the queue reader to pick up QueueHelper.postToExchange(exchangeId, "EdsInbound", null, false); if (!all) { LOG.info("Posted first exchange, so stopping"); break; } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Posting to inbound for " + serviceId); }*/ /*private static void fixPatientSearch(String serviceId) { LOG.info("Fixing patient search for " + serviceId); try { UUID serviceUuid = UUID.fromString(serviceId); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ParserPool parser = new ParserPool(); Set<UUID> patientsDone = new HashSet<>(); List<UUID> exchanges = exchangeDalI.getExchangeIdsForService(serviceUuid); LOG.info("Found " + exchanges.size() + " exchanges"); for (UUID exchangeId: exchanges) { List<ExchangeBatch> batches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); LOG.info("Found " + batches.size() + " batches in exchange " + exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId == null) { continue; } if (patientsDone.contains(patientId)) { continue; } ResourceWrapper wrapper = resourceDalI.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (wrapper != null) { String json = wrapper.getResourceData(); if (!Strings.isNullOrEmpty(json)) { Patient fhirPatient = (Patient) parser.parse(json); UUID systemUuid = wrapper.getSystemId(); patientSearchDal.update(serviceUuid, systemUuid, fhirPatient); } } patientsDone.add(patientId); if (patientsDone.size() % 1000 == 0) { LOG.info("Done " + patientsDone.size()); } } } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished fixing patient search for " + serviceId); }*/ private static void runSql(String host, String username, String password, String sqlFile) { LOG.info("Running SQL on " + host + " from " + sqlFile); Connection conn = null; Statement statement = null; try { File f = new File(sqlFile); if (!f.exists()) { LOG.error("" + f + " doesn't exist"); return; } List<String> lines = FileUtils.readLines(f); /*String combined = String.join("\n", lines); LOG.info("Going to run SQL"); LOG.info(combined);*/ //load driver Class.forName("com.mysql.cj.jdbc.Driver"); //create connection Properties props = new Properties(); props.setProperty("user", username); props.setProperty("password", password); conn = DriverManager.getConnection(host, props); LOG.info("Opened connection"); statement = conn.createStatement(); long totalStart = System.currentTimeMillis(); for (String sql: lines) { sql = sql.trim(); if (sql.startsWith("--") || sql.startsWith("/*") || Strings.isNullOrEmpty(sql)) { continue; } LOG.info(""); LOG.info(sql); long start = System.currentTimeMillis(); boolean hasResultSet = statement.execute(sql); long end = System.currentTimeMillis(); LOG.info("SQL took " + (end - start) + "ms"); if (hasResultSet) { while (true) { ResultSet rs = statement.getResultSet(); int cols = rs.getMetaData().getColumnCount(); List<String> colHeaders = new ArrayList<>(); for (int i = 0; i < cols; i++) { String header = rs.getMetaData().getColumnName(i + 1); colHeaders.add(header); } String colHeaderStr = String.join(", ", colHeaders); LOG.info(colHeaderStr); while (rs.next()) { List<String> row = new ArrayList<>(); for (int i = 0; i < cols; i++) { Object o = rs.getObject(i + 1); if (rs.wasNull()) { row.add("<null>"); } else { row.add(o.toString()); } } String rowStr = String.join(", ", row); LOG.info(rowStr); } if (!statement.getMoreResults()) { break; } } } else { int updateCount = statement.getUpdateCount(); LOG.info("Updated " + updateCount + " Row(s)"); } } long totalEnd = System.currentTimeMillis(); LOG.info(""); LOG.info("Total time taken " + (totalEnd - totalStart) + "ms"); } catch (Throwable t) { LOG.error("", t); } finally { if (statement != null) { try { statement.close(); } catch (Exception ex) { } } if (conn != null) { try { conn.close(); } catch (Exception ex) { } } LOG.info("Closed connection"); } LOG.info("Finished Testing DB Size Limit"); } /*private static void fixExchangeBatches() { LOG.info("Starting Fixing Exchange Batches"); try { ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); List<Service> services = serviceDalI.getAll(); for (Service service: services) { LOG.info("Doing " + service.getName()); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(service.getId()); for (UUID exchangeId: exchangeIds) { LOG.info(" Exchange " + exchangeId); List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } List<ResourceWrapper> resources = resourceDalI.getResourcesForBatch(exchangeBatch.getBatchId()); if (resources.isEmpty()) { continue; } ResourceWrapper first = resources.get(0); UUID patientId = first.getPatientId(); if (patientId != null) { exchangeBatch.setEdsPatientId(patientId); exchangeBatchDalI.save(exchangeBatch); LOG.info("Fixed batch " + exchangeBatch.getBatchId() + " -> " + exchangeBatch.getEdsPatientId()); } } } } LOG.info("Finished Fixing Exchange Batches"); } catch (Exception ex) { LOG.error("", ex); } }*/ /** * exports ADT Encounters for patients based on a CSV file produced using the below SQL --USE EDS DATABASE -- barts b5a08769-cbbe-4093-93d6-b696cd1da483 -- homerton 962d6a9a-5950-47ac-9e16-ebee56f9507a create table adt_patients ( service_id character(36), system_id character(36), nhs_number character varying(10), patient_id character(36) ); -- delete from adt_patients; select * from patient_search limit 10; select * from patient_link limit 10; insert into adt_patients select distinct ps.service_id, ps.system_id, ps.nhs_number, ps.patient_id from patient_search ps join patient_link pl on pl.patient_id = ps.patient_id join patient_link pl2 on pl.person_id = pl2.person_id join patient_search ps2 on ps2.patient_id = pl2.patient_id where ps.service_id IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a') and ps2.service_id NOT IN ('b5a08769-cbbe-4093-93d6-b696cd1da483', '962d6a9a-5950-47ac-9e16-ebee56f9507a'); select count(1) from adt_patients limit 100; select * from adt_patients limit 100; ---MOVE TABLE TO HL7 RECEIVER DB select count(1) from adt_patients; -- top 1000 patients with messages select * from mapping.resource_uuid where resource_type = 'Patient' limit 10; select * from log.message limit 10; create table adt_patient_counts ( nhs_number character varying(100), count int ); insert into adt_patient_counts select pid1, count(1) from log.message where pid1 is not null and pid1 <> '' group by pid1; select * from adt_patient_counts order by count desc limit 100; alter table adt_patients add count int; update adt_patients set count = adt_patient_counts.count from adt_patient_counts where adt_patients.nhs_number = adt_patient_counts.nhs_number; select count(1) from adt_patients where nhs_number is null; select * from adt_patients where nhs_number is not null and count is not null order by count desc limit 1000; */ /*private static void exportHl7Encounters(String sourceCsvPath, String outputPath) { LOG.info("Exporting HL7 Encounters from " + sourceCsvPath + " to " + outputPath); try { File sourceFile = new File(sourceCsvPath); CSVParser csvParser = CSVParser.parse(sourceFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); //"service_id","system_id","nhs_number","patient_id","count" int count = 0; HashMap<UUID, List<UUID>> serviceAndSystemIds = new HashMap<>(); HashMap<UUID, Integer> patientIds = new HashMap<>(); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); count ++; String serviceId = csvRecord.get("service_id"); String systemId = csvRecord.get("system_id"); String patientId = csvRecord.get("patient_id"); UUID serviceUuid = UUID.fromString(serviceId); List<UUID> systemIds = serviceAndSystemIds.get(serviceUuid); if (systemIds == null) { systemIds = new ArrayList<>(); serviceAndSystemIds.put(serviceUuid, systemIds); } systemIds.add(UUID.fromString(systemId)); patientIds.put(UUID.fromString(patientId), new Integer(count)); } csvParser.close(); ExchangeDalI exchangeDalI = DalProvider.factoryExchangeDal(); ResourceDalI resourceDalI = DalProvider.factoryResourceDal(); ExchangeBatchDalI exchangeBatchDalI = DalProvider.factoryExchangeBatchDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); ParserPool parser = new ParserPool(); Map<Integer, List<Object[]>> patientRows = new HashMap<>(); SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (UUID serviceId: serviceAndSystemIds.keySet()) { //List<UUID> systemIds = serviceAndSystemIds.get(serviceId); Service service = serviceDalI.getById(serviceId); String serviceName = service.getName(); LOG.info("Doing service " + serviceId + " " + serviceName); List<UUID> exchangeIds = exchangeDalI.getExchangeIdsForService(serviceId); LOG.info("Got " + exchangeIds.size() + " exchange IDs to scan"); int exchangeCount = 0; for (UUID exchangeId: exchangeIds) { exchangeCount ++; if (exchangeCount % 1000 == 0) { LOG.info("Done " + exchangeCount + " exchanges"); } List<ExchangeBatch> exchangeBatches = exchangeBatchDalI.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch: exchangeBatches) { UUID patientId = exchangeBatch.getEdsPatientId(); if (patientId != null && !patientIds.containsKey(patientId)) { continue; } Integer patientIdInt = patientIds.get(patientId); //get encounters for exchange batch UUID batchId = exchangeBatch.getBatchId(); List<ResourceWrapper> resourceWrappers = resourceDalI.getResourcesForBatch(serviceId, batchId); for (ResourceWrapper resourceWrapper: resourceWrappers) { if (resourceWrapper.isDeleted()) { continue; } String resourceType = resourceWrapper.getResourceType(); if (!resourceType.equals(ResourceType.Encounter.toString())) { continue; } LOG.info("Processing " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId()); String json = resourceWrapper.getResourceData(); Encounter fhirEncounter = (Encounter)parser.parse(json); Date date = null; if (fhirEncounter.hasPeriod()) { Period period = fhirEncounter.getPeriod(); if (period.hasStart()) { date = period.getStart(); } } String episodeId = null; if (fhirEncounter.hasEpisodeOfCare()) { Reference episodeReference = fhirEncounter.getEpisodeOfCare().get(0); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(episodeReference); EpisodeOfCare fhirEpisode = (EpisodeOfCare)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirEpisode != null) { if (fhirEpisode.hasIdentifier()) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_BARTS_FIN_EPISODE_ID); if (Strings.isNullOrEmpty(episodeId)) { episodeId = IdentifierHelper.findIdentifierValue(fhirEpisode.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_FIN_EPISODE_ID); } } } } String adtType = null; String adtCode = null; Extension extension = ExtensionConverter.findExtension(fhirEncounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (extension != null) { CodeableConcept codeableConcept = (CodeableConcept) extension.getValue(); Coding hl7MessageTypeCoding = CodeableConceptHelper.findCoding(codeableConcept, FhirUri.CODE_SYSTEM_HL7V2_MESSAGE_TYPE); if (hl7MessageTypeCoding != null) { adtType = hl7MessageTypeCoding.getDisplay(); adtCode = hl7MessageTypeCoding.getCode(); } } else { //for older formats of the transformed resources, the HL7 message type can only be found from the raw original exchange body try { Exchange exchange = exchangeDalI.getExchange(exchangeId); String exchangeBody = exchange.getBody(); Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(exchangeBody); for (Bundle.BundleEntryComponent entry: bundle.getEntry()) { if (entry.getResource() != null && entry.getResource() instanceof MessageHeader) { MessageHeader header = (MessageHeader)entry.getResource(); if (header.hasEvent()) { Coding coding = header.getEvent(); adtType = coding.getDisplay(); adtCode = coding.getCode(); } } } } catch (Exception ex) { //if the exchange body isn't a FHIR bundle, then we'll get an error by treating as such, so just ignore them } } String cls = null; if (fhirEncounter.hasClass_()) { Encounter.EncounterClass encounterClass = fhirEncounter.getClass_(); if (encounterClass == Encounter.EncounterClass.OTHER && fhirEncounter.hasClass_Element() && fhirEncounter.getClass_Element().hasExtension()) { for (Extension classExtension: fhirEncounter.getClass_Element().getExtension()) { if (classExtension.getUrl().equals(FhirExtensionUri.ENCOUNTER_CLASS)) { //not 100% of the type of the value, so just append to a String cls = "" + classExtension.getValue(); } } } if (Strings.isNullOrEmpty(cls)) { cls = encounterClass.toCode(); } } String type = null; if (fhirEncounter.hasType()) { //only seem to ever have one type CodeableConcept codeableConcept = fhirEncounter.getType().get(0); type = codeableConcept.getText(); } String status = null; if (fhirEncounter.hasStatus()) { Encounter.EncounterState encounterState = fhirEncounter.getStatus(); status = encounterState.toCode(); } String location = null; String locationType = null; if (fhirEncounter.hasLocation()) { //first location is always the current location Encounter.EncounterLocationComponent encounterLocation = fhirEncounter.getLocation().get(0); if (encounterLocation.hasLocation()) { Reference locationReference = encounterLocation.getLocation(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(locationReference); Location fhirLocation = (Location)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirLocation != null) { if (fhirLocation.hasName()) { location = fhirLocation.getName(); } if (fhirLocation.hasType()) { CodeableConcept typeCodeableConcept = fhirLocation.getType(); if (typeCodeableConcept.hasCoding()) { Coding coding = typeCodeableConcept.getCoding().get(0); locationType = coding.getDisplay(); } } } } } String clinician = null; if (fhirEncounter.hasParticipant()) { //first participant seems to be the interesting one Encounter.EncounterParticipantComponent encounterParticipant = fhirEncounter.getParticipant().get(0); if (encounterParticipant.hasIndividual()) { Reference practitionerReference = encounterParticipant.getIndividual(); ReferenceComponents comps = ReferenceHelper.getReferenceComponents(practitionerReference); Practitioner fhirPractitioner = (Practitioner)resourceDalI.getCurrentVersionAsResource(serviceId, comps.getResourceType(), comps.getId()); if (fhirPractitioner != null) { if (fhirPractitioner.hasName()) { HumanName name = fhirPractitioner.getName(); clinician = name.getText(); if (Strings.isNullOrEmpty(clinician)) { clinician = ""; for (StringType s: name.getPrefix()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getGiven()) { clinician += s.getValueNotNull(); clinician += " "; } for (StringType s: name.getFamily()) { clinician += s.getValueNotNull(); clinician += " "; } clinician = clinician.trim(); } } } } } Object[] row = new Object[12]; row[0] = serviceName; row[1] = patientIdInt.toString(); row[2] = sdfOutput.format(date); row[3] = episodeId; row[4] = adtCode; row[5] = adtType; row[6] = cls; row[7] = type; row[8] = status; row[9] = location; row[10] = locationType; row[11] = clinician; List<Object[]> rows = patientRows.get(patientIdInt); if (rows == null) { rows = new ArrayList<>(); patientRows.put(patientIdInt, rows); } rows.add(row); } } } } String[] outputColumnHeaders = new String[] {"Source", "Patient", "Date", "Episode ID", "ADT Message Code", "ADT Message Type", "Class", "Type", "Status", "Location", "Location Type", "Clinician"}; FileWriter fileWriter = new FileWriter(outputPath); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); CSVFormat format = CSVFormat.DEFAULT .withHeader(outputColumnHeaders) .withQuote('"'); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); for (int i=0; i <= count; i++) { Integer patientIdInt = new Integer(i); List<Object[]> rows = patientRows.get(patientIdInt); if (rows != null) { for (Object[] row: rows) { csvPrinter.printRecord(row); } } } csvPrinter.close(); bufferedWriter.close(); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Exporting Encounters from " + sourceCsvPath + " to " + outputPath); }*/ /*private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info(""); try { Thread.sleep(5000); } catch (Throwable ex) { LOG.error("", ex); } LOG.info("Done"); } }); }*/ private static void findEmisStartDates(String path, String outputPath) { LOG.info("Finding EMIS Start Dates in " + path + ", writing to " + outputPath); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm.ss"); Map<String, Date> startDates = new HashMap<>(); Map<String, String> servers = new HashMap<>(); Map<String, String> names = new HashMap<>(); Map<String, String> odsCodes = new HashMap<>(); Map<String, String> cdbNumbers = new HashMap<>(); Map<String, Set<String>> distinctPatients = new HashMap<>(); File root = new File(path); for (File sftpRoot: root.listFiles()) { LOG.info("Checking " + sftpRoot); Map<Date, File> extracts = new HashMap<>(); List<Date> extractDates = new ArrayList<>(); for (File extractRoot: sftpRoot.listFiles()) { Date d = sdf.parse(extractRoot.getName()); //LOG.info("" + extractRoot.getName() + " -> " + d); extracts.put(d, extractRoot); extractDates.add(d); } Collections.sort(extractDates); for (Date extractDate: extractDates) { File extractRoot = extracts.get(extractDate); LOG.info("Checking " + extractRoot); //read the sharing agreements file //e.g. 291_Agreements_SharingOrganisation_20150211164536_45E7CD20-EE37-41AB-90D6-DC9D4B03D102.csv File sharingAgreementsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("agreements_sharingorganisation") > -1 && name.endsWith(".csv")) { sharingAgreementsFile = f; break; } } if (sharingAgreementsFile == null) { LOG.info("Null agreements file for " + extractRoot); continue; } CSVParser csvParser = CSVParser.parse(sharingAgreementsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String activated = csvRecord.get("IsActivated"); String disabled = csvRecord.get("Disabled"); servers.put(orgGuid, sftpRoot.getName()); if (activated.equalsIgnoreCase("true")) { if (disabled.equalsIgnoreCase("false")) { Date d = sdf.parse(extractRoot.getName()); Date existingDate = startDates.get(orgGuid); if (existingDate == null) { startDates.put(orgGuid, d); } } else { if (startDates.containsKey(orgGuid)) { startDates.put(orgGuid, null); } } } } } finally { csvParser.close(); } //go through orgs file to get name, ods and cdb codes File orgsFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_organisation_") > -1 && name.endsWith(".csv")) { orgsFile = f; break; } } csvParser = CSVParser.parse(orgsFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String name = csvRecord.get("OrganisationName"); String odsCode = csvRecord.get("ODSCode"); String cdb = csvRecord.get("CDB"); names.put(orgGuid, name); odsCodes.put(orgGuid, odsCode); cdbNumbers.put(orgGuid, cdb); } } finally { csvParser.close(); } //go through patients file to get count File patientFile = null; for (File f: extractRoot.listFiles()) { String name = f.getName().toLowerCase(); if (name.indexOf("admin_patient_") > -1 && name.endsWith(".csv")) { patientFile = f; break; } } csvParser = CSVParser.parse(patientFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); try { Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String orgGuid = csvRecord.get("OrganisationGuid"); String patientGuid = csvRecord.get("PatientGuid"); String deleted = csvRecord.get("Deleted"); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); if (distinctPatientSet == null) { distinctPatientSet = new HashSet<>(); distinctPatients.put(orgGuid, distinctPatientSet); } if (deleted.equalsIgnoreCase("true")) { distinctPatientSet.remove(patientGuid); } else { distinctPatientSet.add(patientGuid); } } } finally { csvParser.close(); } } } SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd"); StringBuilder sb = new StringBuilder(); sb.append("Name,OdsCode,CDB,OrgGuid,StartDate,Server,Patients"); for (String orgGuid: startDates.keySet()) { Date startDate = startDates.get(orgGuid); String server = servers.get(orgGuid); String name = names.get(orgGuid); String odsCode = odsCodes.get(orgGuid); String cdbNumber = cdbNumbers.get(orgGuid); Set<String> distinctPatientSet = distinctPatients.get(orgGuid); String startDateDesc = null; if (startDate != null) { startDateDesc = sdfOutput.format(startDate); } Long countDistinctPatients = null; if (distinctPatientSet != null) { countDistinctPatients = new Long(distinctPatientSet.size()); } sb.append("\n"); sb.append("\"" + name + "\""); sb.append(","); sb.append("\"" + odsCode + "\""); sb.append(","); sb.append("\"" + cdbNumber + "\""); sb.append(","); sb.append("\"" + orgGuid + "\""); sb.append(","); sb.append(startDateDesc); sb.append(","); sb.append("\"" + server + "\""); sb.append(","); sb.append(countDistinctPatients); } LOG.info(sb.toString()); FileUtils.writeStringToFile(new File(outputPath), sb.toString()); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Finding Start Dates in " + path + ", writing to " + outputPath); } private static void findEncounterTerms(String path, String outputPath) { LOG.info("Finding Encounter Terms from " + path); Map<String, Long> hmResults = new HashMap<>(); //source term, source term snomed ID, source term snomed term - count try { File root = new File(path); File[] files = root.listFiles(); for (File readerRoot: files) { //emis001 LOG.info("Finding terms in " + readerRoot); //first read in all the coding files to build up our map of codes Map<String, String> hmCodes = new HashMap<>(); for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for codes in " + dateFolder); File f = findFile(dateFolder, "Coding_ClinicalCode"); if (f == null) { LOG.error("Failed to find coding file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String codeId = csvRecord.get("CodeId"); String term = csvRecord.get("Term"); String snomed = csvRecord.get("SnomedCTConceptId"); hmCodes.put(codeId, snomed + ",\"" + term + "\""); } csvParser.close(); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date cutoff = dateFormat.parse("2017-01-01"); //now process the consultation files themselves for (File dateFolder: readerRoot.listFiles()) { LOG.info("Looking for consultations in " + dateFolder); File f = findFile(dateFolder, "CareRecord_Consultation"); if (f == null) { LOG.error("Failed to find consultation file in " + dateFolder.getAbsolutePath()); continue; } CSVParser csvParser = CSVParser.parse(f, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Iterator<CSVRecord> csvIterator = csvParser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String term = csvRecord.get("ConsultationSourceTerm"); String codeId = csvRecord.get("ConsultationSourceCodeId"); if (Strings.isNullOrEmpty(term) && Strings.isNullOrEmpty(codeId)) { continue; } String date = csvRecord.get("EffectiveDate"); if (Strings.isNullOrEmpty(date)) { continue; } Date d = dateFormat.parse(date); if (d.before(cutoff)) { continue; } String line = "\"" + term + "\","; if (!Strings.isNullOrEmpty(codeId)) { String codeLookup = hmCodes.get(codeId); if (codeLookup == null) { LOG.error("Failed to find lookup for codeID " + codeId); continue; } line += codeLookup; } else { line += ","; } Long count = hmResults.get(line); if (count == null) { count = new Long(1); } else { count = new Long(count.longValue() + 1); } hmResults.put(line, count); } csvParser.close(); } } //save results to file StringBuilder output = new StringBuilder(); output.append("\"consultation term\",\"snomed concept ID\",\"snomed term\",\"count\""); output.append("\r\n"); for (String line: hmResults.keySet()) { Long count = hmResults.get(line); String combined = line + "," + count; output.append(combined); output.append("\r\n"); } LOG.info("FInished"); LOG.info(output.toString()); FileUtils.writeStringToFile(new File(outputPath), output.toString()); LOG.info("written output to " + outputPath); } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished finding Encounter Terms from " + path); } private static File findFile(File root, String token) throws Exception { for (File f: root.listFiles()) { String s = f.getName(); if (s.indexOf(token) > -1) { return f; } } return null; } /*private static void populateProtocolQueue(String serviceIdStr, String startingExchangeId) { LOG.info("Starting Populating Protocol Queue for " + serviceIdStr); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); if (serviceIdStr.equalsIgnoreCase("All")) { serviceIdStr = null; } try { List<Service> services = new ArrayList<>(); if (Strings.isNullOrEmpty(serviceIdStr)) { services = serviceRepository.getAll(); } else { UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); services.add(service); } for (Service service: services) { List<UUID> exchangeIds = auditRepository.getExchangeIdsForService(service.getId()); LOG.info("Found " + exchangeIds.size() + " exchangeIds for " + service.getName()); if (startingExchangeId != null) { UUID startingExchangeUuid = UUID.fromString(startingExchangeId); if (exchangeIds.contains(startingExchangeUuid)) { //if in the list, remove everything up to and including the starting exchange int index = exchangeIds.indexOf(startingExchangeUuid); LOG.info("Found starting exchange " + startingExchangeId + " at " + index + " so removing up to this point"); for (int i=index; i>=0; i--) { exchangeIds.remove(i); } startingExchangeId = null; } else { //if not in the list, skip all these exchanges LOG.info("List doesn't contain starting exchange " + startingExchangeId + " so skipping"); continue; } } QueueHelper.postToExchange(exchangeIds, "edsProtocol", null, true); } } catch (Exception ex) { LOG.error("", ex); } LOG.info("Finished Populating Protocol Queue for " + serviceIdStr); }*/ /*private static void findDeletedOrgs() { LOG.info("Starting finding deleted orgs"); ServiceDalI serviceRepository = DalProvider.factoryServiceDal(); ExchangeDalI auditRepository = DalProvider.factoryExchangeDal(); List<Service> services = new ArrayList<>(); try { for (Service service: serviceRepository.getAll()) { services.add(service); } } catch (Exception ex) { LOG.error("", ex); } services.sort((o1, o2) -> { String name1 = o1.getName(); String name2 = o2.getName(); return name1.compareToIgnoreCase(name2); }); for (Service service: services) { try { UUID serviceUuid = service.getId(); List<Exchange> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 1, new Date(0), new Date()); LOG.info("Service: " + service.getName() + " " + service.getLocalId()); if (exchangeByServices.isEmpty()) { LOG.info(" no exchange found!"); continue; } Exchange exchangeByService = exchangeByServices.get(0); UUID exchangeId = exchangeByService.getId(); Exchange exchange = auditRepository.getExchange(exchangeId); Map<String, String> headers = exchange.getHeaders(); String systemUuidStr = headers.get(HeaderKeys.SenderSystemUuid); UUID systemUuid = UUID.fromString(systemUuidStr); int batches = countBatches(exchangeId, serviceUuid, systemUuid); LOG.info(" Most recent exchange had " + batches + " batches"); if (batches > 1 && batches < 2000) { continue; } //go back until we find the FIRST exchange where it broke exchangeByServices = auditRepository.getExchangesByService(serviceUuid, 250, new Date(0), new Date()); for (int i=0; i<exchangeByServices.size(); i++) { exchangeByService = exchangeByServices.get(i); exchangeId = exchangeByService.getId(); batches = countBatches(exchangeId, serviceUuid, systemUuid); exchange = auditRepository.getExchange(exchangeId); Date timestamp = exchange.getTimestamp(); if (batches < 1 || batches > 2000) { LOG.info(" " + timestamp + " had " + batches); } if (batches > 1 && batches < 2000) { LOG.info(" " + timestamp + " had " + batches); break; } } } catch (Exception ex) { LOG.error("", ex); } } LOG.info("Finished finding deleted orgs"); }*/ private static int countBatches(UUID exchangeId, UUID serviceId, UUID systemId) throws Exception { int batches = 0; ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(serviceId, systemId, exchangeId); for (ExchangeTransformAudit audit: audits) { if (audit.getNumberBatchesCreated() != null) { batches += audit.getNumberBatchesCreated(); } } return batches; } /*private static void fixExchanges(UUID justThisService) { LOG.info("Fixing exchanges"); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId : exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } boolean changed = false; String body = exchange.getBody(); String[] files = body.split("\n"); if (files.length == 0) { continue; } for (int i=0; i<files.length; i++) { String original = files[i]; //remove /r characters String trimmed = original.trim(); //add the new prefix if (!trimmed.startsWith("sftpreader/EMIS001/")) { trimmed = "sftpreader/EMIS001/" + trimmed; } if (!original.equals(trimmed)) { files[i] = trimmed; changed = true; } } if (changed) { LOG.info("Fixed exchange " + exchangeId); LOG.info(body); body = String.join("\n", files); exchange.setBody(body); AuditWriter.writeExchange(exchange); } } } LOG.info("Fixed exchanges"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void deleteDataForService(UUID serviceId) { Service dbService = new ServiceRepository().getById(serviceId); //the delete will take some time, so do the delete in a separate thread LOG.info("Deleting all data for service " + dbService.getName() + " " + dbService.getId()); FhirDeletionService deletor = new FhirDeletionService(dbService); try { deletor.deleteData(); LOG.info("Completed deleting all data for service " + dbService.getName() + " " + dbService.getId()); } catch (Exception ex) { LOG.error("Error deleting service " + dbService.getName() + " " + dbService.getId(), ex); } }*/ /*private static void fixProblems(UUID serviceId, String sharedStoragePath, boolean testMode) { LOG.info("Fixing problems for service " + serviceId); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); List<ExchangeByService> exchangeByServiceList = auditRepository.getExchangesByService(serviceId, Integer.MAX_VALUE); //go backwards as the most recent is first for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); UUID exchangeId = exchangeByService.getExchangeId(); LOG.info("Doing exchange " + exchangeId); EmisCsvHelper helper = null; try { Exchange exchange = AuditWriter.readExchange(exchangeId); String exchangeBody = exchange.getBody(); String[] files = exchangeBody.split(java.lang.System.lineSeparator()); File orgDirectory = validateAndFindCommonDirectory(sharedStoragePath, files); Map<Class, AbstractCsvParser> allParsers = new HashMap<>(); String properVersion = null; String[] versions = new String[]{EmisCsvToFhirTransformer.VERSION_5_0, EmisCsvToFhirTransformer.VERSION_5_1, EmisCsvToFhirTransformer.VERSION_5_3, EmisCsvToFhirTransformer.VERSION_5_4}; for (String version: versions) { try { List<AbstractCsvParser> parsers = new ArrayList<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(Observation.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(DrugRecord.class, orgDirectory, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(IssueRecord.class, orgDirectory, version, true, parsers); for (AbstractCsvParser parser: parsers) { Class cls = parser.getClass(); allParsers.put(cls, parser); } properVersion = version; } catch (Exception ex) { //ignore } } if (allParsers.isEmpty()) { throw new Exception("Failed to open parsers for exchange " + exchangeId + " in folder " + orgDirectory); } UUID systemId = exchange.getHeaderAsUuid(HeaderKeys.SenderSystemUuid); //FhirResourceFiler dummyFiler = new FhirResourceFiler(exchangeId, serviceId, systemId, null, null, 10); if (helper == null) { helper = new EmisCsvHelper(findDataSharingAgreementGuid(new ArrayList<>(allParsers.values()))); } ObservationPreTransformer.transform(properVersion, allParsers, null, helper); IssueRecordPreTransformer.transform(properVersion, allParsers, null, helper); DrugRecordPreTransformer.transform(properVersion, allParsers, null, helper); Map<String, List<String>> problemChildren = helper.getProblemChildMap(); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (Map.Entry<String, List<String>> entry : problemChildren.entrySet()) { String patientLocallyUniqueId = entry.getKey().split(":")[0]; UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientLocallyUniqueId); if (edsPatientId == null) { throw new Exception("Failed to find edsPatientId for local Patient ID " + patientLocallyUniqueId + " in exchange " + exchangeId); } //find the batch ID for our patient UUID batchId = null; for (ExchangeBatch exchangeBatch: exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null && exchangeBatch.getEdsPatientId().equals(edsPatientId)) { batchId = exchangeBatch.getBatchId(); break; } } if (batchId == null) { throw new Exception("Failed to find batch ID for eds Patient ID " + edsPatientId + " in exchange " + exchangeId); } //find the EDS ID for our problem UUID edsProblemId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Condition, entry.getKey()); if (edsProblemId == null) { LOG.warn("No edsProblemId found for local ID " + entry.getKey() + " - assume bad data referring to non-existing problem?"); //throw new Exception("Failed to find edsProblemId for local Patient ID " + problemLocallyUniqueId + " in exchange " + exchangeId); } //convert our child IDs to EDS references List<Reference> references = new ArrayList<>(); HashSet<String> contentsSet = new HashSet<>(); contentsSet.addAll(entry.getValue()); for (String referenceValue : contentsSet) { Reference reference = ReferenceHelper.createReference(referenceValue); ReferenceComponents components = ReferenceHelper.getReferenceComponents(reference); String locallyUniqueId = components.getId(); ResourceType resourceType = components.getResourceType(); UUID edsResourceId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); Reference globallyUniqueReference = ReferenceHelper.createReference(resourceType, edsResourceId.toString()); references.add(globallyUniqueReference); } //find the resource for the problem itself ResourceByExchangeBatch problemResourceByExchangeBatch = null; List<ResourceByExchangeBatch> resources = resourceRepository.getResourcesForBatch(batchId, ResourceType.Condition.toString()); for (ResourceByExchangeBatch resourceByExchangeBatch: resources) { if (resourceByExchangeBatch.getResourceId().equals(edsProblemId)) { problemResourceByExchangeBatch = resourceByExchangeBatch; break; } } if (problemResourceByExchangeBatch == null) { throw new Exception("Problem not found for edsProblemId " + edsProblemId + " for exchange " + exchangeId); } if (problemResourceByExchangeBatch.getIsDeleted()) { LOG.warn("Problem " + edsProblemId + " is deleted, so not adding to it for exchange " + exchangeId); continue; } String json = problemResourceByExchangeBatch.getResourceData(); Condition fhirProblem = (Condition)PARSER_POOL.parse(json); //update the problems if (fhirProblem.hasContained()) { if (fhirProblem.getContained().size() > 1) { throw new Exception("Problem " + edsProblemId + " is has " + fhirProblem.getContained().size() + " contained resources for exchange " + exchangeId); } fhirProblem.getContained().clear(); } List_ list = new List_(); list.setId("Items"); fhirProblem.getContained().add(list); Extension extension = ExtensionConverter.findExtension(fhirProblem, FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE); if (extension == null) { Reference listReference = ReferenceHelper.createInternalReference("Items"); fhirProblem.addExtension(ExtensionConverter.createExtension(FhirExtensionUri.PROBLEM_ASSOCIATED_RESOURCE, listReference)); } for (Reference reference : references) { list.addEntry().setItem(reference); } String newJson = FhirSerializationHelper.serializeResource(fhirProblem); if (newJson.equals(json)) { LOG.warn("Skipping edsProblemId " + edsProblemId + " as JSON hasn't changed"); continue; } problemResourceByExchangeBatch.setResourceData(newJson); String resourceType = problemResourceByExchangeBatch.getResourceType(); UUID versionUuid = problemResourceByExchangeBatch.getVersion(); ResourceHistory problemResourceHistory = resourceRepository.getResourceHistoryByKey(edsProblemId, resourceType, versionUuid); problemResourceHistory.setResourceData(newJson); problemResourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(newJson)); ResourceByService problemResourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType, edsProblemId); if (problemResourceByService.getResourceData() == null) { problemResourceByService = null; LOG.warn("Not updating edsProblemId " + edsProblemId + " for exchange " + exchangeId + " as it's been subsequently delrted"); } else { problemResourceByService.setResourceData(newJson); } //save back to THREE tables if (!testMode) { resourceRepository.save(problemResourceByExchangeBatch); resourceRepository.save(problemResourceHistory); if (problemResourceByService != null) { resourceRepository.save(problemResourceByService); } LOG.info("Fixed edsProblemId " + edsProblemId + " for exchange Id " + exchangeId); } else { LOG.info("Would change edsProblemId " + edsProblemId + " to new JSON"); LOG.info(newJson); } } } catch (Exception ex) { LOG.error("Failed on exchange " + exchangeId, ex); break; } } LOG.info("Finished fixing problems for service " + serviceId); } private static String findDataSharingAgreementGuid(List<AbstractCsvParser> parsers) throws Exception { //we need a file name to work out the data sharing agreement ID, so just the first file we can find File f = parsers .iterator() .next() .getFile(); String name = Files.getNameWithoutExtension(f.getName()); String[] toks = name.split("_"); if (toks.length != 5) { throw new TransformException("Failed to extract data sharing agreement GUID from filename " + f.getName()); } return toks[4]; } private static void closeParsers(Collection<AbstractCsvParser> parsers) { for (AbstractCsvParser parser : parsers) { try { parser.close(); } catch (IOException ex) { //don't worry if this fails, as we're done anyway } } } private static File validateAndFindCommonDirectory(String sharedStoragePath, String[] files) throws Exception { String organisationDir = null; for (String file: files) { File f = new File(sharedStoragePath, file); if (!f.exists()) { LOG.error("Failed to find file {} in shared storage {}", file, sharedStoragePath); throw new FileNotFoundException("" + f + " doesn't exist"); } //LOG.info("Successfully found file {} in shared storage {}", file, sharedStoragePath); try { File orgDir = f.getParentFile(); if (organisationDir == null) { organisationDir = orgDir.getAbsolutePath(); } else { if (!organisationDir.equalsIgnoreCase(orgDir.getAbsolutePath())) { throw new Exception(); } } } catch (Exception ex) { throw new FileNotFoundException("" + f + " isn't in the expected directory structure within " + organisationDir); } } return new File(organisationDir); }*/ /*private static void testLogging() { while (true) { System.out.println("Checking logging at " + System.currentTimeMillis()); try { Thread.sleep(4000); } catch (Exception e) { e.printStackTrace(); } LOG.trace("trace logging"); LOG.debug("debug logging"); LOG.info("info logging"); LOG.warn("warn logging"); LOG.error("error logging"); } } */ /*private static void fixExchangeProtocols() { LOG.info("Fixing exchange protocols"); AuditRepository auditRepository = new AuditRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.Exchange LIMIT 1000;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); LOG.info("Processing exchange " + exchangeId); Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); List<String> newIds = new ArrayList<>(); String protocolJson = headers.get(HeaderKeys.Protocols); if (!headers.containsKey(HeaderKeys.Protocols)) { try { List<LibraryItem> libraryItemList = LibraryRepositoryHelper.getProtocolsByServiceId(serviceIdStr); // Get protocols where service is publisher newIds = libraryItemList.stream() .filter( libraryItem -> libraryItem.getProtocol().getServiceContract().stream() .anyMatch(sc -> sc.getType().equals(ServiceContractType.PUBLISHER) && sc.getService().getUuid().equals(serviceIdStr))) .map(t -> t.getUuid().toString()) .collect(Collectors.toList()); } catch (Exception e) { LOG.error("Failed to find protocols for exchange " + exchange.getExchangeId(), e); continue; } } else { try { JsonNode node = ObjectMapperPool.getInstance().readTree(protocolJson); for (int i = 0; i < node.size(); i++) { JsonNode libraryItemNode = node.get(i); JsonNode idNode = libraryItemNode.get("uuid"); String id = idNode.asText(); newIds.add(id); } } catch (Exception e) { LOG.error("Failed to read Json from " + protocolJson + " for exchange " + exchange.getExchangeId(), e); continue; } } try { if (newIds.isEmpty()) { headers.remove(HeaderKeys.Protocols); } else { String protocolsJson = ObjectMapperPool.getInstance().writeValueAsString(newIds.toArray()); headers.put(HeaderKeys.Protocols, protocolsJson); } } catch (JsonProcessingException e) { LOG.error("Unable to serialize protocols to JSON for exchange " + exchange.getExchangeId(), e); continue; } try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); } catch (JsonProcessingException e) { LOG.error("Failed to write exchange headers to Json for exchange " + exchange.getExchangeId(), e); continue; } auditRepository.save(exchange); } LOG.info("Finished fixing exchange protocols"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } if (headers.containsKey(HeaderKeys.SenderLocalIdentifier) && headers.containsKey(HeaderKeys.SenderOrganisationUuid)) { continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); Map<UUID, String> orgMap = service.getOrganisations(); if (orgMap.size() != 1) { LOG.error("Wrong number of orgs in service " + serviceId + " for exchange " + exchange.getExchangeId()); continue; } UUID orgId = orgMap .keySet() .stream() .collect(StreamExtension.firstOrNullCollector()); Organisation organisation = organisationRepository.getById(orgId); String odsCode = organisation.getNationalId(); headers.put(HeaderKeys.SenderLocalIdentifier, odsCode); headers.put(HeaderKeys.SenderOrganisationUuid, orgId.toString()); try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Creating exchange " + exchange.getExchangeId()); } LOG.info("Finished fixing exchange headers"); }*/ /*private static void fixExchangeHeaders() { LOG.info("Fixing exchange headers"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); OrganisationRepository organisationRepository = new OrganisationRepository(); LibraryRepository libraryRepository = new LibraryRepository(); List<Exchange> exchanges = new AuditRepository().getAllExchanges(); for (Exchange exchange: exchanges) { String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception ex) { LOG.error("Failed to parse headers for exchange " + exchange.getExchangeId(), ex); continue; } String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); if (Strings.isNullOrEmpty(serviceIdStr)) { LOG.error("Failed to find service ID for exchange " + exchange.getExchangeId()); continue; } boolean changed = false; UUID serviceId = UUID.fromString(serviceIdStr); Service service = serviceRepository.getById(serviceId); try { List<JsonServiceInterfaceEndpoint> endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint : endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface : system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid())) { if (!headers.containsKey(HeaderKeys.SourceSystem)) { headers.put(HeaderKeys.SourceSystem, technicalInterface.getMessageFormat()); changed = true; } if (!headers.containsKey(HeaderKeys.SystemVersion)) { headers.put(HeaderKeys.SystemVersion, technicalInterface.getMessageFormatVersion()); changed = true; } if (!headers.containsKey(HeaderKeys.SenderSystemUuid)) { headers.put(HeaderKeys.SenderSystemUuid, endpointSystemId.toString()); changed = true; } } } } } catch (Exception e) { LOG.error("Failed to find endpoint details for " + exchange.getExchangeId()); continue; } if (changed) { try { headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setHeaders(headerJson); auditRepository.save(exchange); LOG.info("Fixed exchange " + exchange.getExchangeId()); } } LOG.info("Finished fixing exchange headers"); }*/ /*private static void testConnection(String configName) { try { JsonNode config = ConfigManager.getConfigurationAsJson(configName, "enterprise"); String driverClass = config.get("driverClass").asText(); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName(driverClass); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void testConnection() { try { JsonNode config = ConfigManager.getConfigurationAsJson("postgres", "enterprise"); String url = config.get("url").asText(); String username = config.get("username").asText(); String password = config.get("password").asText(); //force the driver to be loaded Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); LOG.info("Connection ok"); conn.close(); } catch (Exception e) { LOG.error("", e); } }*/ /*private static void startEnterpriseStream(UUID serviceId, String configName, UUID exchangeIdStartFrom, UUID batchIdStartFrom) throws Exception { LOG.info("Starting Enterprise Streaming for " + serviceId + " using " + configName + " starting from exchange " + exchangeIdStartFrom + " and batch " + batchIdStartFrom); LOG.info("Testing database connection"); testConnection(configName); Service service = new ServiceRepository().getById(serviceId); List<UUID> orgIds = new ArrayList<>(service.getOrganisations().keySet()); UUID orgId = orgIds.get(0); List<ExchangeByService> exchangeByServiceList = new AuditRepository().getExchangesByService(serviceId, Integer.MAX_VALUE); for (int i=exchangeByServiceList.size()-1; i>=0; i--) { ExchangeByService exchangeByService = exchangeByServiceList.get(i); //for (ExchangeByService exchangeByService: exchangeByServiceList) { UUID exchangeId = exchangeByService.getExchangeId(); if (exchangeIdStartFrom != null) { if (!exchangeIdStartFrom.equals(exchangeId)) { continue; } else { //once we have a match, set to null so we don't skip any subsequent ones exchangeIdStartFrom = null; } } Exchange exchange = AuditWriter.readExchange(exchangeId); String senderOrgUuidStr = exchange.getHeader(HeaderKeys.SenderOrganisationUuid); UUID senderOrgUuid = UUID.fromString(senderOrgUuidStr); //this one had 90,000 batches and doesn't need doing again *//*if (exchangeId.equals(UUID.fromString("b9b93be0-afd8-11e6-8c16-c1d5a00342f3"))) { LOG.info("Skipping exchange " + exchangeId); continue; }*//* List<ExchangeBatch> exchangeBatches = new ExchangeBatchRepository().retrieveForExchangeId(exchangeId); LOG.info("Processing exchange " + exchangeId + " with " + exchangeBatches.size() + " batches"); for (int j=0; j<exchangeBatches.size(); j++) { ExchangeBatch exchangeBatch = exchangeBatches.get(j); UUID batchId = exchangeBatch.getBatchId(); if (batchIdStartFrom != null) { if (!batchIdStartFrom.equals(batchId)) { continue; } else { batchIdStartFrom = null; } } LOG.info("Processing exchange " + exchangeId + " and batch " + batchId + " " + (j+1) + "/" + exchangeBatches.size()); try { String outbound = FhirToEnterpriseCsvTransformer.transformFromFhir(senderOrgUuid, batchId, null); if (!Strings.isNullOrEmpty(outbound)) { EnterpriseFiler.file(outbound, configName); } } catch (Exception ex) { throw new PipelineException("Failed to process exchange " + exchangeId + " and batch " + batchId, ex); } } } }*/ /*private static void fixMissingExchanges() { LOG.info("Fixing missing exchanges"); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id, batch_id, inserted_at FROM ehr.exchange_batch LIMIT 600000;"); stmt.setFetchSize(100); Set<UUID> exchangeIdsDone = new HashSet<>(); AuditRepository auditRepository = new AuditRepository(); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); UUID batchId = row.get(1, UUID.class); Date date = row.getTimestamp(2); //LOG.info("Exchange " + exchangeId + " batch " + batchId + " date " + date); if (exchangeIdsDone.contains(exchangeId)) { continue; } if (auditRepository.getExchange(exchangeId) != null) { continue; } UUID serviceId = findServiceId(batchId, session); if (serviceId == null) { continue; } Exchange exchange = new Exchange(); ExchangeByService exchangeByService = new ExchangeByService(); ExchangeEvent exchangeEvent = new ExchangeEvent(); Map<String, String> headers = new HashMap<>(); headers.put(HeaderKeys.SenderServiceUuid, serviceId.toString()); String headersJson = null; try { headersJson = ObjectMapperPool.getInstance().writeValueAsString(headers); } catch (JsonProcessingException e) { //not throwing this exception further up, since it should never happen //and means we don't need to litter try/catches everywhere this is called from LOG.error("Failed to write exchange headers to Json", e); continue; } exchange.setBody("Body not available, as exchange re-created"); exchange.setExchangeId(exchangeId); exchange.setHeaders(headersJson); exchange.setTimestamp(date); exchangeByService.setExchangeId(exchangeId); exchangeByService.setServiceId(serviceId); exchangeByService.setTimestamp(date); exchangeEvent.setEventDesc("Created_By_Conversion"); exchangeEvent.setExchangeId(exchangeId); exchangeEvent.setTimestamp(new Date()); auditRepository.save(exchange); auditRepository.save(exchangeEvent); auditRepository.save(exchangeByService); exchangeIdsDone.add(exchangeId); LOG.info("Creating exchange " + exchangeId); } LOG.info("Finished exchange fix"); } private static UUID findServiceId(UUID batchId, Session session) { Statement stmt = new SimpleStatement("select resource_type, resource_id from ehr.resource_by_exchange_batch where batch_id = " + batchId + " LIMIT 1;"); ResultSet rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_by_exchange_batch for batch_id " + batchId); return null; } Row row = rs.one(); String resourceType = row.getString(0); UUID resourceId = row.get(1, UUID.class); stmt = new SimpleStatement("select service_id from ehr.resource_history where resource_type = '" + resourceType + "' and resource_id = " + resourceId + " LIMIT 1;"); rs = session.execute(stmt); if (rs.isExhausted()) { LOG.error("Failed to find resource_history for resource_type " + resourceType + " and resource_id " + resourceId); return null; } row = rs.one(); UUID serviceId = row.get(0, UUID.class); return serviceId; }*/ /*private static void fixExchangeEvents() { List<ExchangeEvent> events = new AuditRepository().getAllExchangeEvents(); for (ExchangeEvent event: events) { if (event.getEventDesc() != null) { continue; } String eventDesc = ""; int eventType = event.getEvent().intValue(); switch (eventType) { case 1: eventDesc = "Receive"; break; case 2: eventDesc = "Validate"; break; case 3: eventDesc = "Transform_Start"; break; case 4: eventDesc = "Transform_End"; break; case 5: eventDesc = "Send"; break; default: eventDesc = "??? " + eventType; } event.setEventDesc(eventDesc); new AuditRepository().save(null, event); } }*/ /*private static void fixExchanges() { AuditRepository auditRepository = new AuditRepository(); Map<UUID, Set<UUID>> existingOnes = new HashMap(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); List<Exchange> exchanges = auditRepository.getAllExchanges(); for (Exchange exchange: exchanges) { UUID exchangeUuid = exchange.getExchangeId(); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeUuid + " and Json " + headerJson); continue; } *//*String serviceId = headers.get(HeaderKeys.SenderServiceUuid); if (serviceId == null) { LOG.warn("No service ID found for exchange " + exchange.getExchangeId()); continue; } UUID serviceUuid = UUID.fromString(serviceId); Set<UUID> exchangeIdsDone = existingOnes.get(serviceUuid); if (exchangeIdsDone == null) { exchangeIdsDone = new HashSet<>(); List<ExchangeByService> exchangeByServices = auditRepository.getExchangesByService(serviceUuid, Integer.MAX_VALUE); for (ExchangeByService exchangeByService: exchangeByServices) { exchangeIdsDone.add(exchangeByService.getExchangeId()); } existingOnes.put(serviceUuid, exchangeIdsDone); } //create the exchange by service entity if (!exchangeIdsDone.contains(exchangeUuid)) { Date timestamp = exchange.getTimestamp(); ExchangeByService newOne = new ExchangeByService(); newOne.setExchangeId(exchangeUuid); newOne.setServiceId(serviceUuid); newOne.setTimestamp(timestamp); auditRepository.save(newOne); }*//* try { headers.remove(HeaderKeys.BatchIdsJson); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } if (!headers.containsKey(HeaderKeys.BatchIdsJson)) { //fix the batch IDs not being in the exchange List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeUuid); if (!batches.isEmpty()) { List<UUID> batchUuids = batches .stream() .map(t -> t.getBatchId()) .collect(Collectors.toList()); try { String batchUuidsStr = ObjectMapperPool.getInstance().writeValueAsString(batchUuids.toArray()); headers.put(HeaderKeys.BatchIdsJson, batchUuidsStr); String newHeaderJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(newHeaderJson); auditRepository.save(exchange, null); } catch (JsonProcessingException e) { LOG.error("Failed to populate batch IDs for exchange " + exchangeUuid, e); } } //} } }*/ /*private static UUID findSystemId(Service service, String software, String messageVersion) throws PipelineException { List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); String endpointInterfaceId = endpoint.getTechnicalInterfaceUuid().toString(); LibraryRepository libraryRepository = new LibraryRepository(); ActiveItem activeItem = libraryRepository.getActiveItemByItemId(endpointSystemId); Item item = libraryRepository.getItemByKey(endpointSystemId, activeItem.getAuditId()); LibraryItem libraryItem = QueryDocumentSerializer.readLibraryItemFromXml(item.getXmlContent()); System system = libraryItem.getSystem(); for (TechnicalInterface technicalInterface: system.getTechnicalInterface()) { if (endpointInterfaceId.equals(technicalInterface.getUuid()) && technicalInterface.getMessageFormat().equalsIgnoreCase(software) && technicalInterface.getMessageFormatVersion().equalsIgnoreCase(messageVersion)) { return endpointSystemId; } } } } catch (Exception e) { throw new PipelineException("Failed to process endpoints from service " + service.getId()); } return null; } */ /*private static void addSystemIdToExchangeHeaders() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid))) { LOG.info("Skipping exchange " + exchangeId + " as no service UUID"); continue; } if (!Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " as already got system UUID"); continue; } try { //work out service ID String serviceIdStr = headers.get(HeaderKeys.SenderServiceUuid); UUID serviceId = UUID.fromString(serviceIdStr); String software = headers.get(HeaderKeys.SourceSystem); String version = headers.get(HeaderKeys.SystemVersion); Service service = serviceRepository.getById(serviceId); UUID systemUuid = findSystemId(service, software, version); headers.put(HeaderKeys.SenderSystemUuid, systemUuid.toString()); //work out protocol IDs try { String newProtocolIdsJson = DetermineRelevantProtocolIds.getProtocolIdsForPublisherService(serviceIdStr); headers.put(HeaderKeys.ProtocolIds, newProtocolIdsJson); } catch (Exception ex) { LOG.error("Failed to recalculate protocols for " + exchangeId + ": " + ex.getMessage()); } //save to DB headerJson = ObjectMapperPool.getInstance().writeValueAsString(headers); exchange.setHeaders(headerJson); auditRepository.save(exchange); } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); }*/ /*private static void populateExchangeBatchPatients() throws Exception { LOG.info("populateExchangeBatchPatients"); AuditRepository auditRepository = new AuditRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); //ServiceRepository serviceRepository = new ServiceRepository(); //OrganisationRepository organisationRepository = new OrganisationRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT exchange_id FROM audit.exchange LIMIT 500;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID exchangeId = row.get(0, UUID.class); org.endeavourhealth.core.data.audit.models.Exchange exchange = auditRepository.getExchange(exchangeId); String headerJson = exchange.getHeaders(); HashMap<String, String> headers = null; try { headers = ObjectMapperPool.getInstance().readValue(headerJson, HashMap.class); } catch (Exception e) { LOG.error("Failed to read headers for exchange " + exchangeId + " and Json " + headerJson); continue; } if (Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderServiceUuid)) || Strings.isNullOrEmpty(headers.get(HeaderKeys.SenderSystemUuid))) { LOG.info("Skipping exchange " + exchangeId + " because no service or system in header"); continue; } try { UUID serviceId = UUID.fromString(headers.get(HeaderKeys.SenderServiceUuid)); UUID systemId = UUID.fromString(headers.get(HeaderKeys.SenderSystemUuid)); List<ExchangeBatch> exchangeBatches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch exchangeBatch : exchangeBatches) { if (exchangeBatch.getEdsPatientId() != null) { continue; } UUID batchId = exchangeBatch.getBatchId(); List<ResourceByExchangeBatch> resourceWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Patient.toString()); if (resourceWrappers.isEmpty()) { continue; } List<UUID> patientIds = new ArrayList<>(); for (ResourceByExchangeBatch resourceWrapper : resourceWrappers) { UUID patientId = resourceWrapper.getResourceId(); if (resourceWrapper.getIsDeleted()) { deleteEntirePatientRecord(patientId, serviceId, systemId, exchangeId, batchId); } if (!patientIds.contains(patientId)) { patientIds.add(patientId); } } if (patientIds.size() != 1) { LOG.info("Skipping exchange " + exchangeId + " and batch " + batchId + " because found " + patientIds.size() + " patient IDs"); continue; } UUID patientId = patientIds.get(0); exchangeBatch.setEdsPatientId(patientId); exchangeBatchRepository.save(exchangeBatch); } } catch (Exception ex) { LOG.error("Error with exchange " + exchangeId, ex); } } LOG.info("Finished populateExchangeBatchPatients"); } private static void deleteEntirePatientRecord(UUID patientId, UUID serviceId, UUID systemId, UUID exchangeId, UUID batchId) throws Exception { FhirStorageService storageService = new FhirStorageService(serviceId, systemId); ResourceRepository resourceRepository = new ResourceRepository(); List<ResourceByPatient> resourceWrappers = resourceRepository.getResourcesByPatient(serviceId, systemId, patientId); for (ResourceByPatient resourceWrapper: resourceWrappers) { String json = resourceWrapper.getResourceData(); Resource resource = new JsonParser().parse(json); storageService.exchangeBatchDelete(exchangeId, batchId, resource); } }*/ /*private static void convertPatientSearch() { LOG.info("Converting Patient Search"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.EpisodeOfCare.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { EpisodeOfCare episodeOfCare = (EpisodeOfCare) new JsonParser().parse(resourceWrapper.getResourceData()); String patientId = ReferenceHelper.getReferenceId(episodeOfCare.getPatient()); ResourceHistory patientWrapper = resourceRepository.getCurrentVersion(ResourceType.Patient.toString(), UUID.fromString(patientId)); if (Strings.isNullOrEmpty(patientWrapper.getResourceData())) { continue; } Patient patient = (Patient) new JsonParser().parse(patientWrapper.getResourceData()); PatientSearchHelper.update(serviceId, systemId, patient); PatientSearchHelper.update(serviceId, systemId, episodeOfCare); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Search"); } catch (Exception ex) { LOG.error("", ex); } }*/ private static List<UUID> findSystemIds(Service service) throws Exception { List<UUID> ret = new ArrayList<>(); List<JsonServiceInterfaceEndpoint> endpoints = null; try { endpoints = ObjectMapperPool.getInstance().readValue(service.getEndpoints(), new TypeReference<List<JsonServiceInterfaceEndpoint>>() {}); for (JsonServiceInterfaceEndpoint endpoint: endpoints) { UUID endpointSystemId = endpoint.getSystemUuid(); ret.add(endpointSystemId); } } catch (Exception e) { throw new Exception("Failed to process endpoints from service " + service.getId()); } return ret; } /*private static void convertPatientLink() { LOG.info("Converting Patient Link"); ResourceRepository resourceRepository = new ResourceRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); LOG.info("Doing service " + service.getName()); for (UUID systemId : findSystemIds(service)) { List<ResourceByService> resourceWrappers = resourceRepository.getResourcesByService(serviceId, systemId, ResourceType.Patient.toString()); for (ResourceByService resourceWrapper: resourceWrappers) { if (Strings.isNullOrEmpty(resourceWrapper.getResourceData())) { continue; } try { Patient patient = (Patient)new JsonParser().parse(resourceWrapper.getResourceData()); PatientLinkHelper.updatePersonId(patient); } catch (Exception ex) { LOG.error("Failed on " + resourceWrapper.getResourceType() + " " + resourceWrapper.getResourceId(), ex); } } } } LOG.info("Converted Patient Link"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, ResourceHistory> resourcesFixed = new HashMap<>(); Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Set<UUID> batchIdsToPutInProtocolQueue = new HashSet<>(); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); ResourceFiler filer = new ResourceFiler(exchangeId, serviceId, systemId, null, null, 1); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); ProblemPreTransformer.transform(version, parsers, filer, helper); ObservationPreTransformer.transform(version, parsers, filer, helper); DrugRecordPreTransformer.transform(version, parsers, filer, helper); IssueRecordPreTransformer.transform(version, parsers, filer, helper); DiaryPreTransformer.transform(version, parsers, filer, helper); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient)parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() && !patientParser.getDeleted()) { PatientTransformer.createResource(patientParser, filer, helper, version); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { ConsultationTransformer.createResource(consultationParser, filer, helper, version); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { ObservationTransformer.createResource(observationParser, filer, helper, version); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { DiaryTransformer.createResource(diaryParser, filer, helper, version); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { DrugRecordTransformer.createResource(drugRecordParser, filer, helper, version); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord)parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { IssueRecordTransformer.createResource(issueRecordParser, filer, helper, version); } } issueRecordParser.close(); filer.waitToFinish(); //just to close the thread pool, even though it's not been used List<Resource> resources = filer.getNewResources(); for (Resource resource: resources) { String patientId = IdHelper.getPatientId(resource); UUID edsPatientId = UUID.fromString(patientId); ResourceType resourceType = resource.getResourceType(); UUID resourceId = UUID.fromString(resource.getId()); boolean foundResourceInDbBatch = false; List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds != null) { for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), resourceId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; } foundResourceInDbBatch = true; for (ResourceByExchangeBatch resourceByExchangeBatch : resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (!Strings.isNullOrEmpty(json)) { LOG.warn("JSON already in resource " + resourceType + " " + resourceId); } else { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); LOG.info("Saved resource by batch " + resourceType + " " + resourceId + " in batch " + batchId); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(resourceId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + resourceId + " and version " + versionUuid); } resourceHistory.setIsDeleted(false); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceHistory.setSchemaVersion("0.1"); resourceRepository.save(resourceByExchangeBatch); resourceRepository.save(resourceHistory); batchIdsToPutInProtocolQueue.add(batchId); String key = resourceType.toString() + ":" + resourceId; resourcesFixed.put(key, resourceHistory); } //if a patient became confidential, we will have deleted all resources for that //patient, so we need to undo that too //to undelete WHOLE patient record //1. if THIS resource is a patient //2. get all other deletes from the same exchange batch //3. delete those from resource_by_exchange_batch (the deleted ones only) //4. delete same ones from resource_history //5. retrieve most recent resource_history //6. if not deleted, add to resources fixed if (resourceType == ResourceType.Patient) { List<ResourceByExchangeBatch> resourcesInSameBatch = resourceRepository.getResourcesForBatch(batchId); LOG.info("Undeleting " + resourcesInSameBatch.size() + " resources for batch " + batchId); for (ResourceByExchangeBatch resourceInSameBatch: resourcesInSameBatch) { if (!resourceInSameBatch.getIsDeleted()) { continue; } //patient and episode resources will be restored by the above stuff, so don't try //to do it again if (resourceInSameBatch.getResourceType().equals(ResourceType.Patient.toString()) || resourceInSameBatch.getResourceType().equals(ResourceType.EpisodeOfCare.toString())) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(resourceInSameBatch.getResourceId(), resourceInSameBatch.getResourceType(), resourceInSameBatch.getVersion()); mapperResourceByExchangeBatch.delete(resourceInSameBatch); mapperResourceHistory.delete(deletedResourceHistory); batchIdsToPutInProtocolQueue.add(batchId); //check the most recent version of our resource, and if it's not deleted, add to the list to update the resource_by_service table ResourceHistory mostRecentDeletedResourceHistory = resourceRepository.getCurrentVersion(resourceInSameBatch.getResourceType(), resourceInSameBatch.getResourceId()); if (mostRecentDeletedResourceHistory != null && !mostRecentDeletedResourceHistory.getIsDeleted()) { String key2 = mostRecentDeletedResourceHistory.getResourceType().toString() + ":" + mostRecentDeletedResourceHistory.getResourceId(); resourcesFixed.put(key2, mostRecentDeletedResourceHistory); } } } } } } //if we didn't find records in the DB to update, then if (!foundResourceInDbBatch) { //we can't generate a back-dated time UUID, but we need one so the resource_history //table is in order. To get a suitable time UUID, we just pull out the first exchange batch for our exchange, //and the batch ID is actually a time UUID that was allocated around the right time ExchangeBatch firstBatch = exchangeBatchRepository.retrieveFirstForExchangeId(exchangeId); //if there was no batch for the exchange, then the exchange wasn't processed at all. So skip this exchange //and we'll pick up the same patient data in a following exchange if (firstBatch == null) { continue; } UUID versionUuid = firstBatch.getBatchId(); //find suitable batch ID UUID batchId = null; if (batchIds != null && batchIds.size() > 0) { batchId = batchIds.get(batchIds.size()-1); } else { //create new batch ID if not found ExchangeBatch exchangeBatch = new ExchangeBatch(); exchangeBatch.setBatchId(UUIDs.timeBased()); exchangeBatch.setExchangeId(exchangeId); exchangeBatch.setInsertedAt(new Date()); exchangeBatch.setEdsPatientId(edsPatientId); exchangeBatchRepository.save(exchangeBatch); batchId = exchangeBatch.getBatchId(); //add to map for next resource if (batchIds == null) { batchIds = new ArrayList<>(); } batchIds.add(batchId); batchesPerPatient.put(edsPatientId, batchIds); } String json = parserPool.composeString(resource); ResourceHistory resourceHistory = new ResourceHistory(); resourceHistory.setResourceId(resourceId); resourceHistory.setResourceType(resourceType.toString()); resourceHistory.setVersion(versionUuid); resourceHistory.setCreatedAt(new Date()); resourceHistory.setServiceId(serviceId); resourceHistory.setSystemId(systemId); resourceHistory.setIsDeleted(false); resourceHistory.setSchemaVersion("0.1"); resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); ResourceByExchangeBatch resourceByExchangeBatch = new ResourceByExchangeBatch(); resourceByExchangeBatch.setBatchId(batchId); resourceByExchangeBatch.setExchangeId(exchangeId); resourceByExchangeBatch.setResourceType(resourceType.toString()); resourceByExchangeBatch.setResourceId(resourceId); resourceByExchangeBatch.setVersion(versionUuid); resourceByExchangeBatch.setIsDeleted(false); resourceByExchangeBatch.setSchemaVersion("0.1"); resourceByExchangeBatch.setResourceData(json); resourceRepository.save(resourceHistory); resourceRepository.save(resourceByExchangeBatch); batchIdsToPutInProtocolQueue.add(batchId); } } if (!batchIdsToPutInProtocolQueue.isEmpty()) { exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchIdsToPutInProtocolQueue); } } //update the resource_by_service table (and the resource_by_patient view) for (ResourceHistory resourceHistory: resourcesFixed.values()) { UUID latestVersionUpdatedUuid = resourceHistory.getVersion(); ResourceHistory latestVersion = resourceRepository.getCurrentVersion(resourceHistory.getResourceType(), resourceHistory.getResourceId()); UUID latestVersionUuid = latestVersion.getVersion(); //if there have been subsequent updates to the resource, then skip it if (!latestVersionUuid.equals(latestVersionUpdatedUuid)) { continue; } Resource resource = parserPool.parse(resourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment)metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(resourceHistory.getServiceId()); resourceByService.setSystemId(resourceHistory.getSystemId()); resourceByService.setResourceType(resourceHistory.getResourceType()); resourceByService.setResourceId(resourceHistory.getResourceId()); resourceByService.setCurrentVersion(resourceHistory.getVersion()); resourceByService.setUpdatedAt(resourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(resourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(resourceHistory.getResourceData()); resourceRepository.save(resourceByService); //call out to our patient search and person matching services if (resource instanceof Patient) { PatientLinkHelper.updatePersonId((Patient)resource); PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (Patient)resource); } else if (resource instanceof EpisodeOfCare) { PatientSearchHelper.update(serviceId, resourceHistory.getSystemId(), (EpisodeOfCare)resource); } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Fixing Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixDeletedAppointments(String sharedStoragePath, boolean saveChanges, UUID justThisService) { LOG.info("Fixing Deleted Appointments using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); MappingManager mappingManager = CassandraConnector.getInstance().getMappingManager(); Mapper<ResourceHistory> mapperResourceHistory = mappingManager.mapper(ResourceHistory.class); Mapper<ResourceByExchangeBatch> mapperResourceByExchangeBatch = mappingManager.mapper(ResourceByExchangeBatch.class); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class, dir, version, true, parsers); //find any deleted patients List<UUID> deletedPatientUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getDeleted()) { //find the EDS patient ID for this local guid String patientGuid = patientParser.getPatientGuid(); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } deletedPatientUuids.add(edsPatientId); } } patientParser.close(); //go through the appts file to find properly deleted appt GUIDS List<UUID> deletedApptUuids = new ArrayList<>(); org.endeavourhealth.transform.emis.csv.schema.appointment.Slot apptParser = (org.endeavourhealth.transform.emis.csv.schema.appointment.Slot) parsers.get(org.endeavourhealth.transform.emis.csv.schema.appointment.Slot.class); while (apptParser.nextRecord()) { if (apptParser.getDeleted()) { String patientGuid = apptParser.getPatientGuid(); String slotGuid = apptParser.getSlotGuid(); if (!Strings.isNullOrEmpty(patientGuid)) { String uniqueLocalId = EmisCsvHelper.createUniqueId(patientGuid, slotGuid); UUID edsApptId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Appointment, uniqueLocalId); deletedApptUuids.add(edsApptId); } } } apptParser.close(); for (UUID edsPatientId : deletedPatientUuids) { List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; } for (UUID batchId : batchIds) { List<ResourceByExchangeBatch> apptWrappers = resourceRepository.getResourcesForBatch(batchId, ResourceType.Appointment.toString()); for (ResourceByExchangeBatch apptWrapper : apptWrappers) { //ignore non-deleted appts if (!apptWrapper.getIsDeleted()) { continue; } //if the appt was deleted legitamately, then skip it UUID apptId = apptWrapper.getResourceId(); if (deletedApptUuids.contains(apptId)) { continue; } ResourceHistory deletedResourceHistory = resourceRepository.getResourceHistoryByKey(apptWrapper.getResourceId(), apptWrapper.getResourceType(), apptWrapper.getVersion()); if (saveChanges) { mapperResourceByExchangeBatch.delete(apptWrapper); mapperResourceHistory.delete(deletedResourceHistory); } LOG.info("Un-deleted " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " in batch " + batchId + " patient " + edsPatientId); //now get the most recent instance of the appointment, and if it's NOT deleted, insert into the resource_by_service table ResourceHistory mostRecentResourceHistory = resourceRepository.getCurrentVersion(apptWrapper.getResourceType(), apptWrapper.getResourceId()); if (mostRecentResourceHistory != null && !mostRecentResourceHistory.getIsDeleted()) { Resource resource = parserPool.parse(mostRecentResourceHistory.getResourceData()); ResourceMetadata metadata = MetadataFactory.createMetadata(resource); UUID patientId = ((PatientCompartment) metadata).getPatientId(); ResourceByService resourceByService = new ResourceByService(); resourceByService.setServiceId(mostRecentResourceHistory.getServiceId()); resourceByService.setSystemId(mostRecentResourceHistory.getSystemId()); resourceByService.setResourceType(mostRecentResourceHistory.getResourceType()); resourceByService.setResourceId(mostRecentResourceHistory.getResourceId()); resourceByService.setCurrentVersion(mostRecentResourceHistory.getVersion()); resourceByService.setUpdatedAt(mostRecentResourceHistory.getCreatedAt()); resourceByService.setPatientId(patientId); resourceByService.setSchemaVersion(mostRecentResourceHistory.getSchemaVersion()); resourceByService.setResourceMetadata(JsonSerializer.serialize(metadata)); resourceByService.setResourceData(mostRecentResourceHistory.getResourceData()); if (saveChanges) { resourceRepository.save(resourceByService); } LOG.info("Restored " + apptWrapper.getResourceType() + " " + apptWrapper.getResourceId() + " to resource_by_service table"); } } } } } } LOG.info("Finished Deleted Appointments Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixReviews(String sharedStoragePath, UUID justThisService) { LOG.info("Fixing Reviews using path " + sharedStoragePath + " and service " + justThisService); ResourceRepository resourceRepository = new ResourceRepository(); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ParserPool parserPool = new ParserPool(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); Map<String, Long> problemCodes = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); LOG.info("Doing Emis CSV exchange " + exchangeId + " with " + batches.size() + " batches"); for (ExchangeBatch batch: batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem problemParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation)parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (problemParser.nextRecord()) { String patientGuid = problemParser.getPatientGuid(); String observationGuid = problemParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (!problemCodes.containsKey(key)) { problemCodes.put(key, null); } } problemParser.close(); while (observationParser.nextRecord()) { String patientGuid = observationParser.getPatientGuid(); String observationGuid = observationParser.getObservationGuid(); String key = patientGuid + ":" + observationGuid; if (problemCodes.containsKey(key)) { Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } problemCodes.put(key, codeId); } } observationParser.close(); LOG.info("Found " + problemCodes.size() + " problem codes so far"); String dataSharingAgreementId = EmisCsvToFhirTransformer.findDataSharingAgreementGuid(f); EmisCsvHelper helper = new EmisCsvHelper(dataSharingAgreementId); while (observationParser.nextRecord()) { String problemGuid = observationParser.getProblemGuid(); if (!Strings.isNullOrEmpty(problemGuid)) { String patientGuid = observationParser.getPatientGuid(); Long codeId = observationParser.getCodeId(); if (codeId == null) { continue; } String key = patientGuid + ":" + problemGuid; Long problemCodeId = problemCodes.get(key); if (problemCodeId == null || problemCodeId.longValue() != codeId.longValue()) { continue; } //if here, our code is the same as the problem, so it's a review String locallyUniqueId = patientGuid + ":" + observationParser.getObservationGuid(); ResourceType resourceType = ObservationTransformer.getTargetResourceType(observationParser, helper); for (UUID systemId: systemIds) { UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, patientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + patientGuid); } UUID edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); if (edsObservationId == null) { //try observations as diagnostic reports, because it could be one of those instead if (resourceType == ResourceType.Observation) { resourceType = ResourceType.DiagnosticReport; edsObservationId = IdHelper.getEdsResourceId(serviceId, systemId, resourceType, locallyUniqueId); } if (edsObservationId == null) { throw new Exception("Failed to find observation ID for service " + serviceId + " system " + systemId + " resourceType " + resourceType + " local ID " + locallyUniqueId); } } List<UUID> batchIds = batchesPerPatient.get(edsPatientId); if (batchIds == null) { //if there are no batches for this patient, we'll be handling this data in another exchange continue; //throw new Exception("Failed to find batch ID for patient " + edsPatientId + " in exchange " + exchangeId + " for resource " + resourceType + " " + edsObservationId); } for (UUID batchId: batchIds) { List<ResourceByExchangeBatch> resourceByExchangeBatches = resourceRepository.getResourcesForBatch(batchId, resourceType.toString(), edsObservationId); if (resourceByExchangeBatches.isEmpty()) { //if we've deleted data, this will be null continue; //throw new Exception("No resources found for batch " + batchId + " resource type " + resourceType + " and resource id " + edsObservationId); } for (ResourceByExchangeBatch resourceByExchangeBatch: resourceByExchangeBatches) { String json = resourceByExchangeBatch.getResourceData(); if (Strings.isNullOrEmpty(json)) { throw new Exception("No JSON in resource " + resourceType + " " + edsObservationId + " in batch " + batchId); } Resource resource = parserPool.parse(json); if (addReviewExtension((DomainResource)resource)) { json = parserPool.composeString(resource); resourceByExchangeBatch.setResourceData(json); LOG.info("Changed " + resourceType + " " + edsObservationId + " to have extension in batch " + batchId); resourceRepository.save(resourceByExchangeBatch); UUID versionUuid = resourceByExchangeBatch.getVersion(); ResourceHistory resourceHistory = resourceRepository.getResourceHistoryByKey(edsObservationId, resourceType.toString(), versionUuid); if (resourceHistory == null) { throw new Exception("Failed to find resource history for " + resourceType + " " + edsObservationId + " and version " + versionUuid); } resourceHistory.setResourceData(json); resourceHistory.setResourceChecksum(FhirStorageService.generateChecksum(json)); resourceRepository.save(resourceHistory); ResourceByService resourceByService = resourceRepository.getResourceByServiceByKey(serviceId, systemId, resourceType.toString(), edsObservationId); if (resourceByService != null) { UUID serviceVersionUuid = resourceByService.getCurrentVersion(); if (serviceVersionUuid.equals(versionUuid)) { resourceByService.setResourceData(json); resourceRepository.save(resourceByService); } } } else { LOG.info("" + resourceType + " " + edsObservationId + " already has extension"); } } } } //1. find out resource type originall saved from //2. retrieve from resource_by_exchange_batch //3. update resource in resource_by_exchange_batch //4. retrieve from resource_history //5. update resource_history //6. retrieve record from resource_by_service //7. if resource_by_service version UUID matches the resource_history updated, then update that too } } observationParser.close(); } } LOG.info("Finished Fixing Reviews"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static boolean addReviewExtension(DomainResource resource) { if (ExtensionConverter.hasExtension(resource, FhirExtensionUri.IS_REVIEW)) { return false; } Extension extension = ExtensionConverter.createExtension(FhirExtensionUri.IS_REVIEW, new BooleanType(true)); resource.addExtension(extension); return true; }*/ /*private static void runProtocolsForConfidentialPatients(String sharedStoragePath, UUID justThisService) { LOG.info("Running Protocols for Confidential Patients using path " + sharedStoragePath + " and service " + justThisService); ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); try { Iterable<Service> iterable = new ServiceRepository().getAll(); for (Service service : iterable) { UUID serviceId = service.getId(); if (justThisService != null && !service.getId().equals(justThisService)) { LOG.info("Skipping service " + service.getName()); continue; } //once we match the servce, set this to null to do all other services justThisService = null; LOG.info("Doing service " + service.getName()); List<UUID> systemIds = findSystemIds(service); List<String> interestingPatientGuids = new ArrayList<>(); Map<UUID, Map<UUID, List<UUID>>> batchesPerPatientPerExchange = new HashMap<>(); List<UUID> exchangeIds = new AuditRepository().getExchangeIdsForService(serviceId); for (UUID exchangeId: exchangeIds) { Exchange exchange = AuditWriter.readExchange(exchangeId); String software = exchange.getHeader(HeaderKeys.SourceSystem); if (!software.equalsIgnoreCase(MessageFormat.EMIS_CSV)) { continue; } String body = exchange.getBody(); String[] files = body.split(java.lang.System.lineSeparator()); if (files.length == 0) { continue; } LOG.info("Doing Emis CSV exchange " + exchangeId); Map<UUID, List<UUID>> batchesPerPatient = new HashMap<>(); List<ExchangeBatch> batches = exchangeBatchRepository.retrieveForExchangeId(exchangeId); for (ExchangeBatch batch : batches) { UUID patientId = batch.getEdsPatientId(); if (patientId != null) { List<UUID> batchIds = batchesPerPatient.get(patientId); if (batchIds == null) { batchIds = new ArrayList<>(); batchesPerPatient.put(patientId, batchIds); } batchIds.add(batch.getBatchId()); } } batchesPerPatientPerExchange.put(exchangeId, batchesPerPatient); File f = new File(sharedStoragePath, files[0]); File dir = f.getParentFile(); String version = EmisCsvToFhirTransformer.determineVersion(dir); Map<Class, AbstractCsvParser> parsers = new HashMap<>(); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Problem.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class, dir, version, true, parsers); EmisCsvToFhirTransformer.findFileAndOpenParser(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class, dir, version, true, parsers); org.endeavourhealth.transform.emis.csv.schema.admin.Patient patientParser = (org.endeavourhealth.transform.emis.csv.schema.admin.Patient) parsers.get(org.endeavourhealth.transform.emis.csv.schema.admin.Patient.class); while (patientParser.nextRecord()) { if (patientParser.getIsConfidential() || patientParser.getDeleted()) { interestingPatientGuids.add(patientParser.getPatientGuid()); } } patientParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation consultationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Consultation.class); while (consultationParser.nextRecord()) { if (consultationParser.getIsConfidential() && !consultationParser.getDeleted()) { interestingPatientGuids.add(consultationParser.getPatientGuid()); } } consultationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation observationParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Observation.class); while (observationParser.nextRecord()) { if (observationParser.getIsConfidential() && !observationParser.getDeleted()) { interestingPatientGuids.add(observationParser.getPatientGuid()); } } observationParser.close(); org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary diaryParser = (org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary) parsers.get(org.endeavourhealth.transform.emis.csv.schema.careRecord.Diary.class); while (diaryParser.nextRecord()) { if (diaryParser.getIsConfidential() && !diaryParser.getDeleted()) { interestingPatientGuids.add(diaryParser.getPatientGuid()); } } diaryParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord drugRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.DrugRecord.class); while (drugRecordParser.nextRecord()) { if (drugRecordParser.getIsConfidential() && !drugRecordParser.getDeleted()) { interestingPatientGuids.add(drugRecordParser.getPatientGuid()); } } drugRecordParser.close(); org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord issueRecordParser = (org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord) parsers.get(org.endeavourhealth.transform.emis.csv.schema.prescribing.IssueRecord.class); while (issueRecordParser.nextRecord()) { if (issueRecordParser.getIsConfidential() && !issueRecordParser.getDeleted()) { interestingPatientGuids.add(issueRecordParser.getPatientGuid()); } } issueRecordParser.close(); } Map<UUID, Set<UUID>> exchangeBatchesToPutInProtocolQueue = new HashMap<>(); for (String interestingPatientGuid: interestingPatientGuids) { if (systemIds.size() > 1) { throw new Exception("Multiple system IDs for service " + serviceId); } UUID systemId = systemIds.get(0); UUID edsPatientId = IdHelper.getEdsResourceId(serviceId, systemId, ResourceType.Patient, interestingPatientGuid); if (edsPatientId == null) { throw new Exception("Failed to find patient ID for service " + serviceId + " system " + systemId + " resourceType " + ResourceType.Patient + " local ID " + interestingPatientGuid); } for (UUID exchangeId: batchesPerPatientPerExchange.keySet()) { Map<UUID, List<UUID>> batchesPerPatient = batchesPerPatientPerExchange.get(exchangeId); List<UUID> batches = batchesPerPatient.get(edsPatientId); if (batches != null) { Set<UUID> batchesForExchange = exchangeBatchesToPutInProtocolQueue.get(exchangeId); if (batchesForExchange == null) { batchesForExchange = new HashSet<>(); exchangeBatchesToPutInProtocolQueue.put(exchangeId, batchesForExchange); } batchesForExchange.addAll(batches); } } } if (!exchangeBatchesToPutInProtocolQueue.isEmpty()) { //find the config for our protocol queue String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatchesToPutInProtocolQueue.keySet()) { Set<UUID> batchIds = exchangeBatchesToPutInProtocolQueue.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } } LOG.info("Finished Running Protocols for Confidential Patients"); } catch (Exception ex) { LOG.error("", ex); } }*/ /*private static void fixOrgs() { LOG.info("Posting orgs to protocol queue"); String[] orgIds = new String[]{ "332f31a2-7b28-47cb-af6f-18f65440d43d", "c893d66b-eb89-4657-9f53-94c5867e7ed9"}; ExchangeBatchRepository exchangeBatchRepository = new ExchangeBatchRepository(); ResourceRepository resourceRepository = new ResourceRepository(); Map<UUID, Set<UUID>> exchangeBatches = new HashMap<>(); for (String orgId: orgIds) { LOG.info("Doing org ID " + orgId); UUID orgUuid = UUID.fromString(orgId); try { //select batch_id from ehr.resource_by_exchange_batch where resource_type = 'Organization' and resource_id = 8f465517-729b-4ad9-b405-92b487047f19 LIMIT 1 ALLOW FILTERING; ResourceByExchangeBatch resourceByExchangeBatch = resourceRepository.getFirstResourceByExchangeBatch(ResourceType.Organization.toString(), orgUuid); UUID batchId = resourceByExchangeBatch.getBatchId(); //select exchange_id from ehr.exchange_batch where batch_id = 1a940e10-1535-11e7-a29d-a90b99186399 LIMIT 1 ALLOW FILTERING; ExchangeBatch exchangeBatch = exchangeBatchRepository.retrieveFirstForBatchId(batchId); UUID exchangeId = exchangeBatch.getExchangeId(); Set<UUID> list = exchangeBatches.get(exchangeId); if (list == null) { list = new HashSet<>(); exchangeBatches.put(exchangeId, list); } list.add(batchId); } catch (Exception ex) { LOG.error("", ex); break; } } try { //find the config for our protocol queue (which is in the inbound config) String configXml = ConfigManager.getConfiguration("inbound", "queuereader"); //the config XML may be one of two serialised classes, so we use a try/catch to safely try both if necessary QueueReaderConfiguration configuration = ConfigDeserialiser.deserialise(configXml); Pipeline pipeline = configuration.getPipeline(); PostMessageToExchangeConfig config = pipeline .getPipelineComponents() .stream() .filter(t -> t instanceof PostMessageToExchangeConfig) .map(t -> (PostMessageToExchangeConfig) t) .filter(t -> t.getExchange().equalsIgnoreCase("EdsProtocol")) .collect(StreamExtension.singleOrNullCollector()); //post to the protocol exchange for (UUID exchangeId : exchangeBatches.keySet()) { Set<UUID> batchIds = exchangeBatches.get(exchangeId); org.endeavourhealth.core.messaging.exchange.Exchange exchange = AuditWriter.readExchange(exchangeId); String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIds); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); LOG.info("Posting exchange " + exchangeId + " batch " + batchIdString); PostMessageToExchange component = new PostMessageToExchange(config); component.process(exchange); } } catch (Exception ex) { LOG.error("", ex); return; } LOG.info("Finished posting orgs to protocol queue"); }*/ /*private static void findCodes() { LOG.info("Finding missing codes"); AuditRepository auditRepository = new AuditRepository(); ServiceRepository serviceRepository = new ServiceRepository(); Session session = CassandraConnector.getInstance().getSession(); Statement stmt = new SimpleStatement("SELECT service_id, system_id, exchange_id, version FROM audit.exchange_transform_audit ALLOW FILTERING;"); stmt.setFetchSize(100); ResultSet rs = session.execute(stmt); while (!rs.isExhausted()) { Row row = rs.one(); UUID serviceId = row.get(0, UUID.class); UUID systemId = row.get(1, UUID.class); UUID exchangeId = row.get(2, UUID.class); UUID version = row.get(3, UUID.class); ExchangeTransformAudit audit = auditRepository.getExchangeTransformAudit(serviceId, systemId, exchangeId, version); String xml = audit.getErrorXml(); if (xml == null) { continue; } String codePrefix = "Failed to find clinical code CodeableConcept for codeId "; int codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " clinical code " + code + " from " + audit.getStarted()); continue; } codePrefix = "Failed to find medication CodeableConcept for codeId "; codeIndex = xml.indexOf(codePrefix); if (codeIndex > -1) { int startIndex = codeIndex + codePrefix.length(); int tagEndIndex = xml.indexOf("<", startIndex); String code = xml.substring(startIndex, tagEndIndex); Service service = serviceRepository.getById(serviceId); String name = service.getName(); LOG.info(name + " drug code " + code + " from " + audit.getStarted()); continue; } } LOG.info("Finished finding missing codes"); }*/ private static void createTppSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating TPP Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createTppSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating TPP Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createTppSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } //LOG.info("Doing dir " + sourceFile); createTppSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withHeader(); CSVParser parser = new CSVParser(br, format); String filterColumn = null; Map<String, Integer> headerMap = parser.getHeaderMap(); if (headerMap.containsKey("IDPatient")) { filterColumn = "IDPatient"; } else if (name.equalsIgnoreCase("SRPatient.csv")) { filterColumn = "RowIdentifier"; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } String[] columnHeaders = new String[headerMap.size()]; Iterator<String> headerIterator = headerMap.keySet().iterator(); while (headerIterator.hasNext()) { String headerName = headerIterator.next(); int headerIndex = headerMap.get(headerName); columnHeaders[headerIndex] = headerName; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format.withHeader(columnHeaders)); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); /*} else { //the 2.1 files are going to be a pain to split by patient, so just copy them over LOG.info("Copying 2.1 file " + sourceFile); copyFile(sourceFile, destFile); }*/ } } } private static void createVisionSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Vision Subset"); try { Set<String> personIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } personIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createVisionSubsetForFile(sourceDir, destDir, personIds); LOG.info("Finished Creating Vision Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createVisionSubsetForFile(File sourceDir, File destDir, Set<String> personIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createVisionSubsetForFile(sourceFile, destFile, personIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; if (name.contains("encounter_data") || name.contains("journal_data") || name.contains("patient_data") || name.contains("referral_data")) { filterColumn = 0; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String patientId = csvRecord.get(filterColumn); if (personIds.contains(patientId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } private static void createAdastraSubset(String sourceDirPath, String destDirPath, String samplePatientsFile) { LOG.info("Creating Adastra Subset"); try { Set<String> caseIds = new HashSet<>(); List<String> lines = Files.readAllLines(new File(samplePatientsFile).toPath()); for (String line: lines) { line = line.trim(); //ignore comments if (line.startsWith("#")) { continue; } //adastra extract files are all keyed on caseId caseIds.add(line); } File sourceDir = new File(sourceDirPath); File destDir = new File(destDirPath); if (!destDir.exists()) { destDir.mkdirs(); } createAdastraSubsetForFile(sourceDir, destDir, caseIds); LOG.info("Finished Creating Adastra Subset"); } catch (Throwable t) { LOG.error("", t); } } private static void createAdastraSubsetForFile(File sourceDir, File destDir, Set<String> caseIds) throws Exception { File[] files = sourceDir.listFiles(); LOG.info("Found " + files.length + " files in " + sourceDir); for (File sourceFile: files) { String name = sourceFile.getName(); File destFile = new File(destDir, name); if (sourceFile.isDirectory()) { if (!destFile.exists()) { destFile.mkdirs(); } createAdastraSubsetForFile(sourceFile, destFile, caseIds); } else { if (destFile.exists()) { destFile.delete(); } LOG.info("Checking file " + sourceFile); //skip any non-CSV file String ext = FilenameUtils.getExtension(name); if (!ext.equalsIgnoreCase("csv")) { LOG.info("Skipping as not a CSV file"); continue; } FileReader fr = new FileReader(sourceFile); BufferedReader br = new BufferedReader(fr); //fully quote destination file to fix CRLF in columns CSVFormat format = CSVFormat.DEFAULT.withDelimiter('|'); CSVParser parser = new CSVParser(br, format); int filterColumn = -1; //CaseRef column at 0 if (name.contains("NOTES") || name.contains("CASEQUESTIONS") || name.contains("OUTCOMES") || name.contains("CONSULTATION") || name.contains("CLINICALCODES") || name.contains("PRESCRIPTIONS") || name.contains("PATIENT")) { filterColumn = 0; } else if (name.contains("CASE")) { //CaseRef column at 2 filterColumn = 2; } else if (name.contains("PROVIDER")) { //CaseRef column at 7 filterColumn = 7; } else { //if no patient column, just copy the file parser.close(); LOG.info("Copying non-patient file " + sourceFile); copyFile(sourceFile, destFile); continue; } PrintWriter fw = new PrintWriter(destFile); BufferedWriter bw = new BufferedWriter(fw); CSVPrinter printer = new CSVPrinter(bw, format); Iterator<CSVRecord> csvIterator = parser.iterator(); while (csvIterator.hasNext()) { CSVRecord csvRecord = csvIterator.next(); String caseId = csvRecord.get(filterColumn); if (caseIds.contains(caseId)) { printer.printRecord(csvRecord); printer.flush(); } } parser.close(); printer.close(); } } } } /*class ResourceFiler extends FhirResourceFiler { public ResourceFiler(UUID exchangeId, UUID serviceId, UUID systemId, TransformError transformError, List<UUID> batchIdsCreated, int maxFilingThreads) { super(exchangeId, serviceId, systemId, transformError, batchIdsCreated, maxFilingThreads); } private List<Resource> newResources = new ArrayList<>(); public List<Resource> getNewResources() { return newResources; } @Override public void saveAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling saveAdminResource"); } @Override public void deleteAdminResource(CsvCurrentState parserState, boolean mapIds, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deleteAdminResource"); } @Override public void savePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { for (Resource resource: resources) { if (mapIds) { IdHelper.mapIds(getServiceId(), getSystemId(), resource); } newResources.add(resource); } } @Override public void deletePatientResource(CsvCurrentState parserState, boolean mapIds, String patientId, Resource... resources) throws Exception { throw new Exception("shouldn't be calling deletePatientResource"); } }*/
New transform repo
src/eds-queuereader/src/main/java/org/endeavourhealth/queuereader/Main.java
New transform repo
Java
apache-2.0
e54a591ddaf20f75f6e7037c98215247e7f73791
0
jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient
package org.sagebionetworks.web.unitserver; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import static org.sagebionetworks.repo.model.EntityBundle.*; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.client.exceptions.SynapseBadRequestException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.client.exceptions.SynapseNotFoundException; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.EvaluationStatus; import org.sagebionetworks.evaluation.model.UserEvaluationPermissions; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.*; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.doi.Doi; import org.sagebionetworks.repo.model.doi.DoiStatus; import org.sagebionetworks.repo.model.entity.query.SortDirection; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyRequest; import org.sagebionetworks.repo.model.file.BatchFileHandleCopyResult; import org.sagebionetworks.repo.model.file.CompleteAllChunksRequest; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandleCopyRequest; import org.sagebionetworks.repo.model.file.FileHandleCopyResult; import org.sagebionetworks.repo.model.file.FileHandleResults; import org.sagebionetworks.repo.model.file.FileResultFailureCode; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.State; import org.sagebionetworks.repo.model.file.UploadDaemonStatus; import org.sagebionetworks.repo.model.file.UploadDestination; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken; import org.sagebionetworks.repo.model.message.Settings; import org.sagebionetworks.repo.model.principal.AddEmailInfo; import org.sagebionetworks.repo.model.principal.PrincipalAliasRequest; import org.sagebionetworks.repo.model.principal.PrincipalAliasResponse; import org.sagebionetworks.repo.model.project.ExternalS3StorageLocationSetting; import org.sagebionetworks.repo.model.project.ExternalStorageLocationSetting; import org.sagebionetworks.repo.model.project.ProjectSetting; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.StorageLocationSetting; import org.sagebionetworks.repo.model.project.UploadDestinationListSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.Quiz; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.table.ColumnChange; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.TableSchemaChangeRequest; import org.sagebionetworks.repo.model.table.TableUpdateRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.ViewType; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot; import org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.wiki.WikiHeader; import org.sagebionetworks.repo.model.wiki.WikiPage; import org.sagebionetworks.schema.adapter.AdapterFactory; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.AdapterFactoryImpl; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.util.SerializationUtils; import org.sagebionetworks.web.client.view.TeamRequestBundle; import org.sagebionetworks.web.server.servlet.MarkdownCacheRequest; import org.sagebionetworks.web.server.servlet.NotificationTokenType; import org.sagebionetworks.web.server.servlet.ServiceUrlProvider; import org.sagebionetworks.web.server.servlet.SynapseClientImpl; import org.sagebionetworks.web.server.servlet.SynapseProvider; import org.sagebionetworks.web.server.servlet.TokenProvider; import org.sagebionetworks.web.shared.AccessRequirementUtils; import org.sagebionetworks.web.shared.EntityBundlePlus; import org.sagebionetworks.web.shared.OpenTeamInvitationBundle; import org.sagebionetworks.web.shared.ProjectPagedResults; import org.sagebionetworks.web.shared.TeamBundle; import org.sagebionetworks.web.shared.TeamMemberBundle; import org.sagebionetworks.web.shared.TeamMemberPagedResults; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.shared.exceptions.BadRequestException; import org.sagebionetworks.web.shared.exceptions.ConflictException; import org.sagebionetworks.web.shared.exceptions.NotFoundException; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import org.sagebionetworks.web.shared.exceptions.UnauthorizedException; import org.sagebionetworks.web.shared.exceptions.UnknownErrorException; import org.sagebionetworks.web.shared.users.AclUtils; import org.sagebionetworks.web.shared.users.PermissionLevel; import com.google.appengine.repackaged.com.google.common.base.Objects; import com.google.common.cache.Cache; /** * Test for the SynapseClientImpl * * @author John * */ public class SynapseClientImplTest { private static final String BANNER_2 = "Another Banner"; private static final String BANNER_1 = "Banner 1"; public static final String TEST_HOME_PAGE_BASE = "http://mysynapse.org/"; public static final String MY_USER_PROFILE_OWNER_ID = "MyOwnerID"; SynapseProvider mockSynapseProvider; TokenProvider mockTokenProvider; ServiceUrlProvider mockUrlProvider; SynapseClient mockSynapse; SynapseClientImpl synapseClient; String entityId = "123"; String inviteeUserId = "900"; UserProfile inviteeUserProfile; ExampleEntity entity; Annotations annos; UserEntityPermissions eup; UserEvaluationPermissions userEvaluationPermissions; List<EntityHeader> batchHeaderResults; String testFileName = "testFileEntity.R"; EntityPath path; org.sagebionetworks.reflection.model.PaginatedResults<UserGroup> pgugs; org.sagebionetworks.reflection.model.PaginatedResults<UserProfile> pgups; org.sagebionetworks.reflection.model.PaginatedResults<Team> pguts; Team teamA, teamZ; AccessControlList acl; WikiPage page; V2WikiPage v2Page; S3FileHandle handle; Evaluation mockEvaluation; UserSessionData mockUserSessionData; UserProfile mockUserProfile; MembershipInvtnSubmission testInvitation; PaginatedResults mockPaginatedMembershipRequest; Activity mockActivity; MessageToUser sentMessage; Long storageLocationId = 9090L; UserProfile testUserProfile; Long version = 1L; //Token testing NotificationSettingsSignedToken notificationSettingsToken; JoinTeamSignedToken joinTeamToken; String encodedJoinTeamToken, encodedNotificationSettingsToken; @Mock UserGroupHeaderResponsePage mockUserGroupHeaderResponsePage; @Mock UserGroupHeader mockUserGroupHeader; @Mock PrincipalAliasResponse mockPrincipalAliasResponse; @Mock ColumnModel mockOldColumnModel; @Mock ColumnModel mockNewColumnModel; @Mock ColumnModel mockNewColumnModelAfterCreate; @Mock BatchFileHandleCopyResult mockBatchCopyResults; @Mock FileHandleCopyResult mockFileHandleCopyResult; @Mock FileEntity mockFileEntity; @Mock FileHandleCopyRequest mockFileHandleCopyRequest; List<FileHandleCopyResult> batchCopyResultsList; public static final String OLD_COLUMN_MODEL_ID = "4444"; public static final String NEW_COLUMN_MODEL_ID = "837837"; private static final String testUserId = "myUserId"; private static final String EVAL_ID_1 = "eval ID 1"; private static final String EVAL_ID_2 = "eval ID 2"; private static AdapterFactory adapterFactory = new AdapterFactoryImpl(); private TeamMembershipStatus membershipStatus; @Before public void before() throws SynapseException, JSONObjectAdapterException { MockitoAnnotations.initMocks(this); mockSynapse = Mockito.mock(SynapseClient.class); mockSynapseProvider = Mockito.mock(SynapseProvider.class); mockUrlProvider = Mockito.mock(ServiceUrlProvider.class); when(mockSynapseProvider.createNewClient()).thenReturn(mockSynapse); mockTokenProvider = Mockito.mock(TokenProvider.class); mockPaginatedMembershipRequest = Mockito.mock(PaginatedResults.class); mockActivity = Mockito.mock(Activity.class); when(mockPaginatedMembershipRequest.getTotalNumberOfResults()).thenReturn(3L); synapseClient = new SynapseClientImpl(); synapseClient.setSynapseProvider(mockSynapseProvider); synapseClient.setTokenProvider(mockTokenProvider); synapseClient.setServiceUrlProvider(mockUrlProvider); // Setup the the entity entity = new ExampleEntity(); entity.setId(entityId); entity.setEntityType(ExampleEntity.class.getName()); entity.setModifiedBy(testUserId); // the mock synapse should return this object when(mockSynapse.getEntityById(entityId)).thenReturn(entity); // Setup the annotations annos = new Annotations(); annos.setId(entityId); annos.addAnnotation("string", "a string value"); // the mock synapse should return this object when(mockSynapse.getAnnotations(entityId)).thenReturn(annos); // Setup the Permissions eup = new UserEntityPermissions(); eup.setCanDelete(true); eup.setCanView(false); eup.setOwnerPrincipalId(999L); // the mock synapse should return this object when(mockSynapse.getUsersEntityPermissions(entityId)).thenReturn(eup); // user can change permissions on eval 2, but not on 1 userEvaluationPermissions = new UserEvaluationPermissions(); userEvaluationPermissions.setCanChangePermissions(false); when(mockSynapse.getUserEvaluationPermissions(EVAL_ID_1)).thenReturn( userEvaluationPermissions); userEvaluationPermissions = new UserEvaluationPermissions(); userEvaluationPermissions.setCanChangePermissions(true); when(mockSynapse.getUserEvaluationPermissions(EVAL_ID_2)).thenReturn( userEvaluationPermissions); when(mockOldColumnModel.getId()).thenReturn(OLD_COLUMN_MODEL_ID); when(mockNewColumnModelAfterCreate.getId()).thenReturn(NEW_COLUMN_MODEL_ID); // Setup the path path = new EntityPath(); path.setPath(new ArrayList<EntityHeader>()); EntityHeader header = new EntityHeader(); header.setId(entityId); header.setName("RomperRuuuu"); path.getPath().add(header); // the mock synapse should return this object when(mockSynapse.getEntityPath(entityId)).thenReturn(path); pgugs = new org.sagebionetworks.reflection.model.PaginatedResults<UserGroup>(); List<UserGroup> ugs = new ArrayList<UserGroup>(); ugs.add(new UserGroup()); pgugs.setResults(ugs); when(mockSynapse.getGroups(anyInt(), anyInt())).thenReturn(pgugs); pgups = new org.sagebionetworks.reflection.model.PaginatedResults<UserProfile>(); List<UserProfile> ups = new ArrayList<UserProfile>(); ups.add(new UserProfile()); pgups.setResults(ups); when(mockSynapse.getUsers(anyInt(), anyInt())).thenReturn(pgups); pguts = new org.sagebionetworks.reflection.model.PaginatedResults<Team>(); List<Team> uts = new ArrayList<Team>(); teamZ = new Team(); teamZ.setId("1"); teamZ.setName("zygote"); uts.add(teamZ); teamA = new Team(); teamA.setId("2"); teamA.setName("Amplitude"); uts.add(teamA); pguts.setResults(uts); when(mockSynapse.getTeamsForUser(anyString(), anyInt(), anyInt())) .thenReturn(pguts); acl = new AccessControlList(); acl.setId("sys999"); Set<ResourceAccess> ras = new HashSet<ResourceAccess>(); ResourceAccess ra = new ResourceAccess(); ra.setPrincipalId(101L); ra.setAccessType(AclUtils .getACCESS_TYPEs(PermissionLevel.CAN_ADMINISTER)); acl.setResourceAccess(ras); when(mockSynapse.getACL(anyString())).thenReturn(acl); when(mockSynapse.createACL((AccessControlList) any())).thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any())).thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any(), eq(true))) .thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any(), eq(false))) .thenReturn(acl); when(mockSynapse.updateTeamACL(any(AccessControlList.class))).thenReturn(acl); when(mockSynapse.getTeamACL(anyString())).thenReturn(acl); EntityHeader bene = new EntityHeader(); bene.setId("syn999"); when(mockSynapse.getEntityBenefactor(anyString())).thenReturn(bene); org.sagebionetworks.reflection.model.PaginatedResults<EntityHeader> batchHeaders = new org.sagebionetworks.reflection.model.PaginatedResults<EntityHeader>(); batchHeaderResults = new ArrayList<EntityHeader>(); for (int i = 0; i < 10; i++) { EntityHeader h = new EntityHeader(); h.setId("syn" + i); batchHeaderResults.add(h); } batchHeaders.setResults(batchHeaderResults); when(mockSynapse.getEntityHeaderBatch(anyList())).thenReturn( batchHeaders); List<AccessRequirement> accessRequirements = new ArrayList<AccessRequirement>(); accessRequirements.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD)); int mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH | HAS_CHILDREN | ACCESS_REQUIREMENTS | UNMET_ACCESS_REQUIREMENTS; int emptyMask = 0; EntityBundle bundle = new EntityBundle(); bundle.setEntity(entity); bundle.setAnnotations(annos); bundle.setPermissions(eup); bundle.setPath(path); bundle.setHasChildren(false); bundle.setAccessRequirements(accessRequirements); bundle.setUnmetAccessRequirements(accessRequirements); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(mask))) .thenReturn(bundle); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(ENTITY | ANNOTATIONS | ROOT_WIKI_ID | FILE_HANDLES | PERMISSIONS | BENEFACTOR_ACL))) .thenReturn(bundle); EntityBundle emptyBundle = new EntityBundle(); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(emptyMask))) .thenReturn(emptyBundle); when(mockSynapse.canAccess("syn101", ACCESS_TYPE.READ)) .thenReturn(true); page = new WikiPage(); page.setId("testId"); page.setMarkdown("my markdown"); page.setParentWikiId(null); page.setTitle("A Title"); v2Page = new V2WikiPage(); v2Page.setId("v2TestId"); v2Page.setEtag("122333"); handle = new S3FileHandle(); handle.setId("4422"); handle.setBucketName("bucket"); handle.setFileName(testFileName); handle.setKey("key"); when(mockSynapse.getRawFileHandle(anyString())).thenReturn(handle); org.sagebionetworks.reflection.model.PaginatedResults<AccessRequirement> ars = new org.sagebionetworks.reflection.model.PaginatedResults<AccessRequirement>(); ars.setTotalNumberOfResults(0); ars.setResults(new ArrayList<AccessRequirement>()); when( mockSynapse .getAccessRequirements(any(RestrictableObjectDescriptor.class))) .thenReturn(ars); when( mockSynapse.getUnmetAccessRequirements( any(RestrictableObjectDescriptor.class), any(ACCESS_TYPE.class))).thenReturn(ars); mockEvaluation = Mockito.mock(Evaluation.class); when(mockEvaluation.getStatus()).thenReturn(EvaluationStatus.OPEN); when(mockSynapse.getEvaluation(anyString())).thenReturn(mockEvaluation); mockUserSessionData = Mockito.mock(UserSessionData.class); mockUserProfile = Mockito.mock(UserProfile.class); when(mockSynapse.getUserSessionData()).thenReturn(mockUserSessionData); when(mockUserSessionData.getProfile()).thenReturn(mockUserProfile); when(mockUserProfile.getOwnerId()).thenReturn(MY_USER_PROFILE_OWNER_ID); when(mockSynapse.getMyProfile()).thenReturn(mockUserProfile); UploadDaemonStatus status = new UploadDaemonStatus(); String fileHandleId = "myFileHandleId"; status.setFileHandleId(fileHandleId); status.setState(State.COMPLETED); when(mockSynapse.getCompleteUploadDaemonStatus(anyString())) .thenReturn(status); status = new UploadDaemonStatus(); status.setState(State.PROCESSING); status.setPercentComplete(.05d); when(mockSynapse.startUploadDeamon(any(CompleteAllChunksRequest.class))) .thenReturn(status); PaginatedResults<MembershipInvitation> openInvites = new PaginatedResults<MembershipInvitation>(); openInvites.setTotalNumberOfResults(0); when( mockSynapse.getOpenMembershipInvitations(anyString(), anyString(), anyLong(), anyLong())).thenReturn( openInvites); PaginatedResults<MembershipRequest> openRequests = new PaginatedResults<MembershipRequest>(); openRequests.setTotalNumberOfResults(0); when( mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(openRequests); membershipStatus = new TeamMembershipStatus(); membershipStatus.setCanJoin(false); membershipStatus.setHasOpenInvitation(false); membershipStatus.setHasOpenRequest(false); membershipStatus.setHasUnmetAccessRequirement(false); membershipStatus.setIsMember(false); membershipStatus.setMembershipApprovalRequired(false); when(mockSynapse.getTeamMembershipStatus(anyString(), anyString())) .thenReturn(membershipStatus); sentMessage = new MessageToUser(); sentMessage.setId("987"); when(mockSynapse.sendMessage(any(MessageToUser.class))).thenReturn(sentMessage); when(mockSynapse.sendMessage(any(MessageToUser.class), anyString())).thenReturn(sentMessage); // getMyProjects getUserProjects PaginatedResults headers = new PaginatedResults<ProjectHeader>(); headers.setTotalNumberOfResults(1100); List<ProjectHeader> projectHeaders = new ArrayList(); List<UserProfile> userProfile = new ArrayList(); projectHeaders.add(new ProjectHeader()); headers.setResults(projectHeaders); when( mockSynapse.getMyProjects(any(ProjectListType.class), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); when( mockSynapse.getProjectsFromUser(anyLong(), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); when( mockSynapse.getProjectsForTeam(anyLong(), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); testUserProfile = new UserProfile(); testUserProfile.setUserName("Test User"); when(mockSynapse.getUserProfile(eq(testUserId))).thenReturn( testUserProfile); joinTeamToken = new JoinTeamSignedToken(); joinTeamToken.setHmac("98765"); joinTeamToken.setMemberId("1"); joinTeamToken.setTeamId("2"); joinTeamToken.setUserId("3"); encodedJoinTeamToken = SerializationUtils.serializeAndHexEncode(joinTeamToken); notificationSettingsToken = new NotificationSettingsSignedToken(); notificationSettingsToken.setHmac("987654"); notificationSettingsToken.setSettings(new Settings()); notificationSettingsToken.setUserId("4"); encodedNotificationSettingsToken = SerializationUtils.serializeAndHexEncode(notificationSettingsToken); when(mockSynapse.copyFileHandles(any(BatchFileHandleCopyRequest.class))).thenReturn(mockBatchCopyResults); batchCopyResultsList = new ArrayList<FileHandleCopyResult>(); when(mockBatchCopyResults.getCopyResults()).thenReturn(batchCopyResultsList); } private AccessRequirement createAccessRequirement(ACCESS_TYPE type) { TermsOfUseAccessRequirement accessRequirement = new TermsOfUseAccessRequirement(); accessRequirement.setConcreteType(TermsOfUseAccessRequirement.class .getName()); RestrictableObjectDescriptor descriptor = new RestrictableObjectDescriptor(); descriptor.setId("101"); descriptor.setType(RestrictableObjectType.ENTITY); accessRequirement.setSubjectIds(Arrays .asList(new RestrictableObjectDescriptor[] { descriptor })); accessRequirement.setAccessType(type); return accessRequirement; } private void setupTeamInvitations() throws SynapseException { ArrayList<MembershipInvtnSubmission> testInvitations = new ArrayList<MembershipInvtnSubmission>(); testInvitation = new MembershipInvtnSubmission(); testInvitation.setId("628319"); testInvitation.setInviteeId(inviteeUserId); testInvitations.add(testInvitation); PaginatedResults<MembershipInvtnSubmission> paginatedInvitations = new PaginatedResults<MembershipInvtnSubmission>(); paginatedInvitations.setResults(testInvitations); when( mockSynapse.getOpenMembershipInvitationSubmissions(anyString(), anyString(), anyLong(), anyLong())).thenReturn( paginatedInvitations); inviteeUserProfile = new UserProfile(); inviteeUserProfile.setUserName("Invitee User"); inviteeUserProfile.setOwnerId(inviteeUserId); when(mockSynapse.getUserProfile(eq(inviteeUserId))).thenReturn( inviteeUserProfile); } @Test public void testGetEntityBundleAll() throws RestServiceException { // Make sure we can get all parts of the bundel int mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH | HAS_CHILDREN | ACCESS_REQUIREMENTS | UNMET_ACCESS_REQUIREMENTS; EntityBundle bundle = synapseClient.getEntityBundle(entityId, mask); assertNotNull(bundle); // We should have all of the strings assertNotNull(bundle.getEntity()); assertNotNull(bundle.getAnnotations()); assertNotNull(bundle.getPath()); assertNotNull(bundle.getPermissions()); assertNotNull(bundle.getHasChildren()); assertNotNull(bundle.getAccessRequirements()); assertNotNull(bundle.getUnmetAccessRequirements()); } @Test public void testGetEntityBundleNone() throws RestServiceException { // Make sure all are null int mask = 0x0; EntityBundle bundle = synapseClient.getEntityBundle(entityId, mask); assertNotNull(bundle); // We should have all of the strings assertNull(bundle.getEntity()); assertNull(bundle.getAnnotations()); assertNull(bundle.getPath()); assertNull(bundle.getPermissions()); assertNull(bundle.getHasChildren()); assertNull(bundle.getAccessRequirements()); assertNull(bundle.getUnmetAccessRequirements()); } @Test(expected = IllegalArgumentException.class) public void testParseEntityFromJsonNoType() throws JSONObjectAdapterException { ExampleEntity example = new ExampleEntity(); example.setName("some name"); example.setDescription("some description"); // do not set the type String json = EntityFactory.createJSONStringForEntity(example); // This will fail as the type is required synapseClient.parseEntityFromJson(json); } @Test public void testParseEntityFromJson() throws JSONObjectAdapterException { ExampleEntity example = new ExampleEntity(); example.setName("some name"); example.setDescription("some description"); example.setEntityType(ExampleEntity.class.getName()); String json = EntityFactory.createJSONStringForEntity(example); // System.out.println(json); // Now make sure this can be read back ExampleEntity clone = (ExampleEntity) synapseClient .parseEntityFromJson(json); assertEquals(example, clone); } @Test public void testCreateOrUpdateEntityFalse() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.putEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, null, false); assertEquals(out.getId(), result); verify(mockSynapse).putEntity(in); } @Test public void testCreateOrUpdateEntityTrue() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.createEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, null, true); assertEquals(out.getId(), result); verify(mockSynapse).createEntity(in); } @Test public void testCreateOrUpdateEntityTrueWithAnnos() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); Annotations annos = new Annotations(); annos.addAnnotation("someString", "one"); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.createEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, annos, true); assertEquals(out.getId(), result); verify(mockSynapse).createEntity(in); annos.setEtag(out.getEtag()); annos.setId(out.getId()); verify(mockSynapse).updateAnnotations(out.getId(), annos); } @Test public void testMoveEntity() throws JSONObjectAdapterException, RestServiceException, SynapseException { String entityId = "syn123"; String oldParentId = "syn1", newParentId = "syn2"; ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setParentId(oldParentId); in.setId(entityId); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setEntityType(ExampleEntity.class.getName()); out.setId(entityId); out.setParentId(newParentId); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.putEntity(in)).thenReturn(out); when(mockSynapse.getEntityById(entityId)).thenReturn(in); Entity result = synapseClient.moveEntity(entityId, newParentId); assertEquals(newParentId, result.getParentId()); verify(mockSynapse).getEntityById(entityId); verify(mockSynapse).putEntity(any(Entity.class)); } @Test public void testGetEntityBenefactorAcl() throws Exception { EntityBundle bundle = new EntityBundle(); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle("syn101", EntityBundle.BENEFACTOR_ACL)) .thenReturn(bundle); AccessControlList clone = synapseClient .getEntityBenefactorAcl("syn101"); assertEquals(acl, clone); } @Test public void testCreateAcl() throws Exception { AccessControlList clone = synapseClient.createAcl(acl); assertEquals(acl, clone); } @Test public void testUpdateAcl() throws Exception { AccessControlList clone = synapseClient.updateAcl(acl); assertEquals(acl, clone); } @Test public void testUpdateAclRecursive() throws Exception { AccessControlList clone = synapseClient.updateAcl(acl, true); assertEquals(acl, clone); verify(mockSynapse).updateACL(any(AccessControlList.class), eq(true)); } @Test public void testDeleteAcl() throws Exception { EntityBundle bundle = new EntityBundle(); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle("syn101", EntityBundle.BENEFACTOR_ACL)) .thenReturn(bundle); AccessControlList clone = synapseClient.deleteAcl("syn101"); assertEquals(acl, clone); } @Test public void testHasAccess() throws Exception { assertTrue(synapseClient.hasAccess("syn101", "READ")); } @Test public void testGetUserProfile() throws Exception { // verify call is directly calling the synapse client provider String testRepoUrl = "http://mytestrepourl"; when(mockUrlProvider.getRepositoryServiceUrl()).thenReturn(testRepoUrl); UserProfile userProfile = synapseClient.getUserProfile(testUserId); assertEquals(userProfile, testUserProfile); } @Test public void testGetProjectById() throws Exception { String projectId = "syn1029"; Project project = new Project(); project.setId(projectId); when(mockSynapse.getEntityById(projectId)).thenReturn(project); Project actualProject = synapseClient.getProject(projectId); assertEquals(project, actualProject); } @Test public void testGetJSONEntity() throws Exception { JSONObject json = EntityFactory.createJSONObjectForEntity(entity); Mockito.when(mockSynapse.getEntity(anyString())).thenReturn(json); String testRepoUri = "/testservice"; synapseClient.getJSONEntity(testRepoUri); // verify that this call uses Synapse.getEntity(testRepoUri) verify(mockSynapse).getEntity(testRepoUri); } @Test public void testGetWikiHeaderTree() throws Exception { PaginatedResults<WikiHeader> headerTreeResults = new PaginatedResults<WikiHeader>(); when(mockSynapse.getWikiHeaderTree(anyString(), any(ObjectType.class))) .thenReturn(headerTreeResults); synapseClient.getWikiHeaderTree("testId", ObjectType.ENTITY.toString()); verify(mockSynapse).getWikiHeaderTree(anyString(), eq(ObjectType.ENTITY)); } @Test public void testGetWikiAttachmentHandles() throws Exception { FileHandleResults testResults = new FileHandleResults(); Mockito.when( mockSynapse .getWikiAttachmenthHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(testResults); synapseClient.getWikiAttachmentHandles(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getWikiAttachmenthHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testDeleteV2WikiPage() throws Exception { synapseClient.deleteV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).deleteV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testGetV2WikiPage() throws Exception { Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); synapseClient.getV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY .toString(), "20")); verify(mockSynapse).getV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(v2Page); synapseClient.getVersionOfV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testUpdateV2WikiPage() throws Exception { Mockito.when( mockSynapse.updateV2WikiPage(anyString(), any(ObjectType.class), any(V2WikiPage.class))) .thenReturn(v2Page); synapseClient.updateV2WikiPage("testId", ObjectType.ENTITY.toString(), v2Page); verify(mockSynapse).updateV2WikiPage(anyString(), any(ObjectType.class), any(V2WikiPage.class)); } @Test public void testRestoreV2WikiPage() throws Exception { String wikiId = "syn123"; Mockito.when( mockSynapse.restoreV2WikiPage(anyString(), any(ObjectType.class), any(String.class), anyLong())) .thenReturn(v2Page); synapseClient.restoreV2WikiPage("ownerId", ObjectType.ENTITY.toString(), wikiId, new Long(2)); verify(mockSynapse).restoreV2WikiPage(anyString(), any(ObjectType.class), any(String.class), anyLong()); } @Test public void testGetV2WikiHeaderTree() throws Exception { PaginatedResults<V2WikiHeader> headerTreeResults = new PaginatedResults<V2WikiHeader>(); when( mockSynapse.getV2WikiHeaderTree(anyString(), any(ObjectType.class))).thenReturn(headerTreeResults); synapseClient.getV2WikiHeaderTree("testId", ObjectType.ENTITY.toString()); verify(mockSynapse).getV2WikiHeaderTree(anyString(), any(ObjectType.class)); } @Test public void testGetV2WikiOrderHint() throws Exception { V2WikiOrderHint orderHint = new V2WikiOrderHint(); when( mockSynapse .getV2OrderHint(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(orderHint); synapseClient.getV2WikiOrderHint(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getV2OrderHint( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testUpdateV2WikiOrderHint() throws Exception { V2WikiOrderHint orderHint = new V2WikiOrderHint(); when(mockSynapse.updateV2WikiOrderHint(any(V2WikiOrderHint.class))) .thenReturn(orderHint); synapseClient.updateV2WikiOrderHint(orderHint); verify(mockSynapse).updateV2WikiOrderHint(any(V2WikiOrderHint.class)); } @Test public void testGetV2WikiHistory() throws Exception { PaginatedResults<V2WikiHistorySnapshot> historyResults = new PaginatedResults<V2WikiHistorySnapshot>(); when( mockSynapse .getV2WikiHistory( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class), any(Long.class))).thenReturn( historyResults); synapseClient.getV2WikiHistory(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(10), new Long(0)); verify(mockSynapse).getV2WikiHistory( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class), any(Long.class)); } @Test public void testGetV2WikiAttachmentHandles() throws Exception { FileHandleResults testResults = new FileHandleResults(); Mockito.when( mockSynapse .getV2WikiAttachmentHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(testResults); synapseClient.getV2WikiAttachmentHandles(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getVersionOfV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(testResults); synapseClient.getVersionOfV2WikiAttachmentHandles(new WikiPageKey( "syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getVersionOfV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testZipAndUpload() throws IOException, RestServiceException, JSONObjectAdapterException, SynapseException { Mockito.when( mockSynapse .createFileHandle(any(File.class), any(String.class))) .thenReturn(handle); synapseClient.zipAndUploadFile("markdown", "fileName"); verify(mockSynapse) .createFileHandle(any(File.class), any(String.class)); } @Test public void testGetMarkdown() throws IOException, RestServiceException, SynapseException { String someMarkDown = "someMarkDown"; Mockito.when( mockSynapse .downloadV2WikiMarkdown(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(someMarkDown); synapseClient.getMarkdown(new WikiPageKey("syn123", ObjectType.ENTITY .toString(), "20")); verify(mockSynapse).downloadV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .downloadVersionOfV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(someMarkDown); synapseClient.getVersionOfMarkdown(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).downloadVersionOfV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testCreateV2WikiPageWithV1() throws Exception { Mockito.when( mockSynapse.createWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class))).thenReturn(page); synapseClient.createV2WikiPageWithV1("testId", ObjectType.ENTITY.toString(), page); verify(mockSynapse).createWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class)); } @Test public void testUpdateV2WikiPageWithV1() throws Exception { Mockito.when( mockSynapse.updateWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class))).thenReturn(page); synapseClient.updateV2WikiPageWithV1("testId", ObjectType.ENTITY.toString(), page); verify(mockSynapse).updateWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class)); } @Test public void getV2WikiPageAsV1() throws Exception { Mockito.when( mockSynapse .getWikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(page); Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); synapseClient.getV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getWikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); // asking for the same page twice should result in a cache hit, and it // should not ask for it from the synapse client synapseClient.getV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse, Mockito.times(1)).getWikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(page); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), anyLong())).thenReturn(v2Page); synapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); // asking for the same page twice should result in a cache hit, and it // should not ask for it from the synapse client synapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse, Mockito.times(1)).getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } private void resetUpdateExternalFileHandleMocks(String testId, FileEntity file, ExternalFileHandle handle) throws SynapseException, JSONObjectAdapterException { reset(mockSynapse); when(mockSynapse.getEntityById(testId)).thenReturn(file); when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(handle); when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file); } @Test public void testUpdateExternalFileHandle() throws Exception { // verify call is directly calling the synapse client provider, and it // tries to rename the entity to the filename String myFileName = "testFileName.csv"; String testUrl = " http://mytesturl/" + myFileName; String testId = "myTestId"; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize=2048L; FileEntity file = new FileEntity(); String originalFileEntityName = "syn1223"; file.setName(originalFileEntityName); file.setId(testId); file.setDataFileHandleId("handle1"); ExternalFileHandle handle = new ExternalFileHandle(); handle.setExternalURL(testUrl); resetUpdateExternalFileHandleMocks(testId, file, handle); synapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId); verify(mockSynapse).getEntityById(testId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor.forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle capturedValue = captor.getValue(); assertEquals(testUrl.trim(), capturedValue.getExternalURL()); assertEquals(md5, capturedValue.getContentMd5()); // assertEquals(fileSize, capturedValue.getContentSize()); verify(mockSynapse).putEntity(any(FileEntity.class)); // and if rename fails, verify all is well (but the FileEntity name is // not updated) resetUpdateExternalFileHandleMocks(testId, file, handle); file.setName(originalFileEntityName); // first call should return file, second call to putEntity should throw // an exception when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file) .thenThrow( new IllegalArgumentException( "invalid name for some reason")); synapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId); // called createExternalFileHandle verify(mockSynapse).createExternalFileHandle( any(ExternalFileHandle.class)); // and it should have called putEntity again verify(mockSynapse).putEntity(any(FileEntity.class)); } @Test public void testCreateExternalFile() throws Exception { // test setting file handle name String parentEntityId = "syn123333"; String externalUrl = " sftp://foobar.edu/b/test.txt"; String fileName = "testing.txt"; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize = 1024L; when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(new ExternalFileHandle()); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( new FileEntity()); synapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor .forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle handle = captor.getValue(); // verify name is set assertEquals(fileName, handle.getFileName()); assertEquals(externalUrl.trim(), handle.getExternalURL()); assertEquals(storageLocationId, handle.getStorageLocationId()); assertEquals(md5, handle.getContentMd5()); // assertEquals(fileSize, handle.getContentSize()); } @Test public void testCreateExternalFileAutoname() throws Exception { // test setting file handle name String parentEntityId = "syn123333"; String externalUrl = "sftp://foobar.edu/b/test.txt"; String expectedAutoFilename = "test.txt"; String fileName = null; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize = 1024L; when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(new ExternalFileHandle()); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( new FileEntity()); synapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor .forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle handle = captor.getValue(); // verify name is set assertEquals(expectedAutoFilename, handle.getFileName()); assertEquals(externalUrl, handle.getExternalURL()); assertEquals(storageLocationId, handle.getStorageLocationId()); assertEquals(md5, handle.getContentMd5()); //also check the entity name ArgumentCaptor<Entity> entityCaptor = ArgumentCaptor.forClass(Entity.class); verify(mockSynapse).createEntity(entityCaptor.capture()); assertEquals(expectedAutoFilename, entityCaptor.getValue().getName()); } @Test public void testGetEntityDoi() throws Exception { // wiring test Doi testDoi = new Doi(); testDoi.setDoiStatus(DoiStatus.CREATED); testDoi.setId("test doi id"); testDoi.setCreatedBy("Test User"); testDoi.setCreatedOn(new Date()); testDoi.setObjectId("syn1234"); Mockito.when(mockSynapse.getEntityDoi(anyString(), anyLong())) .thenReturn(testDoi); synapseClient.getEntityDoi("test entity id", null); verify(mockSynapse).getEntityDoi(anyString(), anyLong()); } private FileEntity getTestFileEntity() { FileEntity testFileEntity = new FileEntity(); testFileEntity.setId("5544"); testFileEntity.setName(testFileName); return testFileEntity; } @Test(expected = NotFoundException.class) public void testGetEntityDoiNotFound() throws Exception { // wiring test Mockito.when(mockSynapse.getEntityDoi(anyString(), anyLong())) .thenThrow(new SynapseNotFoundException()); synapseClient.getEntityDoi("test entity id", null); } @Test public void testCreateDoi() throws Exception { // wiring test synapseClient.createDoi("test entity id", null); verify(mockSynapse).createEntityDoi(anyString(), anyLong()); } @Test public void testGetUploadDaemonStatus() throws JSONObjectAdapterException, SynapseException, RestServiceException { synapseClient.getUploadDaemonStatus("daemonId"); verify(mockSynapse).getCompleteUploadDaemonStatus(anyString()); } /** * Direct upload tests. Most of the methods are simple pass-throughs to the * Java Synapse client, but completeUpload has additional logic * * @throws JSONObjectAdapterException * @throws SynapseException * @throws RestServiceException */ @Test public void testCompleteUpload() throws JSONObjectAdapterException, SynapseException, RestServiceException { FileEntity testFileEntity = getTestFileEntity(); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( testFileEntity); when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn( testFileEntity); // parent entity has no immediate children EntityIdList childEntities = new EntityIdList(); childEntities.setIdList(new ArrayList()); synapseClient.setFileEntityFileHandle(null, null, "parentEntityId"); // it should have tried to create a new entity (since entity id was // null) verify(mockSynapse).createEntity(any(FileEntity.class)); } @Test(expected = NotFoundException.class) public void testGetFileEntityIdWithSameNameNotFound() throws JSONObjectAdapterException, SynapseException, RestServiceException, JSONException { JSONObject queryResult = new JSONObject(); queryResult.put("totalNumberOfResults", (long) 0); when(mockSynapse.query(anyString())).thenReturn(queryResult); // TODO String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); } @Test(expected = ConflictException.class) public void testGetFileEntityIdWithSameNameConflict() throws JSONObjectAdapterException, SynapseException, RestServiceException, JSONException { Folder folder = new Folder(); folder.setName(testFileName); JSONObject queryResult = new JSONObject(); JSONArray results = new JSONArray(); // Set up results. JSONObject objectResult = EntityFactory .createJSONObjectForEntity(folder); JSONArray typeArray = new JSONArray(); typeArray.put("Folder"); objectResult.put("entity.concreteType", typeArray); results.put(objectResult); // Set up query result. queryResult.put("totalNumberOfResults", (long) 1); queryResult.put("results", results); // Have results returned in query. when(mockSynapse.query(anyString())).thenReturn(queryResult); String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); } @Test public void testGetFileEntityIdWithSameNameFound() throws JSONException, JSONObjectAdapterException, SynapseException, RestServiceException { FileEntity file = getTestFileEntity(); JSONObject queryResult = new JSONObject(); JSONArray results = new JSONArray(); // Set up results. JSONObject objectResult = EntityFactory.createJSONObjectForEntity(file); JSONArray typeArray = new JSONArray(); typeArray.put(FileEntity.class.getName()); objectResult.put("entity.concreteType", typeArray); objectResult.put("entity.id", file.getId()); results.put(objectResult); queryResult.put("totalNumberOfResults", (long) 1); queryResult.put("results", results); // Have results returned in query. when(mockSynapse.query(anyString())).thenReturn(queryResult); String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); assertEquals(fileEntityId, file.getId()); } @Test public void testInviteMemberOpenInvitations() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setHasOpenInvitation(true); // verify it does not create a new invitation since one is already open synapseClient.inviteMember("123", "a team", "", ""); verify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(), anyString(), anyString(), anyString()); verify(mockSynapse, Mockito.times(0)).createMembershipInvitation( any(MembershipInvtnSubmission.class), anyString(), anyString()); } @Test public void testRequestMemberOpenRequests() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setHasOpenRequest(true); // verify it does not create a new request since one is already open synapseClient.requestMembership("123", "a team", "let me join", TEST_HOME_PAGE_BASE, null); verify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); } @Test public void testInviteMemberCanJoin() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setCanJoin(true); synapseClient.inviteMember("123", "a team", "", TEST_HOME_PAGE_BASE); verify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testRequestMembershipCanJoin() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setCanJoin(true); synapseClient.requestMembership("123", "a team", "", TEST_HOME_PAGE_BASE, new Date()); verify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testInviteMember() throws SynapseException, RestServiceException, JSONObjectAdapterException { synapseClient.inviteMember("123", "a team", "", TEST_HOME_PAGE_BASE); verify(mockSynapse).createMembershipInvitation( any(MembershipInvtnSubmission.class), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testRequestMembership() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); String teamId = "a team"; String message= "let me join"; Date expiresOn = null; synapseClient.requestMembership("123", teamId, message, TEST_HOME_PAGE_BASE, expiresOn); verify(mockSynapse).createMembershipRequest( captor.capture(), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); MembershipRqstSubmission request = captor.getValue(); assertEquals(expiresOn, request.getExpiresOn()); assertEquals(teamId, request.getTeamId()); assertEquals(message, request.getMessage()); } @Test public void testRequestMembershipWithExpiresOn() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); String teamId = "a team"; String message= "let me join"; Date expiresOn = new Date(); synapseClient.requestMembership("123", teamId, message, TEST_HOME_PAGE_BASE, expiresOn); verify(mockSynapse).createMembershipRequest( captor.capture(), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); MembershipRqstSubmission request = captor.getValue(); assertEquals(expiresOn, request.getExpiresOn()); assertEquals(teamId, request.getTeamId()); assertEquals(message, request.getMessage()); } @Test public void testGetOpenRequestCountUnauthorized() throws SynapseException, RestServiceException { // is not an admin TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(false); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); Long count = synapseClient.getOpenRequestCount("myUserId", "myTeamId"); // should never ask for open request count verify(mockSynapse, Mockito.never()).getOpenMembershipRequests( anyString(), anyString(), anyLong(), anyLong()); assertNull(count); } @Test public void testGetOpenRequestCount() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // is admin TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(true); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); Long testCount = 42L; PaginatedResults<MembershipRequest> testOpenRequests = new PaginatedResults<MembershipRequest>(); testOpenRequests.setTotalNumberOfResults(testCount); when( mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(testOpenRequests); Long count = synapseClient.getOpenRequestCount("myUserId", "myTeamId"); verify(mockSynapse, Mockito.times(1)).getOpenMembershipRequests( anyString(), anyString(), anyLong(), anyLong()); assertEquals(testCount, count); } @Test public void testGetOpenTeamInvitations() throws SynapseException, RestServiceException, JSONObjectAdapterException { setupTeamInvitations(); int limit = 55; int offset = 2; String teamId = "132"; List<OpenTeamInvitationBundle> invitationBundles = synapseClient .getOpenTeamInvitations(teamId, limit, offset); verify(mockSynapse).getOpenMembershipInvitationSubmissions(eq(teamId), anyString(), eq((long) limit), eq((long) offset)); // we set this up so that a single invite would be returned. Verify that // it is the one we're looking for assertEquals(1, invitationBundles.size()); OpenTeamInvitationBundle invitationBundle = invitationBundles.get(0); assertEquals(inviteeUserProfile, invitationBundle.getUserProfile()); assertEquals(testInvitation, invitationBundle.getMembershipInvtnSubmission()); } @Test public void testGetTeamBundle() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // set team member count Long testMemberCount = 111L; PaginatedResults<TeamMember> allMembers = new PaginatedResults<TeamMember>(); allMembers.setTotalNumberOfResults(testMemberCount); when( mockSynapse.getTeamMembers(anyString(), anyString(), anyLong(), anyLong())).thenReturn(allMembers); // set team Team team = new Team(); team.setId("test team id"); when(mockSynapse.getTeam(anyString())).thenReturn(team); // is member TeamMembershipStatus membershipStatus = new TeamMembershipStatus(); membershipStatus.setIsMember(true); when(mockSynapse.getTeamMembershipStatus(anyString(), anyString())) .thenReturn(membershipStatus); // is admin TeamMember testTeamMember = new TeamMember(); boolean isAdmin = true; testTeamMember.setIsAdmin(isAdmin); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); // make the call TeamBundle bundle = synapseClient.getTeamBundle("myUserId", "myTeamId", true); // now verify round all values were returned in the bundle (based on the // mocked service calls) assertEquals(team, bundle.getTeam()); assertEquals(membershipStatus, bundle.getTeamMembershipStatus()); assertEquals(isAdmin, bundle.isUserAdmin()); assertEquals(testMemberCount, bundle.getTotalMemberCount()); } @Test public void testGetTeamMembers() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // set team member count Long testMemberCount = 111L; PaginatedResults<TeamMember> allMembers = new PaginatedResults<TeamMember>(); allMembers.setTotalNumberOfResults(testMemberCount); List<TeamMember> members = new ArrayList<TeamMember>(); TeamMember member1 = new TeamMember(); member1.setIsAdmin(true); UserGroupHeader header1 = new UserGroupHeader(); Long member1Id = 123L; header1.setOwnerId(member1Id + ""); member1.setMember(header1); members.add(member1); TeamMember member2 = new TeamMember(); member2.setIsAdmin(false); UserGroupHeader header2 = new UserGroupHeader(); Long member2Id = 456L; header2.setOwnerId(member2Id + ""); member2.setMember(header2); members.add(member2); allMembers.setResults(members); when( mockSynapse.getTeamMembers(anyString(), anyString(), anyLong(), anyLong())).thenReturn(allMembers); List<UserProfile> profiles = new ArrayList<UserProfile>(); UserProfile profile1 = new UserProfile(); profile1.setOwnerId(member1Id + ""); UserProfile profile2 = new UserProfile(); profile2.setOwnerId(member2Id + ""); profiles.add(profile1); profiles.add(profile2); when(mockSynapse.listUserProfiles(anyList())).thenReturn(profiles); // make the call TeamMemberPagedResults results = synapseClient.getTeamMembers( "myTeamId", "search term", 100, 0); // verify it results in the two team member bundles that we expect List<TeamMemberBundle> memberBundles = results.getResults(); assertEquals(2, memberBundles.size()); TeamMemberBundle bundle1 = memberBundles.get(0); assertTrue(bundle1.getIsTeamAdmin()); assertEquals(profile1, bundle1.getUserProfile()); TeamMemberBundle bundle2 = memberBundles.get(1); assertFalse(bundle2.getIsTeamAdmin()); assertEquals(profile2, bundle2.getUserProfile()); } @Test public void testIsTeamMember() throws NumberFormatException, RestServiceException, SynapseException { synapseClient.isTeamMember(entityId, Long.valueOf(teamA.getId())); verify(mockSynapse).getTeamMembershipStatus(teamA.getId(), entityId); } @Test public void testGetEntityHeaderBatch() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { List<EntityHeader> headers = synapseClient .getEntityHeaderBatch(new ArrayList()); // in the setup, we told the mockSynapse.getEntityHeaderBatch to return // batchHeaderResults for (int i = 0; i < batchHeaderResults.size(); i++) { assertEquals(batchHeaderResults.get(i), headers.get(i)); } } @Test public void testSendMessage() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MessageToUser> arg = ArgumentCaptor .forClass(MessageToUser.class); Set<String> recipients = new HashSet<String>(); recipients.add("333"); String subject = "The Mathematics of Quantum Neutrino Fields"; String messageBody = "Atoms are not to be trusted, they make up everything"; String hostPageBaseURL = "http://localhost/Portal.html"; synapseClient.sendMessage(recipients, subject, messageBody, hostPageBaseURL); verify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE)); verify(mockSynapse).sendMessage(arg.capture()); MessageToUser toSendMessage = arg.getValue(); assertEquals(subject, toSendMessage.getSubject()); assertEquals(recipients, toSendMessage.getRecipients()); assertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL)); } @Test public void testSendMessageToEntityOwner() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MessageToUser> arg = ArgumentCaptor .forClass(MessageToUser.class); ArgumentCaptor<String> entityIdCaptor = ArgumentCaptor .forClass(String.class); String subject = "The Mathematics of Quantum Neutrino Fields"; String messageBody = "Atoms are not to be trusted, they make up everything"; String hostPageBaseURL = "http://localhost/Portal.html"; String entityId = "syn98765"; synapseClient.sendMessageToEntityOwner(entityId, subject, messageBody, hostPageBaseURL); verify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE)); verify(mockSynapse).sendMessage(arg.capture(), entityIdCaptor.capture()); MessageToUser toSendMessage = arg.getValue(); assertEquals(subject, toSendMessage.getSubject()); assertEquals(entityId, entityIdCaptor.getValue()); assertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL)); } @Test public void testGetCertifiedUserPassingRecord() throws RestServiceException, SynapseException, JSONObjectAdapterException { PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(true); passingRecord.setQuizId(1238L); String passingRecordJson = passingRecord.writeToJSONObject( adapterFactory.createNew()).toJSONString(); when(mockSynapse.getCertifiedUserPassingRecord(anyString())) .thenReturn(passingRecord); String returnedPassingRecordJson = synapseClient .getCertifiedUserPassingRecord("123"); verify(mockSynapse).getCertifiedUserPassingRecord(anyString()); assertEquals(passingRecordJson, returnedPassingRecordJson); } @Test(expected = NotFoundException.class) public void testUserNeverAttemptedCertification() throws RestServiceException, SynapseException { when(mockSynapse.getCertifiedUserPassingRecord(anyString())).thenThrow( new SynapseNotFoundException("PassingRecord not found")); synapseClient.getCertifiedUserPassingRecord("123"); } @Test(expected = NotFoundException.class) public void testUserFailedCertification() throws RestServiceException, SynapseException { PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(false); passingRecord.setQuizId(1238L); when(mockSynapse.getCertifiedUserPassingRecord(anyString())) .thenReturn(passingRecord); synapseClient.getCertifiedUserPassingRecord("123"); } @Test public void testGetCertificationQuiz() throws RestServiceException, SynapseException { when(mockSynapse.getCertifiedUserTest()).thenReturn(new Quiz()); synapseClient.getCertificationQuiz(); verify(mockSynapse).getCertifiedUserTest(); } @Test public void testSubmitCertificationQuizResponse() throws RestServiceException, SynapseException, JSONObjectAdapterException { PassingRecord mockPassingRecord = new PassingRecord(); when( mockSynapse .submitCertifiedUserTestResponse(any(QuizResponse.class))) .thenReturn(mockPassingRecord); QuizResponse myResponse = new QuizResponse(); myResponse.setId(837L); synapseClient.submitCertificationQuizResponse(myResponse); verify(mockSynapse).submitCertifiedUserTestResponse(eq(myResponse)); } @Test public void testMarkdownCache() throws Exception { Cache<MarkdownCacheRequest, WikiPage> mockCache = Mockito .mock(Cache.class); synapseClient.setMarkdownCache(mockCache); WikiPage page = new WikiPage(); when(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page); Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); WikiPage actualResult = synapseClient .getV2WikiPageAsV1(new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), "12")); assertEquals(page, actualResult); verify(mockCache).get(any(MarkdownCacheRequest.class)); } @Test public void testMarkdownCacheWithVersion() throws Exception { Cache<MarkdownCacheRequest, WikiPage> mockCache = Mockito .mock(Cache.class); synapseClient.setMarkdownCache(mockCache); WikiPage page = new WikiPage(); when(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), anyLong())).thenReturn(v2Page); WikiPage actualResult = synapseClient.getVersionOfV2WikiPageAsV1( new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), "12"), 5L); assertEquals(page, actualResult); verify(mockCache).get(any(MarkdownCacheRequest.class)); } @Test public void testFilterAccessRequirements() throws Exception { List<AccessRequirement> unfilteredAccessRequirements = new ArrayList<AccessRequirement>(); List<AccessRequirement> filteredAccessRequirements; // filter empty list should not result in failure filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.UPDATE); assertTrue(filteredAccessRequirements.isEmpty()); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD)); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.SUBMIT)); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.SUBMIT)); // no requirements of type UPDATE filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.UPDATE); assertTrue(filteredAccessRequirements.isEmpty()); // 1 download filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.DOWNLOAD); assertEquals(1, filteredAccessRequirements.size()); // 2 submit filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.SUBMIT); assertEquals(2, filteredAccessRequirements.size()); // finally, filter null list - result will be an empty list filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(null, ACCESS_TYPE.SUBMIT); assertNotNull(filteredAccessRequirements); assertTrue(filteredAccessRequirements.isEmpty()); } @Test public void testGetEntityUnmetAccessRequirements() throws Exception { // verify it calls getUnmetAccessRequirements when unmet is true synapseClient.getEntityAccessRequirements(entityId, true, null); verify(mockSynapse) .getUnmetAccessRequirements( any(RestrictableObjectDescriptor.class), any(ACCESS_TYPE.class)); } @Test public void testGetAllEntityAccessRequirements() throws Exception { // verify it calls getAccessRequirements when unmet is false synapseClient.getEntityAccessRequirements(entityId, false, null); verify(mockSynapse).getAccessRequirements( any(RestrictableObjectDescriptor.class)); } // pass through tests for email validation @Test public void testAdditionalEmailValidation() throws Exception { Long userId = 992843l; String emailAddress = "[email protected]"; String callbackUrl = "http://www.synapse.org/#!Account:"; synapseClient.additionalEmailValidation(userId.toString(), emailAddress, callbackUrl); verify(mockSynapse).additionalEmailValidation(eq(userId), eq(emailAddress), eq(callbackUrl)); } @Test public void testAddEmail() throws Exception { String emailAddressToken = "long synapse email token"; synapseClient.addEmail(emailAddressToken); verify(mockSynapse).addEmail(any(AddEmailInfo.class), anyBoolean()); } @Test public void testGetNotificationEmail() throws Exception { synapseClient.getNotificationEmail(); verify(mockSynapse).getNotificationEmail(); } @Test public void testSetNotificationEmail() throws Exception { String emailAddress = "[email protected]"; synapseClient.setNotificationEmail(emailAddress); verify(mockSynapse).setNotificationEmail(eq(emailAddress)); } @Test public void testLogErrorToRepositoryServices() throws SynapseException, RestServiceException, JSONObjectAdapterException { String errorMessage = "error has occurred"; String permutationStrongName="Chrome"; synapseClient.logErrorToRepositoryServices(errorMessage, null, null, null, permutationStrongName); verify(mockSynapse).getMyProfile(); verify(mockSynapse).logError(any(LogEntry.class)); } @Test public void testLogErrorToRepositoryServicesTruncation() throws SynapseException, RestServiceException, JSONObjectAdapterException, ServletException { String exceptionMessage = "This exception brought to you by Sage Bionetworks"; Exception e = new Exception(exceptionMessage, new IllegalArgumentException(new NullPointerException())); ServletContext mockServletContext = Mockito.mock(ServletContext.class); ServletConfig mockServletConfig = Mockito.mock(ServletConfig.class); when(mockServletConfig.getServletContext()).thenReturn(mockServletContext); synapseClient.init(mockServletConfig); String errorMessage = "error has occurred"; String permutationStrongName="FF"; synapseClient.logErrorToRepositoryServices(errorMessage, e.getClass().getSimpleName(), e.getMessage(), e.getStackTrace(), permutationStrongName); ArgumentCaptor<LogEntry> captor = ArgumentCaptor .forClass(LogEntry.class); verify(mockSynapse).logError(captor.capture()); LogEntry logEntry = captor.getValue(); assertTrue(logEntry.getLabel().length() < SynapseClientImpl.MAX_LOG_ENTRY_LABEL_SIZE + 100); assertTrue(logEntry.getMessage().contains(errorMessage)); assertTrue(logEntry.getMessage().contains(MY_USER_PROFILE_OWNER_ID)); assertTrue(logEntry.getMessage().contains(e.getClass().getSimpleName())); assertTrue(logEntry.getMessage().contains(exceptionMessage)); } @Test public void testGetMyProjects() throws Exception { int limit = 11; int offset = 20; ProjectPagedResults results = synapseClient.getMyProjects(ProjectListType.MY_PROJECTS, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getMyProjects(eq(ProjectListType.MY_PROJECTS), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testGetUserProjects() throws Exception { int limit = 11; int offset = 20; Long userId = 133l; String userIdString = userId.toString(); synapseClient.getUserProjects(userIdString, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getProjectsFromUser(eq(userId), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testGetProjectsForTeam() throws Exception { int limit = 13; int offset = 40; Long teamId = 144l; String teamIdString = teamId.toString(); synapseClient.getProjectsForTeam(teamIdString, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getProjectsForTeam(eq(teamId), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testSafeLongToInt() { int inRangeInt = 500; int after = SynapseClientImpl.safeLongToInt(inRangeInt); assertEquals(inRangeInt, after); } @Test(expected = IllegalArgumentException.class) public void testSafeLongToIntPositive() { long testValue = Integer.MAX_VALUE; testValue++; SynapseClientImpl.safeLongToInt(testValue); } @Test(expected = IllegalArgumentException.class) public void testSafeLongToIntNegative() { long testValue = Integer.MIN_VALUE; testValue--; SynapseClientImpl.safeLongToInt(testValue); } @Test public void testGetHost() throws RestServiceException { assertEquals("mydomain.com", synapseClient.getHost("sfTp://mydomain.com/foo/bar")); assertEquals("mydomain.com", synapseClient.getHost("http://mydomain.com/foo/bar")); assertEquals("mydomain.com", synapseClient.getHost("http://mydomain.com")); assertEquals("mydomain.com", synapseClient.getHost("sftp://mydomain.com:22/foo/bar")); } @Test(expected = IllegalArgumentException.class) public void testGetHostNull() throws RestServiceException { synapseClient.getHost(null); } @Test(expected = IllegalArgumentException.class) public void testGetHostEmpty() throws RestServiceException { synapseClient.getHost(""); } @Test(expected = BadRequestException.class) public void testGetHostBadUrl() throws RestServiceException { synapseClient.getHost("foobar"); } @Test public void testGetRootWikiId() throws JSONObjectAdapterException, SynapseException, RestServiceException { org.sagebionetworks.repo.model.dao.WikiPageKey key = new org.sagebionetworks.repo.model.dao.WikiPageKey(); key.setOwnerObjectId("1"); key.setOwnerObjectType(ObjectType.ENTITY); String expectedId = "123"; key.setWikiPageId(expectedId); when(mockSynapse.getRootWikiPageKey(anyString(), any(ObjectType.class))) .thenReturn(key); String actualId = synapseClient.getRootWikiId("1", ObjectType.ENTITY.toString()); assertEquals(expectedId, actualId); } @Test public void testGetFavorites() throws JSONObjectAdapterException, SynapseException, RestServiceException { PaginatedResults<EntityHeader> pagedResults = new PaginatedResults<EntityHeader>(); List<EntityHeader> unsortedResults = new ArrayList<EntityHeader>(); pagedResults.setResults(unsortedResults); when(mockSynapse.getFavorites(anyInt(), anyInt())).thenReturn( pagedResults); // test empty favorites List<EntityHeader> actualList = synapseClient.getFavorites(); assertTrue(actualList.isEmpty()); // test a few unsorted favorites EntityHeader favZ = new EntityHeader(); favZ.setName("Z"); unsortedResults.add(favZ); EntityHeader favA = new EntityHeader(); favA.setName("A"); unsortedResults.add(favA); EntityHeader favQ = new EntityHeader(); favQ.setName("q"); unsortedResults.add(favQ); actualList = synapseClient.getFavorites(); assertEquals(3, actualList.size()); assertEquals(favA, actualList.get(0)); assertEquals(favQ, actualList.get(1)); assertEquals(favZ, actualList.get(2)); } @Test public void testGetTeamBundlesNotOwner() throws RestServiceException, SynapseException { // the paginated results were set up to return {teamZ, teamA}, but // servlet side we sort by name. List<TeamRequestBundle> results = synapseClient.getTeamsForUser("abba", false); verify(mockSynapse).getTeamsForUser(eq("abba"), anyInt(), anyInt()); assertEquals(2, results.size()); assertEquals(teamA, results.get(0).getTeam()); assertEquals(teamZ, results.get(1).getTeam()); verify(mockSynapse, Mockito.never()).getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong()); } @Test public void testGetTeamBundlesOwner() throws RestServiceException, SynapseException { TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(true); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); when(mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(mockPaginatedMembershipRequest); List<TeamRequestBundle> results = synapseClient.getTeamsForUser("abba", true); verify(mockSynapse).getTeamsForUser(eq("abba"), anyInt(), anyInt()); assertEquals(2, results.size()); assertEquals(teamA, results.get(0).getTeam()); assertEquals(teamZ, results.get(1).getTeam()); Long reqCount1 = results.get(0).getRequestCount(); Long reqCount2 = results.get(1).getRequestCount(); assertEquals(new Long(3L), results.get(0).getRequestCount()); assertEquals(new Long(3L), results.get(1).getRequestCount()); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenNull() throws RestServiceException, SynapseException{ String tokenTypeName = null; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenEmpty() throws RestServiceException, SynapseException{ String tokenTypeName = ""; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenUnrecognized() throws RestServiceException, SynapseException{ String tokenTypeName = "InvalidTokenType"; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test public void testHandleSignedTokenJoinTeam() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.JoinTeam.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); synapseClient.handleSignedToken(token,TEST_HOME_PAGE_BASE); verify(mockSynapse).addTeamMember(joinTeamToken, TEST_HOME_PAGE_BASE+"#!Team:", TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/"); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenInvalidJoinTeam() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.JoinTeam.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, "invalid token"); } @Test public void testHandleSignedTokenNotificationSettings() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.Settings.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedNotificationSettingsToken); synapseClient.handleSignedToken(token, TEST_HOME_PAGE_BASE); verify(mockSynapse).updateNotificationSettings(notificationSettingsToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenInvalidNotificationSettings() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.Settings.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, "invalid token"); } @Test public void testGetOrCreateActivityForEntityVersionGet() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenReturn(new Activity()); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); verify(mockSynapse).getActivityForEntityVersion(entityId, version); } @Test public void testGetOrCreateActivityForEntityVersionCreate() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new SynapseNotFoundException()); when(mockSynapse.createActivity(any(Activity.class))).thenReturn(mockActivity); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); verify(mockSynapse).getActivityForEntityVersion(entityId, version); verify(mockSynapse).createActivity(any(Activity.class)); verify(mockSynapse).putEntity(mockSynapse.getEntityById(entityId), mockActivity.getId()); } @Test(expected = Exception.class) public void testGetOrCreateActivityForEntityVersionFailure() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new Exception()); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); } private void setupGetMyLocationSettings() throws SynapseException, RestServiceException{ List<StorageLocationSetting> existingStorageLocations = new ArrayList<StorageLocationSetting>(); StorageLocationSetting storageLocation = new ExternalS3StorageLocationSetting(); storageLocation.setStorageLocationId(1L); storageLocation.setBanner(BANNER_1); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(2L); storageLocation.setBanner(BANNER_2); ((ExternalStorageLocationSetting)storageLocation).setUrl("sftp://www.jayhodgson.com"); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(3L); storageLocation.setBanner(BANNER_1); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(4L); storageLocation.setBanner(null); existingStorageLocations.add(storageLocation); when(mockSynapse.getMyStorageLocationSettings()).thenReturn(existingStorageLocations); } @Test public void testGetMyLocationSettingBanners() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); List<String> banners = synapseClient.getMyLocationSettingBanners(); verify(mockSynapse).getMyStorageLocationSettings(); //should be 2 (only returns unique values) assertEquals(2, banners.size()); assertTrue(banners.contains(BANNER_1)); assertTrue(banners.contains(BANNER_2)); } @Test(expected = Exception.class) public void testGetMyLocationSettingBannersFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSettings()).thenThrow(new Exception()); synapseClient.getMyLocationSettingBanners(); } @Test public void testGetStorageLocationSettingNullSetting() throws SynapseException, RestServiceException { when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null); assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSettingNullUploadDestination() throws SynapseException, RestServiceException { assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSettingDefaultUploadDestination() throws SynapseException, RestServiceException { UploadDestination setting = Mockito.mock(UploadDestination.class); String defaultStorageId = synapseClient.getSynapseProperties().get(SynapseClientImpl.DEFAULT_STORAGE_ID_PROPERTY_KEY); when(setting.getStorageLocationId()).thenReturn(Long.parseLong(defaultStorageId)); when(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting); StorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class); when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting); assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSetting() throws SynapseException, RestServiceException { UploadDestination setting = Mockito.mock(UploadDestination.class); when(setting.getStorageLocationId()).thenReturn(42L); when(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting); StorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class); when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting); assertEquals(mockStorageLocationSetting, synapseClient.getStorageLocationSetting(entityId)); } @Test(expected = Exception.class) public void testGetStorageLocationSettingFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception()); synapseClient.getStorageLocationSetting(entityId); } @Test public void testCreateStorageLocationSettingFoundStorageAndProjectSetting() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); UploadDestinationListSetting projectSetting = new UploadDestinationListSetting(); projectSetting.setLocations(Collections.EMPTY_LIST); when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(projectSetting); //test the case when it finds a duplicate storage location. ExternalStorageLocationSetting setting = new ExternalStorageLocationSetting(); setting.setBanner(BANNER_2); setting.setUrl("sftp://www.jayhodgson.com"); synapseClient.createStorageLocationSetting(entityId, setting); //should have found the duplicate storage location, so this is never called verify(mockSynapse, Mockito.never()).createStorageLocationSetting(any(StorageLocationSetting.class)); //verify updates project setting, and the new location list is a single value (id of existing storage location) ArgumentCaptor<ProjectSetting> captor = ArgumentCaptor.forClass(ProjectSetting.class); verify(mockSynapse).updateProjectSetting(captor.capture()); UploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue(); List<Long> locations = updatedProjectSetting.getLocations(); assertEquals(new Long(2), locations.get(0)); } @Test public void testCreateStorageLocationSettingNewStorageAndProjectSetting() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null); //test the case when it does not find duplicate storage location setting. ExternalStorageLocationSetting setting = new ExternalStorageLocationSetting(); setting.setBanner(BANNER_2); setting.setUrl("sftp://www.google.com"); Long newStorageLocationId = 1007L; ExternalStorageLocationSetting createdSetting = new ExternalStorageLocationSetting(); createdSetting.setStorageLocationId(newStorageLocationId); when(mockSynapse.createStorageLocationSetting(any(StorageLocationSetting.class))).thenReturn(createdSetting); synapseClient.createStorageLocationSetting(entityId, setting); //should not have found a duplicate storage location, so this should be called verify(mockSynapse).createStorageLocationSetting(any(StorageLocationSetting.class)); //verify creates new project setting, and the new location list is a single value (id of the new storage location) ArgumentCaptor<ProjectSetting> captor = ArgumentCaptor.forClass(ProjectSetting.class); verify(mockSynapse).createProjectSetting(captor.capture()); UploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue(); List<Long> locations = updatedProjectSetting.getLocations(); assertEquals(newStorageLocationId, locations.get(0)); assertEquals(ProjectSettingsType.upload, updatedProjectSetting.getSettingsType()); assertEquals(entityId, updatedProjectSetting.getProjectId()); } @Test(expected = Exception.class) public void testCreateStorageLocationSettingFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception()); synapseClient.createStorageLocationSetting(entityId, new ExternalStorageLocationSetting()); } @Test public void testUpdateTeamAcl() throws SynapseException, RestServiceException { AccessControlList returnedAcl = synapseClient.updateTeamAcl(acl); verify(mockSynapse).updateTeamACL(acl); assertEquals(acl, returnedAcl); } @Test public void testGetTeamAcl() throws SynapseException, RestServiceException { String teamId = "14"; AccessControlList returnedAcl = synapseClient.getTeamAcl(teamId); verify(mockSynapse).getTeamACL(teamId); assertEquals(acl, returnedAcl); } private void setupVersionedEntityBundle(String entityId, Long latestVersionNumber) throws SynapseException { EntityBundle eb = new EntityBundle(); Entity file = new FileEntity(); eb.setEntity(file); eb.getEntity().setId(entityId); when(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb); when(mockSynapse.getEntityBundle(anyString(), anyLong(), anyInt())).thenReturn(eb); PaginatedResults<VersionInfo> versionInfoPaginatedResults = new PaginatedResults<VersionInfo>(); List<VersionInfo> versionInfoList = new LinkedList<VersionInfo>(); VersionInfo versionInfo = new VersionInfo(); versionInfo.setVersionNumber(latestVersionNumber); versionInfoList.add(versionInfo); versionInfoPaginatedResults.setResults(versionInfoList); when(mockSynapse.getEntityVersions(anyString(), anyInt(), anyInt())).thenReturn(versionInfoPaginatedResults); when(mockSynapse.getEntityById(anyString())).thenReturn(file); } @Test public void testGetEntityBundlePlusForVersionVersionable() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = 1L; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), eq(targetVersionNumber), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForNullVersionVersionable() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = null; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForVersionLatestVersion() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = 2L; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForVersionNonVersionable() throws RestServiceException, SynapseException { EntityBundle eb = new EntityBundle(); eb.setEntity(new Folder()); eb.getEntity().setId("syn123"); when(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion("syn123", 123L, 1); assertNull(returnedEntityBundle.getLatestVersionNumber()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), "syn123"); } @Test public void testGetUserIdFromUsername() throws UnsupportedEncodingException, SynapseException, RestServiceException { //find the user id based on user name Long targetUserId = 4L; when(mockPrincipalAliasResponse.getPrincipalId()).thenReturn(targetUserId); when(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenReturn(mockPrincipalAliasResponse); String userId = synapseClient.getUserIdFromUsername("luke"); assertEquals(targetUserId.toString(), userId); } @Test(expected = BadRequestException.class) public void testGetUserIdFromUsernameBackendError() throws UnsupportedEncodingException, SynapseException, RestServiceException { //test error from backend when(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenThrow(new SynapseBadRequestException()); synapseClient.getUserIdFromUsername("bad-request"); } @Test public void testGetTableUpdateTransactionRequestNoChange() throws RestServiceException, SynapseException { String tableId = "syn93939"; List<ColumnModel> oldColumnModels = Collections.singletonList(mockOldColumnModel); when(mockSynapse.createColumnModels(anyList())).thenReturn(oldColumnModels); when(mockSynapse.getColumnModelsForTableEntity(tableId)).thenReturn(oldColumnModels); assertEquals(0, synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, oldColumnModels).getChanges().size()); } @Test public void testGetTableUpdateTransactionRequestNewColumn() throws RestServiceException, SynapseException { String tableId = "syn93939"; List<ColumnModel> oldColumnModels = new ArrayList<ColumnModel>(); when(mockSynapse.createColumnModels(anyList())).thenReturn(Collections.singletonList(mockNewColumnModelAfterCreate)); List<ColumnModel> newColumnModels = Collections.singletonList(mockNewColumnModel); TableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, newColumnModels); verify(mockSynapse).createColumnModels(anyList()); assertEquals(tableId, request.getEntityId()); List<TableUpdateRequest> tableUpdates = request.getChanges(); assertEquals(1, tableUpdates.size()); TableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0); List<ColumnChange> changes = schemaChange.getChanges(); assertEquals(1, changes.size()); ColumnChange columnChange = changes.get(0); assertNull(columnChange.getOldColumnId()); assertEquals(NEW_COLUMN_MODEL_ID, columnChange.getNewColumnId()); } private ColumnModel getColumnModel(String id, ColumnType columnType) { ColumnModel cm = new ColumnModel(); cm.setId(id); cm.setColumnType(columnType); return cm; } private ColumnChange getColumnChange(String oldColumnId, List<ColumnChange> changes) { for (ColumnChange columnChange : changes) { if (Objects.equal(oldColumnId, columnChange.getOldColumnId())) { return columnChange; } } throw new NoSuchElementException(); } @Test public void testGetTableUpdateTransactionRequestFullTest() throws RestServiceException, SynapseException { //In this test, we will change a column, delete a column, and add a column (with appropriately mocked responses) // Modify colA, delete colB, no change to colC, and add colD ColumnModel colA, colB, colC, colD, colAModified, colAAfterSave, colDAfterSave; String tableId = "syn93939"; colA = getColumnModel("1", ColumnType.STRING); colB = getColumnModel("2", ColumnType.STRING); colC = getColumnModel("3", ColumnType.STRING); colD = getColumnModel(null, ColumnType.STRING); colAModified = getColumnModel("1", ColumnType.INTEGER); colAAfterSave = getColumnModel("4", ColumnType.INTEGER); colDAfterSave = getColumnModel("5", ColumnType.STRING); List<ColumnModel> oldSchema = Arrays.asList(colA, colB, colC); List<ColumnModel> proposedNewSchema = Arrays.asList(colAModified, colC, colD); List<ColumnModel> newSchemaAfterUpdate = Arrays.asList(colAAfterSave, colC, colDAfterSave); when(mockSynapse.createColumnModels(anyList())).thenReturn(newSchemaAfterUpdate); TableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldSchema, proposedNewSchema); verify(mockSynapse).createColumnModels(anyList()); assertEquals(tableId, request.getEntityId()); List<TableUpdateRequest> tableUpdates = request.getChanges(); assertEquals(1, tableUpdates.size()); TableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0); //changes should consist of a create, an update, and a delete List<ColumnChange> changes = schemaChange.getChanges(); assertEquals(3, changes.size()); // colB should be deleted ColumnChange columnChange = getColumnChange("2", changes); assertNull(columnChange.getNewColumnId()); // colA should be modified columnChange = getColumnChange("1", changes); assertEquals("4", columnChange.getNewColumnId()); // colD should be new columnChange = getColumnChange(null, changes); assertEquals("5", columnChange.getNewColumnId()); } @Test public void testGetDefaultColumnsForView() throws RestServiceException, SynapseException{ ColumnModel colA, colB; colA = getColumnModel("1", ColumnType.STRING); colB = getColumnModel("2", ColumnType.STRING); List<ColumnModel> defaultColumns = Arrays.asList(colA, colB); when(mockSynapse.getDefaultColumnsForView(any(ViewType.class))).thenReturn(defaultColumns); List<ColumnModel> returnedColumns = synapseClient.getDefaultColumnsForView(ViewType.file); assertEquals(2, returnedColumns.size()); assertNull(returnedColumns.get(0).getId()); assertNull(returnedColumns.get(1).getId()); } @Test(expected = UnknownErrorException.class) public void testUpdateFileEntityWrongResponseSize() throws RestServiceException, SynapseException { synapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest); } @Test(expected = UnknownErrorException.class) public void testUpdateFileEntityWrongResponseSizeTooMany() throws RestServiceException, SynapseException { batchCopyResultsList.add(mockFileHandleCopyResult); batchCopyResultsList.add(mockFileHandleCopyResult); synapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest); } @Test public void testUpdateFileEntity() throws RestServiceException, SynapseException { batchCopyResultsList.add(mockFileHandleCopyResult); when(mockFileHandleCopyResult.getFailureCode()).thenReturn(null); when(mockFileHandleCopyResult.getNewFileHandle()).thenReturn(handle); synapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest); verify(mockSynapse).copyFileHandles(isA(BatchFileHandleCopyRequest.class)); verify(mockFileEntity).setDataFileHandleId(handle.getId()); verify(mockSynapse).putEntity(mockFileEntity); } @Test(expected = NotFoundException.class) public void testUpdateFileEntityNotFound() throws RestServiceException, SynapseException { batchCopyResultsList.add(mockFileHandleCopyResult); when(mockFileHandleCopyResult.getFailureCode()).thenReturn(FileResultFailureCode.NOT_FOUND); synapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest); } @Test(expected = UnauthorizedException.class) public void testUpdateFileEntityUnauthorized() throws RestServiceException, SynapseException { batchCopyResultsList.add(mockFileHandleCopyResult); when(mockFileHandleCopyResult.getFailureCode()).thenReturn(FileResultFailureCode.UNAUTHORIZED); synapseClient.updateFileEntity(mockFileEntity, mockFileHandleCopyRequest); } }
src/test/java/org/sagebionetworks/web/unitserver/SynapseClientImplTest.java
package org.sagebionetworks.web.unitserver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.repo.model.EntityBundle.ACCESS_REQUIREMENTS; import static org.sagebionetworks.repo.model.EntityBundle.ANNOTATIONS; import static org.sagebionetworks.repo.model.EntityBundle.BENEFACTOR_ACL; import static org.sagebionetworks.repo.model.EntityBundle.ENTITY; import static org.sagebionetworks.repo.model.EntityBundle.ENTITY_PATH; import static org.sagebionetworks.repo.model.EntityBundle.FILE_HANDLES; import static org.sagebionetworks.repo.model.EntityBundle.HAS_CHILDREN; import static org.sagebionetworks.repo.model.EntityBundle.PERMISSIONS; import static org.sagebionetworks.repo.model.EntityBundle.ROOT_WIKI_ID; import static org.sagebionetworks.repo.model.EntityBundle.UNMET_ACCESS_REQUIREMENTS; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.client.exceptions.SynapseBadRequestException; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.client.exceptions.SynapseNotFoundException; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.EvaluationStatus; import org.sagebionetworks.evaluation.model.UserEvaluationPermissions; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.AccessControlList; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.Annotations; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityIdList; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.ExampleEntity; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.JoinTeamSignedToken; import org.sagebionetworks.repo.model.LogEntry; import org.sagebionetworks.repo.model.MembershipInvitation; import org.sagebionetworks.repo.model.MembershipInvtnSubmission; import org.sagebionetworks.repo.model.MembershipRequest; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.ProjectHeader; import org.sagebionetworks.repo.model.ProjectListSortColumn; import org.sagebionetworks.repo.model.ProjectListType; import org.sagebionetworks.repo.model.ResourceAccess; import org.sagebionetworks.repo.model.RestrictableObjectDescriptor; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.SignedTokenInterface; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamMember; import org.sagebionetworks.repo.model.TeamMembershipStatus; import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupHeader; import org.sagebionetworks.repo.model.UserGroupHeaderResponsePage; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.UserSessionData; import org.sagebionetworks.repo.model.VersionInfo; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.doi.Doi; import org.sagebionetworks.repo.model.doi.DoiStatus; import org.sagebionetworks.repo.model.entity.query.SortDirection; import org.sagebionetworks.repo.model.file.CompleteAllChunksRequest; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandleResults; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.State; import org.sagebionetworks.repo.model.file.UploadDaemonStatus; import org.sagebionetworks.repo.model.file.UploadDestination; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.message.NotificationSettingsSignedToken; import org.sagebionetworks.repo.model.message.Settings; import org.sagebionetworks.repo.model.principal.AddEmailInfo; import org.sagebionetworks.repo.model.principal.PrincipalAliasRequest; import org.sagebionetworks.repo.model.principal.PrincipalAliasResponse; import org.sagebionetworks.repo.model.project.ExternalS3StorageLocationSetting; import org.sagebionetworks.repo.model.project.ExternalStorageLocationSetting; import org.sagebionetworks.repo.model.project.ProjectSetting; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.StorageLocationSetting; import org.sagebionetworks.repo.model.project.UploadDestinationListSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.Quiz; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.table.ColumnChange; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.TableSchemaChangeRequest; import org.sagebionetworks.repo.model.table.TableUpdateRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.ViewType; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader; import org.sagebionetworks.repo.model.v2.wiki.V2WikiHistorySnapshot; import org.sagebionetworks.repo.model.v2.wiki.V2WikiOrderHint; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.wiki.WikiHeader; import org.sagebionetworks.repo.model.wiki.WikiPage; import org.sagebionetworks.schema.adapter.AdapterFactory; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.schema.adapter.org.json.AdapterFactoryImpl; import org.sagebionetworks.schema.adapter.org.json.EntityFactory; import org.sagebionetworks.util.SerializationUtils; import org.sagebionetworks.web.client.view.TeamRequestBundle; import org.sagebionetworks.web.server.servlet.MarkdownCacheRequest; import org.sagebionetworks.web.server.servlet.NotificationTokenType; import org.sagebionetworks.web.server.servlet.ServiceUrlProvider; import org.sagebionetworks.web.server.servlet.SynapseClientImpl; import org.sagebionetworks.web.server.servlet.SynapseProvider; import org.sagebionetworks.web.server.servlet.TokenProvider; import org.sagebionetworks.web.shared.AccessRequirementUtils; import org.sagebionetworks.web.shared.EntityBundlePlus; import org.sagebionetworks.web.shared.OpenTeamInvitationBundle; import org.sagebionetworks.web.shared.ProjectPagedResults; import org.sagebionetworks.web.shared.TeamBundle; import org.sagebionetworks.web.shared.TeamMemberBundle; import org.sagebionetworks.web.shared.TeamMemberPagedResults; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.shared.exceptions.BadRequestException; import org.sagebionetworks.web.shared.exceptions.ConflictException; import org.sagebionetworks.web.shared.exceptions.NotFoundException; import org.sagebionetworks.web.shared.exceptions.RestServiceException; import org.sagebionetworks.web.shared.users.AclUtils; import org.sagebionetworks.web.shared.users.PermissionLevel; import com.google.appengine.repackaged.com.google.common.base.Objects; import com.google.common.cache.Cache; /** * Test for the SynapseClientImpl * * @author John * */ public class SynapseClientImplTest { private static final String BANNER_2 = "Another Banner"; private static final String BANNER_1 = "Banner 1"; public static final String TEST_HOME_PAGE_BASE = "http://mysynapse.org/"; public static final String MY_USER_PROFILE_OWNER_ID = "MyOwnerID"; SynapseProvider mockSynapseProvider; TokenProvider mockTokenProvider; ServiceUrlProvider mockUrlProvider; SynapseClient mockSynapse; SynapseClientImpl synapseClient; String entityId = "123"; String inviteeUserId = "900"; UserProfile inviteeUserProfile; ExampleEntity entity; Annotations annos; UserEntityPermissions eup; UserEvaluationPermissions userEvaluationPermissions; List<EntityHeader> batchHeaderResults; String testFileName = "testFileEntity.R"; EntityPath path; org.sagebionetworks.reflection.model.PaginatedResults<UserGroup> pgugs; org.sagebionetworks.reflection.model.PaginatedResults<UserProfile> pgups; org.sagebionetworks.reflection.model.PaginatedResults<Team> pguts; Team teamA, teamZ; AccessControlList acl; WikiPage page; V2WikiPage v2Page; S3FileHandle handle; Evaluation mockEvaluation; UserSessionData mockUserSessionData; UserProfile mockUserProfile; MembershipInvtnSubmission testInvitation; PaginatedResults mockPaginatedMembershipRequest; Activity mockActivity; MessageToUser sentMessage; Long storageLocationId = 9090L; UserProfile testUserProfile; Long version = 1L; //Token testing NotificationSettingsSignedToken notificationSettingsToken; JoinTeamSignedToken joinTeamToken; String encodedJoinTeamToken, encodedNotificationSettingsToken; @Mock UserGroupHeaderResponsePage mockUserGroupHeaderResponsePage; @Mock UserGroupHeader mockUserGroupHeader; @Mock PrincipalAliasResponse mockPrincipalAliasResponse; @Mock ColumnModel mockOldColumnModel; @Mock ColumnModel mockNewColumnModel; @Mock ColumnModel mockNewColumnModelAfterCreate; public static final String OLD_COLUMN_MODEL_ID = "4444"; public static final String NEW_COLUMN_MODEL_ID = "837837"; private static final String testUserId = "myUserId"; private static final String EVAL_ID_1 = "eval ID 1"; private static final String EVAL_ID_2 = "eval ID 2"; private static AdapterFactory adapterFactory = new AdapterFactoryImpl(); private TeamMembershipStatus membershipStatus; @Before public void before() throws SynapseException, JSONObjectAdapterException { MockitoAnnotations.initMocks(this); mockSynapse = Mockito.mock(SynapseClient.class); mockSynapseProvider = Mockito.mock(SynapseProvider.class); mockUrlProvider = Mockito.mock(ServiceUrlProvider.class); when(mockSynapseProvider.createNewClient()).thenReturn(mockSynapse); mockTokenProvider = Mockito.mock(TokenProvider.class); mockPaginatedMembershipRequest = Mockito.mock(PaginatedResults.class); mockActivity = Mockito.mock(Activity.class); when(mockPaginatedMembershipRequest.getTotalNumberOfResults()).thenReturn(3L); synapseClient = new SynapseClientImpl(); synapseClient.setSynapseProvider(mockSynapseProvider); synapseClient.setTokenProvider(mockTokenProvider); synapseClient.setServiceUrlProvider(mockUrlProvider); // Setup the the entity entity = new ExampleEntity(); entity.setId(entityId); entity.setEntityType(ExampleEntity.class.getName()); entity.setModifiedBy(testUserId); // the mock synapse should return this object when(mockSynapse.getEntityById(entityId)).thenReturn(entity); // Setup the annotations annos = new Annotations(); annos.setId(entityId); annos.addAnnotation("string", "a string value"); // the mock synapse should return this object when(mockSynapse.getAnnotations(entityId)).thenReturn(annos); // Setup the Permissions eup = new UserEntityPermissions(); eup.setCanDelete(true); eup.setCanView(false); eup.setOwnerPrincipalId(999L); // the mock synapse should return this object when(mockSynapse.getUsersEntityPermissions(entityId)).thenReturn(eup); // user can change permissions on eval 2, but not on 1 userEvaluationPermissions = new UserEvaluationPermissions(); userEvaluationPermissions.setCanChangePermissions(false); when(mockSynapse.getUserEvaluationPermissions(EVAL_ID_1)).thenReturn( userEvaluationPermissions); userEvaluationPermissions = new UserEvaluationPermissions(); userEvaluationPermissions.setCanChangePermissions(true); when(mockSynapse.getUserEvaluationPermissions(EVAL_ID_2)).thenReturn( userEvaluationPermissions); when(mockOldColumnModel.getId()).thenReturn(OLD_COLUMN_MODEL_ID); when(mockNewColumnModelAfterCreate.getId()).thenReturn(NEW_COLUMN_MODEL_ID); // Setup the path path = new EntityPath(); path.setPath(new ArrayList<EntityHeader>()); EntityHeader header = new EntityHeader(); header.setId(entityId); header.setName("RomperRuuuu"); path.getPath().add(header); // the mock synapse should return this object when(mockSynapse.getEntityPath(entityId)).thenReturn(path); pgugs = new org.sagebionetworks.reflection.model.PaginatedResults<UserGroup>(); List<UserGroup> ugs = new ArrayList<UserGroup>(); ugs.add(new UserGroup()); pgugs.setResults(ugs); when(mockSynapse.getGroups(anyInt(), anyInt())).thenReturn(pgugs); pgups = new org.sagebionetworks.reflection.model.PaginatedResults<UserProfile>(); List<UserProfile> ups = new ArrayList<UserProfile>(); ups.add(new UserProfile()); pgups.setResults(ups); when(mockSynapse.getUsers(anyInt(), anyInt())).thenReturn(pgups); pguts = new org.sagebionetworks.reflection.model.PaginatedResults<Team>(); List<Team> uts = new ArrayList<Team>(); teamZ = new Team(); teamZ.setId("1"); teamZ.setName("zygote"); uts.add(teamZ); teamA = new Team(); teamA.setId("2"); teamA.setName("Amplitude"); uts.add(teamA); pguts.setResults(uts); when(mockSynapse.getTeamsForUser(anyString(), anyInt(), anyInt())) .thenReturn(pguts); acl = new AccessControlList(); acl.setId("sys999"); Set<ResourceAccess> ras = new HashSet<ResourceAccess>(); ResourceAccess ra = new ResourceAccess(); ra.setPrincipalId(101L); ra.setAccessType(AclUtils .getACCESS_TYPEs(PermissionLevel.CAN_ADMINISTER)); acl.setResourceAccess(ras); when(mockSynapse.getACL(anyString())).thenReturn(acl); when(mockSynapse.createACL((AccessControlList) any())).thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any())).thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any(), eq(true))) .thenReturn(acl); when(mockSynapse.updateACL((AccessControlList) any(), eq(false))) .thenReturn(acl); when(mockSynapse.updateTeamACL(any(AccessControlList.class))).thenReturn(acl); when(mockSynapse.getTeamACL(anyString())).thenReturn(acl); EntityHeader bene = new EntityHeader(); bene.setId("syn999"); when(mockSynapse.getEntityBenefactor(anyString())).thenReturn(bene); org.sagebionetworks.reflection.model.PaginatedResults<EntityHeader> batchHeaders = new org.sagebionetworks.reflection.model.PaginatedResults<EntityHeader>(); batchHeaderResults = new ArrayList<EntityHeader>(); for (int i = 0; i < 10; i++) { EntityHeader h = new EntityHeader(); h.setId("syn" + i); batchHeaderResults.add(h); } batchHeaders.setResults(batchHeaderResults); when(mockSynapse.getEntityHeaderBatch(anyList())).thenReturn( batchHeaders); List<AccessRequirement> accessRequirements = new ArrayList<AccessRequirement>(); accessRequirements.add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD)); int mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH | HAS_CHILDREN | ACCESS_REQUIREMENTS | UNMET_ACCESS_REQUIREMENTS; int emptyMask = 0; EntityBundle bundle = new EntityBundle(); bundle.setEntity(entity); bundle.setAnnotations(annos); bundle.setPermissions(eup); bundle.setPath(path); bundle.setHasChildren(false); bundle.setAccessRequirements(accessRequirements); bundle.setUnmetAccessRequirements(accessRequirements); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(mask))) .thenReturn(bundle); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(ENTITY | ANNOTATIONS | ROOT_WIKI_ID | FILE_HANDLES | PERMISSIONS | BENEFACTOR_ACL))) .thenReturn(bundle); EntityBundle emptyBundle = new EntityBundle(); when(mockSynapse.getEntityBundle(anyString(), Matchers.eq(emptyMask))) .thenReturn(emptyBundle); when(mockSynapse.canAccess("syn101", ACCESS_TYPE.READ)) .thenReturn(true); page = new WikiPage(); page.setId("testId"); page.setMarkdown("my markdown"); page.setParentWikiId(null); page.setTitle("A Title"); v2Page = new V2WikiPage(); v2Page.setId("v2TestId"); v2Page.setEtag("122333"); handle = new S3FileHandle(); handle.setId("4422"); handle.setBucketName("bucket"); handle.setFileName(testFileName); handle.setKey("key"); when(mockSynapse.getRawFileHandle(anyString())).thenReturn(handle); org.sagebionetworks.reflection.model.PaginatedResults<AccessRequirement> ars = new org.sagebionetworks.reflection.model.PaginatedResults<AccessRequirement>(); ars.setTotalNumberOfResults(0); ars.setResults(new ArrayList<AccessRequirement>()); when( mockSynapse .getAccessRequirements(any(RestrictableObjectDescriptor.class))) .thenReturn(ars); when( mockSynapse.getUnmetAccessRequirements( any(RestrictableObjectDescriptor.class), any(ACCESS_TYPE.class))).thenReturn(ars); mockEvaluation = Mockito.mock(Evaluation.class); when(mockEvaluation.getStatus()).thenReturn(EvaluationStatus.OPEN); when(mockSynapse.getEvaluation(anyString())).thenReturn(mockEvaluation); mockUserSessionData = Mockito.mock(UserSessionData.class); mockUserProfile = Mockito.mock(UserProfile.class); when(mockSynapse.getUserSessionData()).thenReturn(mockUserSessionData); when(mockUserSessionData.getProfile()).thenReturn(mockUserProfile); when(mockUserProfile.getOwnerId()).thenReturn(MY_USER_PROFILE_OWNER_ID); when(mockSynapse.getMyProfile()).thenReturn(mockUserProfile); UploadDaemonStatus status = new UploadDaemonStatus(); String fileHandleId = "myFileHandleId"; status.setFileHandleId(fileHandleId); status.setState(State.COMPLETED); when(mockSynapse.getCompleteUploadDaemonStatus(anyString())) .thenReturn(status); status = new UploadDaemonStatus(); status.setState(State.PROCESSING); status.setPercentComplete(.05d); when(mockSynapse.startUploadDeamon(any(CompleteAllChunksRequest.class))) .thenReturn(status); PaginatedResults<MembershipInvitation> openInvites = new PaginatedResults<MembershipInvitation>(); openInvites.setTotalNumberOfResults(0); when( mockSynapse.getOpenMembershipInvitations(anyString(), anyString(), anyLong(), anyLong())).thenReturn( openInvites); PaginatedResults<MembershipRequest> openRequests = new PaginatedResults<MembershipRequest>(); openRequests.setTotalNumberOfResults(0); when( mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(openRequests); membershipStatus = new TeamMembershipStatus(); membershipStatus.setCanJoin(false); membershipStatus.setHasOpenInvitation(false); membershipStatus.setHasOpenRequest(false); membershipStatus.setHasUnmetAccessRequirement(false); membershipStatus.setIsMember(false); membershipStatus.setMembershipApprovalRequired(false); when(mockSynapse.getTeamMembershipStatus(anyString(), anyString())) .thenReturn(membershipStatus); sentMessage = new MessageToUser(); sentMessage.setId("987"); when(mockSynapse.sendMessage(any(MessageToUser.class))).thenReturn(sentMessage); when(mockSynapse.sendMessage(any(MessageToUser.class), anyString())).thenReturn(sentMessage); // getMyProjects getUserProjects PaginatedResults headers = new PaginatedResults<ProjectHeader>(); headers.setTotalNumberOfResults(1100); List<ProjectHeader> projectHeaders = new ArrayList(); List<UserProfile> userProfile = new ArrayList(); projectHeaders.add(new ProjectHeader()); headers.setResults(projectHeaders); when( mockSynapse.getMyProjects(any(ProjectListType.class), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); when( mockSynapse.getProjectsFromUser(anyLong(), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); when( mockSynapse.getProjectsForTeam(anyLong(), any(ProjectListSortColumn.class), any(SortDirection.class), anyInt(), anyInt())) .thenReturn(headers); testUserProfile = new UserProfile(); testUserProfile.setUserName("Test User"); when(mockSynapse.getUserProfile(eq(testUserId))).thenReturn( testUserProfile); joinTeamToken = new JoinTeamSignedToken(); joinTeamToken.setHmac("98765"); joinTeamToken.setMemberId("1"); joinTeamToken.setTeamId("2"); joinTeamToken.setUserId("3"); encodedJoinTeamToken = SerializationUtils.serializeAndHexEncode(joinTeamToken); notificationSettingsToken = new NotificationSettingsSignedToken(); notificationSettingsToken.setHmac("987654"); notificationSettingsToken.setSettings(new Settings()); notificationSettingsToken.setUserId("4"); encodedNotificationSettingsToken = SerializationUtils.serializeAndHexEncode(notificationSettingsToken); } private AccessRequirement createAccessRequirement(ACCESS_TYPE type) { TermsOfUseAccessRequirement accessRequirement = new TermsOfUseAccessRequirement(); accessRequirement.setConcreteType(TermsOfUseAccessRequirement.class .getName()); RestrictableObjectDescriptor descriptor = new RestrictableObjectDescriptor(); descriptor.setId("101"); descriptor.setType(RestrictableObjectType.ENTITY); accessRequirement.setSubjectIds(Arrays .asList(new RestrictableObjectDescriptor[] { descriptor })); accessRequirement.setAccessType(type); return accessRequirement; } private void setupTeamInvitations() throws SynapseException { ArrayList<MembershipInvtnSubmission> testInvitations = new ArrayList<MembershipInvtnSubmission>(); testInvitation = new MembershipInvtnSubmission(); testInvitation.setId("628319"); testInvitation.setInviteeId(inviteeUserId); testInvitations.add(testInvitation); PaginatedResults<MembershipInvtnSubmission> paginatedInvitations = new PaginatedResults<MembershipInvtnSubmission>(); paginatedInvitations.setResults(testInvitations); when( mockSynapse.getOpenMembershipInvitationSubmissions(anyString(), anyString(), anyLong(), anyLong())).thenReturn( paginatedInvitations); inviteeUserProfile = new UserProfile(); inviteeUserProfile.setUserName("Invitee User"); inviteeUserProfile.setOwnerId(inviteeUserId); when(mockSynapse.getUserProfile(eq(inviteeUserId))).thenReturn( inviteeUserProfile); } @Test public void testGetEntityBundleAll() throws RestServiceException { // Make sure we can get all parts of the bundel int mask = ENTITY | ANNOTATIONS | PERMISSIONS | ENTITY_PATH | HAS_CHILDREN | ACCESS_REQUIREMENTS | UNMET_ACCESS_REQUIREMENTS; EntityBundle bundle = synapseClient.getEntityBundle(entityId, mask); assertNotNull(bundle); // We should have all of the strings assertNotNull(bundle.getEntity()); assertNotNull(bundle.getAnnotations()); assertNotNull(bundle.getPath()); assertNotNull(bundle.getPermissions()); assertNotNull(bundle.getHasChildren()); assertNotNull(bundle.getAccessRequirements()); assertNotNull(bundle.getUnmetAccessRequirements()); } @Test public void testGetEntityBundleNone() throws RestServiceException { // Make sure all are null int mask = 0x0; EntityBundle bundle = synapseClient.getEntityBundle(entityId, mask); assertNotNull(bundle); // We should have all of the strings assertNull(bundle.getEntity()); assertNull(bundle.getAnnotations()); assertNull(bundle.getPath()); assertNull(bundle.getPermissions()); assertNull(bundle.getHasChildren()); assertNull(bundle.getAccessRequirements()); assertNull(bundle.getUnmetAccessRequirements()); } @Test(expected = IllegalArgumentException.class) public void testParseEntityFromJsonNoType() throws JSONObjectAdapterException { ExampleEntity example = new ExampleEntity(); example.setName("some name"); example.setDescription("some description"); // do not set the type String json = EntityFactory.createJSONStringForEntity(example); // This will fail as the type is required synapseClient.parseEntityFromJson(json); } @Test public void testParseEntityFromJson() throws JSONObjectAdapterException { ExampleEntity example = new ExampleEntity(); example.setName("some name"); example.setDescription("some description"); example.setEntityType(ExampleEntity.class.getName()); String json = EntityFactory.createJSONStringForEntity(example); // System.out.println(json); // Now make sure this can be read back ExampleEntity clone = (ExampleEntity) synapseClient .parseEntityFromJson(json); assertEquals(example, clone); } @Test public void testCreateOrUpdateEntityFalse() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.putEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, null, false); assertEquals(out.getId(), result); verify(mockSynapse).putEntity(in); } @Test public void testCreateOrUpdateEntityTrue() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.createEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, null, true); assertEquals(out.getId(), result); verify(mockSynapse).createEntity(in); } @Test public void testCreateOrUpdateEntityTrueWithAnnos() throws JSONObjectAdapterException, RestServiceException, SynapseException { ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setDescription("some description"); in.setEntityType(ExampleEntity.class.getName()); Annotations annos = new Annotations(); annos.addAnnotation("someString", "one"); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setDescription("some description"); out.setEntityType(ExampleEntity.class.getName()); out.setId("syn123"); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.createEntity(in)).thenReturn(out); String result = synapseClient.createOrUpdateEntity(in, annos, true); assertEquals(out.getId(), result); verify(mockSynapse).createEntity(in); annos.setEtag(out.getEtag()); annos.setId(out.getId()); verify(mockSynapse).updateAnnotations(out.getId(), annos); } @Test public void testMoveEntity() throws JSONObjectAdapterException, RestServiceException, SynapseException { String entityId = "syn123"; String oldParentId = "syn1", newParentId = "syn2"; ExampleEntity in = new ExampleEntity(); in.setName("some name"); in.setParentId(oldParentId); in.setId(entityId); in.setEntityType(ExampleEntity.class.getName()); ExampleEntity out = new ExampleEntity(); out.setName("some name"); out.setEntityType(ExampleEntity.class.getName()); out.setId(entityId); out.setParentId(newParentId); out.setEtag("45"); // when in comes in then return out. when(mockSynapse.putEntity(in)).thenReturn(out); when(mockSynapse.getEntityById(entityId)).thenReturn(in); Entity result = synapseClient.moveEntity(entityId, newParentId); assertEquals(newParentId, result.getParentId()); verify(mockSynapse).getEntityById(entityId); verify(mockSynapse).putEntity(any(Entity.class)); } @Test public void testGetEntityBenefactorAcl() throws Exception { EntityBundle bundle = new EntityBundle(); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle("syn101", EntityBundle.BENEFACTOR_ACL)) .thenReturn(bundle); AccessControlList clone = synapseClient .getEntityBenefactorAcl("syn101"); assertEquals(acl, clone); } @Test public void testCreateAcl() throws Exception { AccessControlList clone = synapseClient.createAcl(acl); assertEquals(acl, clone); } @Test public void testUpdateAcl() throws Exception { AccessControlList clone = synapseClient.updateAcl(acl); assertEquals(acl, clone); } @Test public void testUpdateAclRecursive() throws Exception { AccessControlList clone = synapseClient.updateAcl(acl, true); assertEquals(acl, clone); verify(mockSynapse).updateACL(any(AccessControlList.class), eq(true)); } @Test public void testDeleteAcl() throws Exception { EntityBundle bundle = new EntityBundle(); bundle.setBenefactorAcl(acl); when(mockSynapse.getEntityBundle("syn101", EntityBundle.BENEFACTOR_ACL)) .thenReturn(bundle); AccessControlList clone = synapseClient.deleteAcl("syn101"); assertEquals(acl, clone); } @Test public void testHasAccess() throws Exception { assertTrue(synapseClient.hasAccess("syn101", "READ")); } @Test public void testGetUserProfile() throws Exception { // verify call is directly calling the synapse client provider String testRepoUrl = "http://mytestrepourl"; when(mockUrlProvider.getRepositoryServiceUrl()).thenReturn(testRepoUrl); UserProfile userProfile = synapseClient.getUserProfile(testUserId); assertEquals(userProfile, testUserProfile); } @Test public void testGetProjectById() throws Exception { String projectId = "syn1029"; Project project = new Project(); project.setId(projectId); when(mockSynapse.getEntityById(projectId)).thenReturn(project); Project actualProject = synapseClient.getProject(projectId); assertEquals(project, actualProject); } @Test public void testGetJSONEntity() throws Exception { JSONObject json = EntityFactory.createJSONObjectForEntity(entity); Mockito.when(mockSynapse.getEntity(anyString())).thenReturn(json); String testRepoUri = "/testservice"; synapseClient.getJSONEntity(testRepoUri); // verify that this call uses Synapse.getEntity(testRepoUri) verify(mockSynapse).getEntity(testRepoUri); } @Test public void testGetWikiHeaderTree() throws Exception { PaginatedResults<WikiHeader> headerTreeResults = new PaginatedResults<WikiHeader>(); when(mockSynapse.getWikiHeaderTree(anyString(), any(ObjectType.class))) .thenReturn(headerTreeResults); synapseClient.getWikiHeaderTree("testId", ObjectType.ENTITY.toString()); verify(mockSynapse).getWikiHeaderTree(anyString(), eq(ObjectType.ENTITY)); } @Test public void testGetWikiAttachmentHandles() throws Exception { FileHandleResults testResults = new FileHandleResults(); Mockito.when( mockSynapse .getWikiAttachmenthHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(testResults); synapseClient.getWikiAttachmentHandles(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getWikiAttachmenthHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testDeleteV2WikiPage() throws Exception { synapseClient.deleteV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).deleteV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testGetV2WikiPage() throws Exception { Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); synapseClient.getV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY .toString(), "20")); verify(mockSynapse).getV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(v2Page); synapseClient.getVersionOfV2WikiPage(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testUpdateV2WikiPage() throws Exception { Mockito.when( mockSynapse.updateV2WikiPage(anyString(), any(ObjectType.class), any(V2WikiPage.class))) .thenReturn(v2Page); synapseClient.updateV2WikiPage("testId", ObjectType.ENTITY.toString(), v2Page); verify(mockSynapse).updateV2WikiPage(anyString(), any(ObjectType.class), any(V2WikiPage.class)); } @Test public void testRestoreV2WikiPage() throws Exception { String wikiId = "syn123"; Mockito.when( mockSynapse.restoreV2WikiPage(anyString(), any(ObjectType.class), any(String.class), anyLong())) .thenReturn(v2Page); synapseClient.restoreV2WikiPage("ownerId", ObjectType.ENTITY.toString(), wikiId, new Long(2)); verify(mockSynapse).restoreV2WikiPage(anyString(), any(ObjectType.class), any(String.class), anyLong()); } @Test public void testGetV2WikiHeaderTree() throws Exception { PaginatedResults<V2WikiHeader> headerTreeResults = new PaginatedResults<V2WikiHeader>(); when( mockSynapse.getV2WikiHeaderTree(anyString(), any(ObjectType.class))).thenReturn(headerTreeResults); synapseClient.getV2WikiHeaderTree("testId", ObjectType.ENTITY.toString()); verify(mockSynapse).getV2WikiHeaderTree(anyString(), any(ObjectType.class)); } @Test public void testGetV2WikiOrderHint() throws Exception { V2WikiOrderHint orderHint = new V2WikiOrderHint(); when( mockSynapse .getV2OrderHint(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(orderHint); synapseClient.getV2WikiOrderHint(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getV2OrderHint( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); } @Test public void testUpdateV2WikiOrderHint() throws Exception { V2WikiOrderHint orderHint = new V2WikiOrderHint(); when(mockSynapse.updateV2WikiOrderHint(any(V2WikiOrderHint.class))) .thenReturn(orderHint); synapseClient.updateV2WikiOrderHint(orderHint); verify(mockSynapse).updateV2WikiOrderHint(any(V2WikiOrderHint.class)); } @Test public void testGetV2WikiHistory() throws Exception { PaginatedResults<V2WikiHistorySnapshot> historyResults = new PaginatedResults<V2WikiHistorySnapshot>(); when( mockSynapse .getV2WikiHistory( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class), any(Long.class))).thenReturn( historyResults); synapseClient.getV2WikiHistory(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(10), new Long(0)); verify(mockSynapse).getV2WikiHistory( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class), any(Long.class)); } @Test public void testGetV2WikiAttachmentHandles() throws Exception { FileHandleResults testResults = new FileHandleResults(); Mockito.when( mockSynapse .getV2WikiAttachmentHandles(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(testResults); synapseClient.getV2WikiAttachmentHandles(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getVersionOfV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(testResults); synapseClient.getVersionOfV2WikiAttachmentHandles(new WikiPageKey( "syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getVersionOfV2WikiAttachmentHandles( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testZipAndUpload() throws IOException, RestServiceException, JSONObjectAdapterException, SynapseException { Mockito.when( mockSynapse .createFileHandle(any(File.class), any(String.class))) .thenReturn(handle); synapseClient.zipAndUploadFile("markdown", "fileName"); verify(mockSynapse) .createFileHandle(any(File.class), any(String.class)); } @Test public void testGetMarkdown() throws IOException, RestServiceException, SynapseException { String someMarkDown = "someMarkDown"; Mockito.when( mockSynapse .downloadV2WikiMarkdown(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(someMarkDown); synapseClient.getMarkdown(new WikiPageKey("syn123", ObjectType.ENTITY .toString(), "20")); verify(mockSynapse).downloadV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .downloadVersionOfV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(someMarkDown); synapseClient.getVersionOfMarkdown(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).downloadVersionOfV2WikiMarkdown( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } @Test public void testCreateV2WikiPageWithV1() throws Exception { Mockito.when( mockSynapse.createWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class))).thenReturn(page); synapseClient.createV2WikiPageWithV1("testId", ObjectType.ENTITY.toString(), page); verify(mockSynapse).createWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class)); } @Test public void testUpdateV2WikiPageWithV1() throws Exception { Mockito.when( mockSynapse.updateWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class))).thenReturn(page); synapseClient.updateV2WikiPageWithV1("testId", ObjectType.ENTITY.toString(), page); verify(mockSynapse).updateWikiPage(anyString(), any(ObjectType.class), any(WikiPage.class)); } @Test public void getV2WikiPageAsV1() throws Exception { Mockito.when( mockSynapse .getWikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(page); Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); synapseClient.getV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse).getWikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); // asking for the same page twice should result in a cache hit, and it // should not ask for it from the synapse client synapseClient.getV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20")); verify(mockSynapse, Mockito.times(1)).getWikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class)); Mockito.when( mockSynapse .getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class))).thenReturn(page); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), anyLong())).thenReturn(v2Page); synapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse).getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); // asking for the same page twice should result in a cache hit, and it // should not ask for it from the synapse client synapseClient.getVersionOfV2WikiPageAsV1(new WikiPageKey("syn123", ObjectType.ENTITY.toString(), "20"), new Long(0)); verify(mockSynapse, Mockito.times(1)).getWikiPageForVersion( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), any(Long.class)); } private void resetUpdateExternalFileHandleMocks(String testId, FileEntity file, ExternalFileHandle handle) throws SynapseException, JSONObjectAdapterException { reset(mockSynapse); when(mockSynapse.getEntityById(testId)).thenReturn(file); when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(handle); when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file); } @Test public void testUpdateExternalFileHandle() throws Exception { // verify call is directly calling the synapse client provider, and it // tries to rename the entity to the filename String myFileName = "testFileName.csv"; String testUrl = " http://mytesturl/" + myFileName; String testId = "myTestId"; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize=2048L; FileEntity file = new FileEntity(); String originalFileEntityName = "syn1223"; file.setName(originalFileEntityName); file.setId(testId); file.setDataFileHandleId("handle1"); ExternalFileHandle handle = new ExternalFileHandle(); handle.setExternalURL(testUrl); resetUpdateExternalFileHandleMocks(testId, file, handle); synapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId); verify(mockSynapse).getEntityById(testId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor.forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle capturedValue = captor.getValue(); assertEquals(testUrl.trim(), capturedValue.getExternalURL()); assertEquals(md5, capturedValue.getContentMd5()); // assertEquals(fileSize, capturedValue.getContentSize()); verify(mockSynapse).putEntity(any(FileEntity.class)); // and if rename fails, verify all is well (but the FileEntity name is // not updated) resetUpdateExternalFileHandleMocks(testId, file, handle); file.setName(originalFileEntityName); // first call should return file, second call to putEntity should throw // an exception when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn(file) .thenThrow( new IllegalArgumentException( "invalid name for some reason")); synapseClient.updateExternalFile(testId, testUrl, fileSize, md5, storageLocationId); // called createExternalFileHandle verify(mockSynapse).createExternalFileHandle( any(ExternalFileHandle.class)); // and it should have called putEntity again verify(mockSynapse).putEntity(any(FileEntity.class)); } @Test public void testCreateExternalFile() throws Exception { // test setting file handle name String parentEntityId = "syn123333"; String externalUrl = " sftp://foobar.edu/b/test.txt"; String fileName = "testing.txt"; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize = 1024L; when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(new ExternalFileHandle()); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( new FileEntity()); synapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor .forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle handle = captor.getValue(); // verify name is set assertEquals(fileName, handle.getFileName()); assertEquals(externalUrl.trim(), handle.getExternalURL()); assertEquals(storageLocationId, handle.getStorageLocationId()); assertEquals(md5, handle.getContentMd5()); // assertEquals(fileSize, handle.getContentSize()); } @Test public void testCreateExternalFileAutoname() throws Exception { // test setting file handle name String parentEntityId = "syn123333"; String externalUrl = "sftp://foobar.edu/b/test.txt"; String expectedAutoFilename = "test.txt"; String fileName = null; String md5 = "e10e3f4491440ce7b48edc97f03307bb"; Long fileSize = 1024L; when( mockSynapse .createExternalFileHandle(any(ExternalFileHandle.class))) .thenReturn(new ExternalFileHandle()); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( new FileEntity()); synapseClient.createExternalFile(parentEntityId, externalUrl, fileName, fileSize, md5, storageLocationId); ArgumentCaptor<ExternalFileHandle> captor = ArgumentCaptor .forClass(ExternalFileHandle.class); verify(mockSynapse).createExternalFileHandle(captor.capture()); ExternalFileHandle handle = captor.getValue(); // verify name is set assertEquals(expectedAutoFilename, handle.getFileName()); assertEquals(externalUrl, handle.getExternalURL()); assertEquals(storageLocationId, handle.getStorageLocationId()); assertEquals(md5, handle.getContentMd5()); //also check the entity name ArgumentCaptor<Entity> entityCaptor = ArgumentCaptor.forClass(Entity.class); verify(mockSynapse).createEntity(entityCaptor.capture()); assertEquals(expectedAutoFilename, entityCaptor.getValue().getName()); } @Test public void testGetEntityDoi() throws Exception { // wiring test Doi testDoi = new Doi(); testDoi.setDoiStatus(DoiStatus.CREATED); testDoi.setId("test doi id"); testDoi.setCreatedBy("Test User"); testDoi.setCreatedOn(new Date()); testDoi.setObjectId("syn1234"); Mockito.when(mockSynapse.getEntityDoi(anyString(), anyLong())) .thenReturn(testDoi); synapseClient.getEntityDoi("test entity id", null); verify(mockSynapse).getEntityDoi(anyString(), anyLong()); } private FileEntity getTestFileEntity() { FileEntity testFileEntity = new FileEntity(); testFileEntity.setId("5544"); testFileEntity.setName(testFileName); return testFileEntity; } @Test(expected = NotFoundException.class) public void testGetEntityDoiNotFound() throws Exception { // wiring test Mockito.when(mockSynapse.getEntityDoi(anyString(), anyLong())) .thenThrow(new SynapseNotFoundException()); synapseClient.getEntityDoi("test entity id", null); } @Test public void testCreateDoi() throws Exception { // wiring test synapseClient.createDoi("test entity id", null); verify(mockSynapse).createEntityDoi(anyString(), anyLong()); } @Test public void testGetUploadDaemonStatus() throws JSONObjectAdapterException, SynapseException, RestServiceException { synapseClient.getUploadDaemonStatus("daemonId"); verify(mockSynapse).getCompleteUploadDaemonStatus(anyString()); } /** * Direct upload tests. Most of the methods are simple pass-throughs to the * Java Synapse client, but completeUpload has additional logic * * @throws JSONObjectAdapterException * @throws SynapseException * @throws RestServiceException */ @Test public void testCompleteUpload() throws JSONObjectAdapterException, SynapseException, RestServiceException { FileEntity testFileEntity = getTestFileEntity(); when(mockSynapse.createEntity(any(FileEntity.class))).thenReturn( testFileEntity); when(mockSynapse.putEntity(any(FileEntity.class))).thenReturn( testFileEntity); // parent entity has no immediate children EntityIdList childEntities = new EntityIdList(); childEntities.setIdList(new ArrayList()); synapseClient.setFileEntityFileHandle(null, null, "parentEntityId"); // it should have tried to create a new entity (since entity id was // null) verify(mockSynapse).createEntity(any(FileEntity.class)); } @Test(expected = NotFoundException.class) public void testGetFileEntityIdWithSameNameNotFound() throws JSONObjectAdapterException, SynapseException, RestServiceException, JSONException { JSONObject queryResult = new JSONObject(); queryResult.put("totalNumberOfResults", (long) 0); when(mockSynapse.query(anyString())).thenReturn(queryResult); // TODO String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); } @Test(expected = ConflictException.class) public void testGetFileEntityIdWithSameNameConflict() throws JSONObjectAdapterException, SynapseException, RestServiceException, JSONException { Folder folder = new Folder(); folder.setName(testFileName); JSONObject queryResult = new JSONObject(); JSONArray results = new JSONArray(); // Set up results. JSONObject objectResult = EntityFactory .createJSONObjectForEntity(folder); JSONArray typeArray = new JSONArray(); typeArray.put("Folder"); objectResult.put("entity.concreteType", typeArray); results.put(objectResult); // Set up query result. queryResult.put("totalNumberOfResults", (long) 1); queryResult.put("results", results); // Have results returned in query. when(mockSynapse.query(anyString())).thenReturn(queryResult); String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); } @Test public void testGetFileEntityIdWithSameNameFound() throws JSONException, JSONObjectAdapterException, SynapseException, RestServiceException { FileEntity file = getTestFileEntity(); JSONObject queryResult = new JSONObject(); JSONArray results = new JSONArray(); // Set up results. JSONObject objectResult = EntityFactory.createJSONObjectForEntity(file); JSONArray typeArray = new JSONArray(); typeArray.put(FileEntity.class.getName()); objectResult.put("entity.concreteType", typeArray); objectResult.put("entity.id", file.getId()); results.put(objectResult); queryResult.put("totalNumberOfResults", (long) 1); queryResult.put("results", results); // Have results returned in query. when(mockSynapse.query(anyString())).thenReturn(queryResult); String fileEntityId = synapseClient.getFileEntityIdWithSameName( testFileName, "parentEntityId"); assertEquals(fileEntityId, file.getId()); } @Test public void testInviteMemberOpenInvitations() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setHasOpenInvitation(true); // verify it does not create a new invitation since one is already open synapseClient.inviteMember("123", "a team", "", ""); verify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(), anyString(), anyString(), anyString()); verify(mockSynapse, Mockito.times(0)).createMembershipInvitation( any(MembershipInvtnSubmission.class), anyString(), anyString()); } @Test public void testRequestMemberOpenRequests() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setHasOpenRequest(true); // verify it does not create a new request since one is already open synapseClient.requestMembership("123", "a team", "let me join", TEST_HOME_PAGE_BASE, null); verify(mockSynapse, Mockito.times(0)).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); } @Test public void testInviteMemberCanJoin() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setCanJoin(true); synapseClient.inviteMember("123", "a team", "", TEST_HOME_PAGE_BASE); verify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testRequestMembershipCanJoin() throws SynapseException, RestServiceException, JSONObjectAdapterException { membershipStatus.setCanJoin(true); synapseClient.requestMembership("123", "a team", "", TEST_HOME_PAGE_BASE, new Date()); verify(mockSynapse).addTeamMember(anyString(), anyString(), eq(TEST_HOME_PAGE_BASE+"#!Team:"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testInviteMember() throws SynapseException, RestServiceException, JSONObjectAdapterException { synapseClient.inviteMember("123", "a team", "", TEST_HOME_PAGE_BASE); verify(mockSynapse).createMembershipInvitation( any(MembershipInvtnSubmission.class), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); } @Test public void testRequestMembership() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); String teamId = "a team"; String message= "let me join"; Date expiresOn = null; synapseClient.requestMembership("123", teamId, message, TEST_HOME_PAGE_BASE, expiresOn); verify(mockSynapse).createMembershipRequest( captor.capture(), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); MembershipRqstSubmission request = captor.getValue(); assertEquals(expiresOn, request.getExpiresOn()); assertEquals(teamId, request.getTeamId()); assertEquals(message, request.getMessage()); } @Test public void testRequestMembershipWithExpiresOn() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MembershipRqstSubmission> captor = ArgumentCaptor.forClass(MembershipRqstSubmission.class); verify(mockSynapse, Mockito.times(0)).createMembershipRequest( captor.capture(), anyString(), anyString()); String teamId = "a team"; String message= "let me join"; Date expiresOn = new Date(); synapseClient.requestMembership("123", teamId, message, TEST_HOME_PAGE_BASE, expiresOn); verify(mockSynapse).createMembershipRequest( captor.capture(), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:JoinTeam/"), eq(TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/")); MembershipRqstSubmission request = captor.getValue(); assertEquals(expiresOn, request.getExpiresOn()); assertEquals(teamId, request.getTeamId()); assertEquals(message, request.getMessage()); } @Test public void testGetOpenRequestCountUnauthorized() throws SynapseException, RestServiceException { // is not an admin TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(false); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); Long count = synapseClient.getOpenRequestCount("myUserId", "myTeamId"); // should never ask for open request count verify(mockSynapse, Mockito.never()).getOpenMembershipRequests( anyString(), anyString(), anyLong(), anyLong()); assertNull(count); } @Test public void testGetOpenRequestCount() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // is admin TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(true); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); Long testCount = 42L; PaginatedResults<MembershipRequest> testOpenRequests = new PaginatedResults<MembershipRequest>(); testOpenRequests.setTotalNumberOfResults(testCount); when( mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(testOpenRequests); Long count = synapseClient.getOpenRequestCount("myUserId", "myTeamId"); verify(mockSynapse, Mockito.times(1)).getOpenMembershipRequests( anyString(), anyString(), anyLong(), anyLong()); assertEquals(testCount, count); } @Test public void testGetOpenTeamInvitations() throws SynapseException, RestServiceException, JSONObjectAdapterException { setupTeamInvitations(); int limit = 55; int offset = 2; String teamId = "132"; List<OpenTeamInvitationBundle> invitationBundles = synapseClient .getOpenTeamInvitations(teamId, limit, offset); verify(mockSynapse).getOpenMembershipInvitationSubmissions(eq(teamId), anyString(), eq((long) limit), eq((long) offset)); // we set this up so that a single invite would be returned. Verify that // it is the one we're looking for assertEquals(1, invitationBundles.size()); OpenTeamInvitationBundle invitationBundle = invitationBundles.get(0); assertEquals(inviteeUserProfile, invitationBundle.getUserProfile()); assertEquals(testInvitation, invitationBundle.getMembershipInvtnSubmission()); } @Test public void testGetTeamBundle() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // set team member count Long testMemberCount = 111L; PaginatedResults<TeamMember> allMembers = new PaginatedResults<TeamMember>(); allMembers.setTotalNumberOfResults(testMemberCount); when( mockSynapse.getTeamMembers(anyString(), anyString(), anyLong(), anyLong())).thenReturn(allMembers); // set team Team team = new Team(); team.setId("test team id"); when(mockSynapse.getTeam(anyString())).thenReturn(team); // is member TeamMembershipStatus membershipStatus = new TeamMembershipStatus(); membershipStatus.setIsMember(true); when(mockSynapse.getTeamMembershipStatus(anyString(), anyString())) .thenReturn(membershipStatus); // is admin TeamMember testTeamMember = new TeamMember(); boolean isAdmin = true; testTeamMember.setIsAdmin(isAdmin); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); // make the call TeamBundle bundle = synapseClient.getTeamBundle("myUserId", "myTeamId", true); // now verify round all values were returned in the bundle (based on the // mocked service calls) assertEquals(team, bundle.getTeam()); assertEquals(membershipStatus, bundle.getTeamMembershipStatus()); assertEquals(isAdmin, bundle.isUserAdmin()); assertEquals(testMemberCount, bundle.getTotalMemberCount()); } @Test public void testGetTeamMembers() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { // set team member count Long testMemberCount = 111L; PaginatedResults<TeamMember> allMembers = new PaginatedResults<TeamMember>(); allMembers.setTotalNumberOfResults(testMemberCount); List<TeamMember> members = new ArrayList<TeamMember>(); TeamMember member1 = new TeamMember(); member1.setIsAdmin(true); UserGroupHeader header1 = new UserGroupHeader(); Long member1Id = 123L; header1.setOwnerId(member1Id + ""); member1.setMember(header1); members.add(member1); TeamMember member2 = new TeamMember(); member2.setIsAdmin(false); UserGroupHeader header2 = new UserGroupHeader(); Long member2Id = 456L; header2.setOwnerId(member2Id + ""); member2.setMember(header2); members.add(member2); allMembers.setResults(members); when( mockSynapse.getTeamMembers(anyString(), anyString(), anyLong(), anyLong())).thenReturn(allMembers); List<UserProfile> profiles = new ArrayList<UserProfile>(); UserProfile profile1 = new UserProfile(); profile1.setOwnerId(member1Id + ""); UserProfile profile2 = new UserProfile(); profile2.setOwnerId(member2Id + ""); profiles.add(profile1); profiles.add(profile2); when(mockSynapse.listUserProfiles(anyList())).thenReturn(profiles); // make the call TeamMemberPagedResults results = synapseClient.getTeamMembers( "myTeamId", "search term", 100, 0); // verify it results in the two team member bundles that we expect List<TeamMemberBundle> memberBundles = results.getResults(); assertEquals(2, memberBundles.size()); TeamMemberBundle bundle1 = memberBundles.get(0); assertTrue(bundle1.getIsTeamAdmin()); assertEquals(profile1, bundle1.getUserProfile()); TeamMemberBundle bundle2 = memberBundles.get(1); assertFalse(bundle2.getIsTeamAdmin()); assertEquals(profile2, bundle2.getUserProfile()); } @Test public void testIsTeamMember() throws NumberFormatException, RestServiceException, SynapseException { synapseClient.isTeamMember(entityId, Long.valueOf(teamA.getId())); verify(mockSynapse).getTeamMembershipStatus(teamA.getId(), entityId); } @Test public void testGetEntityHeaderBatch() throws SynapseException, RestServiceException, MalformedURLException, JSONObjectAdapterException { List<EntityHeader> headers = synapseClient .getEntityHeaderBatch(new ArrayList()); // in the setup, we told the mockSynapse.getEntityHeaderBatch to return // batchHeaderResults for (int i = 0; i < batchHeaderResults.size(); i++) { assertEquals(batchHeaderResults.get(i), headers.get(i)); } } @Test public void testSendMessage() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MessageToUser> arg = ArgumentCaptor .forClass(MessageToUser.class); Set<String> recipients = new HashSet<String>(); recipients.add("333"); String subject = "The Mathematics of Quantum Neutrino Fields"; String messageBody = "Atoms are not to be trusted, they make up everything"; String hostPageBaseURL = "http://localhost/Portal.html"; synapseClient.sendMessage(recipients, subject, messageBody, hostPageBaseURL); verify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE)); verify(mockSynapse).sendMessage(arg.capture()); MessageToUser toSendMessage = arg.getValue(); assertEquals(subject, toSendMessage.getSubject()); assertEquals(recipients, toSendMessage.getRecipients()); assertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL)); } @Test public void testSendMessageToEntityOwner() throws SynapseException, RestServiceException, JSONObjectAdapterException { ArgumentCaptor<MessageToUser> arg = ArgumentCaptor .forClass(MessageToUser.class); ArgumentCaptor<String> entityIdCaptor = ArgumentCaptor .forClass(String.class); String subject = "The Mathematics of Quantum Neutrino Fields"; String messageBody = "Atoms are not to be trusted, they make up everything"; String hostPageBaseURL = "http://localhost/Portal.html"; String entityId = "syn98765"; synapseClient.sendMessageToEntityOwner(entityId, subject, messageBody, hostPageBaseURL); verify(mockSynapse).uploadToFileHandle(any(byte[].class), eq(SynapseClientImpl.HTML_MESSAGE_CONTENT_TYPE)); verify(mockSynapse).sendMessage(arg.capture(), entityIdCaptor.capture()); MessageToUser toSendMessage = arg.getValue(); assertEquals(subject, toSendMessage.getSubject()); assertEquals(entityId, entityIdCaptor.getValue()); assertTrue(toSendMessage.getNotificationUnsubscribeEndpoint().startsWith(hostPageBaseURL)); } @Test public void testGetCertifiedUserPassingRecord() throws RestServiceException, SynapseException, JSONObjectAdapterException { PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(true); passingRecord.setQuizId(1238L); String passingRecordJson = passingRecord.writeToJSONObject( adapterFactory.createNew()).toJSONString(); when(mockSynapse.getCertifiedUserPassingRecord(anyString())) .thenReturn(passingRecord); String returnedPassingRecordJson = synapseClient .getCertifiedUserPassingRecord("123"); verify(mockSynapse).getCertifiedUserPassingRecord(anyString()); assertEquals(passingRecordJson, returnedPassingRecordJson); } @Test(expected = NotFoundException.class) public void testUserNeverAttemptedCertification() throws RestServiceException, SynapseException { when(mockSynapse.getCertifiedUserPassingRecord(anyString())).thenThrow( new SynapseNotFoundException("PassingRecord not found")); synapseClient.getCertifiedUserPassingRecord("123"); } @Test(expected = NotFoundException.class) public void testUserFailedCertification() throws RestServiceException, SynapseException { PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(false); passingRecord.setQuizId(1238L); when(mockSynapse.getCertifiedUserPassingRecord(anyString())) .thenReturn(passingRecord); synapseClient.getCertifiedUserPassingRecord("123"); } @Test public void testGetCertificationQuiz() throws RestServiceException, SynapseException { when(mockSynapse.getCertifiedUserTest()).thenReturn(new Quiz()); synapseClient.getCertificationQuiz(); verify(mockSynapse).getCertifiedUserTest(); } @Test public void testSubmitCertificationQuizResponse() throws RestServiceException, SynapseException, JSONObjectAdapterException { PassingRecord mockPassingRecord = new PassingRecord(); when( mockSynapse .submitCertifiedUserTestResponse(any(QuizResponse.class))) .thenReturn(mockPassingRecord); QuizResponse myResponse = new QuizResponse(); myResponse.setId(837L); synapseClient.submitCertificationQuizResponse(myResponse); verify(mockSynapse).submitCertifiedUserTestResponse(eq(myResponse)); } @Test public void testMarkdownCache() throws Exception { Cache<MarkdownCacheRequest, WikiPage> mockCache = Mockito .mock(Cache.class); synapseClient.setMarkdownCache(mockCache); WikiPage page = new WikiPage(); when(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page); Mockito.when( mockSynapse .getV2WikiPage(any(org.sagebionetworks.repo.model.dao.WikiPageKey.class))) .thenReturn(v2Page); WikiPage actualResult = synapseClient .getV2WikiPageAsV1(new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), "12")); assertEquals(page, actualResult); verify(mockCache).get(any(MarkdownCacheRequest.class)); } @Test public void testMarkdownCacheWithVersion() throws Exception { Cache<MarkdownCacheRequest, WikiPage> mockCache = Mockito .mock(Cache.class); synapseClient.setMarkdownCache(mockCache); WikiPage page = new WikiPage(); when(mockCache.get(any(MarkdownCacheRequest.class))).thenReturn(page); Mockito.when( mockSynapse .getVersionOfV2WikiPage( any(org.sagebionetworks.repo.model.dao.WikiPageKey.class), anyLong())).thenReturn(v2Page); WikiPage actualResult = synapseClient.getVersionOfV2WikiPageAsV1( new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), "12"), 5L); assertEquals(page, actualResult); verify(mockCache).get(any(MarkdownCacheRequest.class)); } @Test public void testFilterAccessRequirements() throws Exception { List<AccessRequirement> unfilteredAccessRequirements = new ArrayList<AccessRequirement>(); List<AccessRequirement> filteredAccessRequirements; // filter empty list should not result in failure filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.UPDATE); assertTrue(filteredAccessRequirements.isEmpty()); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.DOWNLOAD)); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.SUBMIT)); unfilteredAccessRequirements .add(createAccessRequirement(ACCESS_TYPE.SUBMIT)); // no requirements of type UPDATE filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.UPDATE); assertTrue(filteredAccessRequirements.isEmpty()); // 1 download filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.DOWNLOAD); assertEquals(1, filteredAccessRequirements.size()); // 2 submit filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(unfilteredAccessRequirements, ACCESS_TYPE.SUBMIT); assertEquals(2, filteredAccessRequirements.size()); // finally, filter null list - result will be an empty list filteredAccessRequirements = AccessRequirementUtils .filterAccessRequirements(null, ACCESS_TYPE.SUBMIT); assertNotNull(filteredAccessRequirements); assertTrue(filteredAccessRequirements.isEmpty()); } @Test public void testGetEntityUnmetAccessRequirements() throws Exception { // verify it calls getUnmetAccessRequirements when unmet is true synapseClient.getEntityAccessRequirements(entityId, true, null); verify(mockSynapse) .getUnmetAccessRequirements( any(RestrictableObjectDescriptor.class), any(ACCESS_TYPE.class)); } @Test public void testGetAllEntityAccessRequirements() throws Exception { // verify it calls getAccessRequirements when unmet is false synapseClient.getEntityAccessRequirements(entityId, false, null); verify(mockSynapse).getAccessRequirements( any(RestrictableObjectDescriptor.class)); } // pass through tests for email validation @Test public void testAdditionalEmailValidation() throws Exception { Long userId = 992843l; String emailAddress = "[email protected]"; String callbackUrl = "http://www.synapse.org/#!Account:"; synapseClient.additionalEmailValidation(userId.toString(), emailAddress, callbackUrl); verify(mockSynapse).additionalEmailValidation(eq(userId), eq(emailAddress), eq(callbackUrl)); } @Test public void testAddEmail() throws Exception { String emailAddressToken = "long synapse email token"; synapseClient.addEmail(emailAddressToken); verify(mockSynapse).addEmail(any(AddEmailInfo.class), anyBoolean()); } @Test public void testGetNotificationEmail() throws Exception { synapseClient.getNotificationEmail(); verify(mockSynapse).getNotificationEmail(); } @Test public void testSetNotificationEmail() throws Exception { String emailAddress = "[email protected]"; synapseClient.setNotificationEmail(emailAddress); verify(mockSynapse).setNotificationEmail(eq(emailAddress)); } @Test public void testLogErrorToRepositoryServices() throws SynapseException, RestServiceException, JSONObjectAdapterException { String errorMessage = "error has occurred"; String permutationStrongName="Chrome"; synapseClient.logErrorToRepositoryServices(errorMessage, null, null, null, permutationStrongName); verify(mockSynapse).getMyProfile(); verify(mockSynapse).logError(any(LogEntry.class)); } @Test public void testLogErrorToRepositoryServicesTruncation() throws SynapseException, RestServiceException, JSONObjectAdapterException, ServletException { String exceptionMessage = "This exception brought to you by Sage Bionetworks"; Exception e = new Exception(exceptionMessage, new IllegalArgumentException(new NullPointerException())); ServletContext mockServletContext = Mockito.mock(ServletContext.class); ServletConfig mockServletConfig = Mockito.mock(ServletConfig.class); when(mockServletConfig.getServletContext()).thenReturn(mockServletContext); synapseClient.init(mockServletConfig); String errorMessage = "error has occurred"; String permutationStrongName="FF"; synapseClient.logErrorToRepositoryServices(errorMessage, e.getClass().getSimpleName(), e.getMessage(), e.getStackTrace(), permutationStrongName); ArgumentCaptor<LogEntry> captor = ArgumentCaptor .forClass(LogEntry.class); verify(mockSynapse).logError(captor.capture()); LogEntry logEntry = captor.getValue(); assertTrue(logEntry.getLabel().length() < SynapseClientImpl.MAX_LOG_ENTRY_LABEL_SIZE + 100); assertTrue(logEntry.getMessage().contains(errorMessage)); assertTrue(logEntry.getMessage().contains(MY_USER_PROFILE_OWNER_ID)); assertTrue(logEntry.getMessage().contains(e.getClass().getSimpleName())); assertTrue(logEntry.getMessage().contains(exceptionMessage)); } @Test public void testGetMyProjects() throws Exception { int limit = 11; int offset = 20; ProjectPagedResults results = synapseClient.getMyProjects(ProjectListType.MY_PROJECTS, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getMyProjects(eq(ProjectListType.MY_PROJECTS), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testGetUserProjects() throws Exception { int limit = 11; int offset = 20; Long userId = 133l; String userIdString = userId.toString(); synapseClient.getUserProjects(userIdString, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getProjectsFromUser(eq(userId), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testGetProjectsForTeam() throws Exception { int limit = 13; int offset = 40; Long teamId = 144l; String teamIdString = teamId.toString(); synapseClient.getProjectsForTeam(teamIdString, limit, offset, ProjectListSortColumn.LAST_ACTIVITY, SortDirection.DESC); verify(mockSynapse).getProjectsForTeam(eq(teamId), eq(ProjectListSortColumn.LAST_ACTIVITY), eq(SortDirection.DESC), eq(limit), eq(offset)); verify(mockSynapse).listUserProfiles(anyList()); } @Test public void testSafeLongToInt() { int inRangeInt = 500; int after = SynapseClientImpl.safeLongToInt(inRangeInt); assertEquals(inRangeInt, after); } @Test(expected = IllegalArgumentException.class) public void testSafeLongToIntPositive() { long testValue = Integer.MAX_VALUE; testValue++; SynapseClientImpl.safeLongToInt(testValue); } @Test(expected = IllegalArgumentException.class) public void testSafeLongToIntNegative() { long testValue = Integer.MIN_VALUE; testValue--; SynapseClientImpl.safeLongToInt(testValue); } @Test public void testGetHost() throws RestServiceException { assertEquals("mydomain.com", synapseClient.getHost("sfTp://mydomain.com/foo/bar")); assertEquals("mydomain.com", synapseClient.getHost("http://mydomain.com/foo/bar")); assertEquals("mydomain.com", synapseClient.getHost("http://mydomain.com")); assertEquals("mydomain.com", synapseClient.getHost("sftp://mydomain.com:22/foo/bar")); } @Test(expected = IllegalArgumentException.class) public void testGetHostNull() throws RestServiceException { synapseClient.getHost(null); } @Test(expected = IllegalArgumentException.class) public void testGetHostEmpty() throws RestServiceException { synapseClient.getHost(""); } @Test(expected = BadRequestException.class) public void testGetHostBadUrl() throws RestServiceException { synapseClient.getHost("foobar"); } @Test public void testGetRootWikiId() throws JSONObjectAdapterException, SynapseException, RestServiceException { org.sagebionetworks.repo.model.dao.WikiPageKey key = new org.sagebionetworks.repo.model.dao.WikiPageKey(); key.setOwnerObjectId("1"); key.setOwnerObjectType(ObjectType.ENTITY); String expectedId = "123"; key.setWikiPageId(expectedId); when(mockSynapse.getRootWikiPageKey(anyString(), any(ObjectType.class))) .thenReturn(key); String actualId = synapseClient.getRootWikiId("1", ObjectType.ENTITY.toString()); assertEquals(expectedId, actualId); } @Test public void testGetFavorites() throws JSONObjectAdapterException, SynapseException, RestServiceException { PaginatedResults<EntityHeader> pagedResults = new PaginatedResults<EntityHeader>(); List<EntityHeader> unsortedResults = new ArrayList<EntityHeader>(); pagedResults.setResults(unsortedResults); when(mockSynapse.getFavorites(anyInt(), anyInt())).thenReturn( pagedResults); // test empty favorites List<EntityHeader> actualList = synapseClient.getFavorites(); assertTrue(actualList.isEmpty()); // test a few unsorted favorites EntityHeader favZ = new EntityHeader(); favZ.setName("Z"); unsortedResults.add(favZ); EntityHeader favA = new EntityHeader(); favA.setName("A"); unsortedResults.add(favA); EntityHeader favQ = new EntityHeader(); favQ.setName("q"); unsortedResults.add(favQ); actualList = synapseClient.getFavorites(); assertEquals(3, actualList.size()); assertEquals(favA, actualList.get(0)); assertEquals(favQ, actualList.get(1)); assertEquals(favZ, actualList.get(2)); } @Test public void testGetTeamBundlesNotOwner() throws RestServiceException, SynapseException { // the paginated results were set up to return {teamZ, teamA}, but // servlet side we sort by name. List<TeamRequestBundle> results = synapseClient.getTeamsForUser("abba", false); verify(mockSynapse).getTeamsForUser(eq("abba"), anyInt(), anyInt()); assertEquals(2, results.size()); assertEquals(teamA, results.get(0).getTeam()); assertEquals(teamZ, results.get(1).getTeam()); verify(mockSynapse, Mockito.never()).getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong()); } @Test public void testGetTeamBundlesOwner() throws RestServiceException, SynapseException { TeamMember testTeamMember = new TeamMember(); testTeamMember.setIsAdmin(true); when(mockSynapse.getTeamMember(anyString(), anyString())).thenReturn( testTeamMember); when(mockSynapse.getOpenMembershipRequests(anyString(), anyString(), anyLong(), anyLong())).thenReturn(mockPaginatedMembershipRequest); List<TeamRequestBundle> results = synapseClient.getTeamsForUser("abba", true); verify(mockSynapse).getTeamsForUser(eq("abba"), anyInt(), anyInt()); assertEquals(2, results.size()); assertEquals(teamA, results.get(0).getTeam()); assertEquals(teamZ, results.get(1).getTeam()); Long reqCount1 = results.get(0).getRequestCount(); Long reqCount2 = results.get(1).getRequestCount(); assertEquals(new Long(3L), results.get(0).getRequestCount()); assertEquals(new Long(3L), results.get(1).getRequestCount()); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenNull() throws RestServiceException, SynapseException{ String tokenTypeName = null; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenEmpty() throws RestServiceException, SynapseException{ String tokenTypeName = ""; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenUnrecognized() throws RestServiceException, SynapseException{ String tokenTypeName = "InvalidTokenType"; synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); } @Test public void testHandleSignedTokenJoinTeam() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.JoinTeam.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedJoinTeamToken); synapseClient.handleSignedToken(token,TEST_HOME_PAGE_BASE); verify(mockSynapse).addTeamMember(joinTeamToken, TEST_HOME_PAGE_BASE+"#!Team:", TEST_HOME_PAGE_BASE+"#!SignedToken:Settings/"); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenInvalidJoinTeam() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.JoinTeam.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, "invalid token"); } @Test public void testHandleSignedTokenNotificationSettings() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.Settings.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, encodedNotificationSettingsToken); synapseClient.handleSignedToken(token, TEST_HOME_PAGE_BASE); verify(mockSynapse).updateNotificationSettings(notificationSettingsToken); } @Test(expected = BadRequestException.class) public void testHandleSignedTokenInvalidNotificationSettings() throws RestServiceException, SynapseException{ String tokenTypeName = NotificationTokenType.Settings.name(); SignedTokenInterface token = synapseClient.hexDecodeAndDeserialize(tokenTypeName, "invalid token"); } @Test public void testGetOrCreateActivityForEntityVersionGet() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenReturn(new Activity()); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); verify(mockSynapse).getActivityForEntityVersion(entityId, version); } @Test public void testGetOrCreateActivityForEntityVersionCreate() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new SynapseNotFoundException()); when(mockSynapse.createActivity(any(Activity.class))).thenReturn(mockActivity); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); verify(mockSynapse).getActivityForEntityVersion(entityId, version); verify(mockSynapse).createActivity(any(Activity.class)); verify(mockSynapse).putEntity(mockSynapse.getEntityById(entityId), mockActivity.getId()); } @Test(expected = Exception.class) public void testGetOrCreateActivityForEntityVersionFailure() throws SynapseException, RestServiceException { when(mockSynapse.getActivityForEntityVersion(anyString(), anyLong())).thenThrow(new Exception()); synapseClient.getOrCreateActivityForEntityVersion(entityId, version); } private void setupGetMyLocationSettings() throws SynapseException, RestServiceException{ List<StorageLocationSetting> existingStorageLocations = new ArrayList<StorageLocationSetting>(); StorageLocationSetting storageLocation = new ExternalS3StorageLocationSetting(); storageLocation.setStorageLocationId(1L); storageLocation.setBanner(BANNER_1); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(2L); storageLocation.setBanner(BANNER_2); ((ExternalStorageLocationSetting)storageLocation).setUrl("sftp://www.jayhodgson.com"); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(3L); storageLocation.setBanner(BANNER_1); existingStorageLocations.add(storageLocation); storageLocation = new ExternalStorageLocationSetting(); storageLocation.setStorageLocationId(4L); storageLocation.setBanner(null); existingStorageLocations.add(storageLocation); when(mockSynapse.getMyStorageLocationSettings()).thenReturn(existingStorageLocations); } @Test public void testGetMyLocationSettingBanners() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); List<String> banners = synapseClient.getMyLocationSettingBanners(); verify(mockSynapse).getMyStorageLocationSettings(); //should be 2 (only returns unique values) assertEquals(2, banners.size()); assertTrue(banners.contains(BANNER_1)); assertTrue(banners.contains(BANNER_2)); } @Test(expected = Exception.class) public void testGetMyLocationSettingBannersFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSettings()).thenThrow(new Exception()); synapseClient.getMyLocationSettingBanners(); } @Test public void testGetStorageLocationSettingNullSetting() throws SynapseException, RestServiceException { when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null); assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSettingNullUploadDestination() throws SynapseException, RestServiceException { assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSettingDefaultUploadDestination() throws SynapseException, RestServiceException { UploadDestination setting = Mockito.mock(UploadDestination.class); String defaultStorageId = synapseClient.getSynapseProperties().get(SynapseClientImpl.DEFAULT_STORAGE_ID_PROPERTY_KEY); when(setting.getStorageLocationId()).thenReturn(Long.parseLong(defaultStorageId)); when(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting); StorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class); when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting); assertNull(synapseClient.getStorageLocationSetting(entityId)); } @Test public void testGetStorageLocationSetting() throws SynapseException, RestServiceException { UploadDestination setting = Mockito.mock(UploadDestination.class); when(setting.getStorageLocationId()).thenReturn(42L); when(mockSynapse.getDefaultUploadDestination(entityId)).thenReturn(setting); StorageLocationSetting mockStorageLocationSetting = Mockito.mock(StorageLocationSetting.class); when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenReturn(mockStorageLocationSetting); assertEquals(mockStorageLocationSetting, synapseClient.getStorageLocationSetting(entityId)); } @Test(expected = Exception.class) public void testGetStorageLocationSettingFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception()); synapseClient.getStorageLocationSetting(entityId); } @Test public void testCreateStorageLocationSettingFoundStorageAndProjectSetting() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); UploadDestinationListSetting projectSetting = new UploadDestinationListSetting(); projectSetting.setLocations(Collections.EMPTY_LIST); when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(projectSetting); //test the case when it finds a duplicate storage location. ExternalStorageLocationSetting setting = new ExternalStorageLocationSetting(); setting.setBanner(BANNER_2); setting.setUrl("sftp://www.jayhodgson.com"); synapseClient.createStorageLocationSetting(entityId, setting); //should have found the duplicate storage location, so this is never called verify(mockSynapse, Mockito.never()).createStorageLocationSetting(any(StorageLocationSetting.class)); //verify updates project setting, and the new location list is a single value (id of existing storage location) ArgumentCaptor<ProjectSetting> captor = ArgumentCaptor.forClass(ProjectSetting.class); verify(mockSynapse).updateProjectSetting(captor.capture()); UploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue(); List<Long> locations = updatedProjectSetting.getLocations(); assertEquals(new Long(2), locations.get(0)); } @Test public void testCreateStorageLocationSettingNewStorageAndProjectSetting() throws SynapseException, RestServiceException { setupGetMyLocationSettings(); when(mockSynapse.getProjectSetting(entityId, ProjectSettingsType.upload)).thenReturn(null); //test the case when it does not find duplicate storage location setting. ExternalStorageLocationSetting setting = new ExternalStorageLocationSetting(); setting.setBanner(BANNER_2); setting.setUrl("sftp://www.google.com"); Long newStorageLocationId = 1007L; ExternalStorageLocationSetting createdSetting = new ExternalStorageLocationSetting(); createdSetting.setStorageLocationId(newStorageLocationId); when(mockSynapse.createStorageLocationSetting(any(StorageLocationSetting.class))).thenReturn(createdSetting); synapseClient.createStorageLocationSetting(entityId, setting); //should not have found a duplicate storage location, so this should be called verify(mockSynapse).createStorageLocationSetting(any(StorageLocationSetting.class)); //verify creates new project setting, and the new location list is a single value (id of the new storage location) ArgumentCaptor<ProjectSetting> captor = ArgumentCaptor.forClass(ProjectSetting.class); verify(mockSynapse).createProjectSetting(captor.capture()); UploadDestinationListSetting updatedProjectSetting = (UploadDestinationListSetting)captor.getValue(); List<Long> locations = updatedProjectSetting.getLocations(); assertEquals(newStorageLocationId, locations.get(0)); assertEquals(ProjectSettingsType.upload, updatedProjectSetting.getSettingsType()); assertEquals(entityId, updatedProjectSetting.getProjectId()); } @Test(expected = Exception.class) public void testCreateStorageLocationSettingFailure() throws SynapseException, RestServiceException { when(mockSynapse.getMyStorageLocationSetting(anyLong())).thenThrow(new Exception()); synapseClient.createStorageLocationSetting(entityId, new ExternalStorageLocationSetting()); } @Test public void testUpdateTeamAcl() throws SynapseException, RestServiceException { AccessControlList returnedAcl = synapseClient.updateTeamAcl(acl); verify(mockSynapse).updateTeamACL(acl); assertEquals(acl, returnedAcl); } @Test public void testGetTeamAcl() throws SynapseException, RestServiceException { String teamId = "14"; AccessControlList returnedAcl = synapseClient.getTeamAcl(teamId); verify(mockSynapse).getTeamACL(teamId); assertEquals(acl, returnedAcl); } private void setupVersionedEntityBundle(String entityId, Long latestVersionNumber) throws SynapseException { EntityBundle eb = new EntityBundle(); Entity file = new FileEntity(); eb.setEntity(file); eb.getEntity().setId(entityId); when(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb); when(mockSynapse.getEntityBundle(anyString(), anyLong(), anyInt())).thenReturn(eb); PaginatedResults<VersionInfo> versionInfoPaginatedResults = new PaginatedResults<VersionInfo>(); List<VersionInfo> versionInfoList = new LinkedList<VersionInfo>(); VersionInfo versionInfo = new VersionInfo(); versionInfo.setVersionNumber(latestVersionNumber); versionInfoList.add(versionInfo); versionInfoPaginatedResults.setResults(versionInfoList); when(mockSynapse.getEntityVersions(anyString(), anyInt(), anyInt())).thenReturn(versionInfoPaginatedResults); when(mockSynapse.getEntityById(anyString())).thenReturn(file); } @Test public void testGetEntityBundlePlusForVersionVersionable() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = 1L; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), eq(targetVersionNumber), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForNullVersionVersionable() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = null; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForVersionLatestVersion() throws RestServiceException, SynapseException { String entityId = "syn123"; Long targetVersionNumber = 2L; Long latestVersionNumber = 2L; setupVersionedEntityBundle(entityId, latestVersionNumber); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion(entityId, targetVersionNumber, 1); assertEquals(returnedEntityBundle.getLatestVersionNumber(), latestVersionNumber); verify(mockSynapse).getEntityBundle(anyString(), anyInt()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), entityId); } @Test public void testGetEntityBundlePlusForVersionNonVersionable() throws RestServiceException, SynapseException { EntityBundle eb = new EntityBundle(); eb.setEntity(new Folder()); eb.getEntity().setId("syn123"); when(mockSynapse.getEntityBundle(anyString(), anyInt())).thenReturn(eb); EntityBundlePlus returnedEntityBundle = synapseClient.getEntityBundlePlusForVersion("syn123", 123L, 1); assertNull(returnedEntityBundle.getLatestVersionNumber()); assertEquals(returnedEntityBundle.getEntityBundle().getEntity().getId(), "syn123"); } @Test public void testGetUserIdFromUsername() throws UnsupportedEncodingException, SynapseException, RestServiceException { //find the user id based on user name Long targetUserId = 4L; when(mockPrincipalAliasResponse.getPrincipalId()).thenReturn(targetUserId); when(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenReturn(mockPrincipalAliasResponse); String userId = synapseClient.getUserIdFromUsername("luke"); assertEquals(targetUserId.toString(), userId); } @Test(expected = BadRequestException.class) public void testGetUserIdFromUsernameBackendError() throws UnsupportedEncodingException, SynapseException, RestServiceException { //test error from backend when(mockSynapse.getPrincipalAlias(any(PrincipalAliasRequest.class))).thenThrow(new SynapseBadRequestException()); synapseClient.getUserIdFromUsername("bad-request"); } @Test public void testGetTableUpdateTransactionRequestNoChange() throws RestServiceException, SynapseException { String tableId = "syn93939"; List<ColumnModel> oldColumnModels = Collections.singletonList(mockOldColumnModel); when(mockSynapse.createColumnModels(anyList())).thenReturn(oldColumnModels); when(mockSynapse.getColumnModelsForTableEntity(tableId)).thenReturn(oldColumnModels); assertEquals(0, synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, oldColumnModels).getChanges().size()); } @Test public void testGetTableUpdateTransactionRequestNewColumn() throws RestServiceException, SynapseException { String tableId = "syn93939"; List<ColumnModel> oldColumnModels = new ArrayList<ColumnModel>(); when(mockSynapse.createColumnModels(anyList())).thenReturn(Collections.singletonList(mockNewColumnModelAfterCreate)); List<ColumnModel> newColumnModels = Collections.singletonList(mockNewColumnModel); TableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldColumnModels, newColumnModels); verify(mockSynapse).createColumnModels(anyList()); assertEquals(tableId, request.getEntityId()); List<TableUpdateRequest> tableUpdates = request.getChanges(); assertEquals(1, tableUpdates.size()); TableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0); List<ColumnChange> changes = schemaChange.getChanges(); assertEquals(1, changes.size()); ColumnChange columnChange = changes.get(0); assertNull(columnChange.getOldColumnId()); assertEquals(NEW_COLUMN_MODEL_ID, columnChange.getNewColumnId()); } private ColumnModel getColumnModel(String id, ColumnType columnType) { ColumnModel cm = new ColumnModel(); cm.setId(id); cm.setColumnType(columnType); return cm; } private ColumnChange getColumnChange(String oldColumnId, List<ColumnChange> changes) { for (ColumnChange columnChange : changes) { if (Objects.equal(oldColumnId, columnChange.getOldColumnId())) { return columnChange; } } throw new NoSuchElementException(); } @Test public void testGetTableUpdateTransactionRequestFullTest() throws RestServiceException, SynapseException { //In this test, we will change a column, delete a column, and add a column (with appropriately mocked responses) // Modify colA, delete colB, no change to colC, and add colD ColumnModel colA, colB, colC, colD, colAModified, colAAfterSave, colDAfterSave; String tableId = "syn93939"; colA = getColumnModel("1", ColumnType.STRING); colB = getColumnModel("2", ColumnType.STRING); colC = getColumnModel("3", ColumnType.STRING); colD = getColumnModel(null, ColumnType.STRING); colAModified = getColumnModel("1", ColumnType.INTEGER); colAAfterSave = getColumnModel("4", ColumnType.INTEGER); colDAfterSave = getColumnModel("5", ColumnType.STRING); List<ColumnModel> oldSchema = Arrays.asList(colA, colB, colC); List<ColumnModel> proposedNewSchema = Arrays.asList(colAModified, colC, colD); List<ColumnModel> newSchemaAfterUpdate = Arrays.asList(colAAfterSave, colC, colDAfterSave); when(mockSynapse.createColumnModels(anyList())).thenReturn(newSchemaAfterUpdate); TableUpdateTransactionRequest request = synapseClient.getTableUpdateTransactionRequest(tableId, oldSchema, proposedNewSchema); verify(mockSynapse).createColumnModels(anyList()); assertEquals(tableId, request.getEntityId()); List<TableUpdateRequest> tableUpdates = request.getChanges(); assertEquals(1, tableUpdates.size()); TableSchemaChangeRequest schemaChange = (TableSchemaChangeRequest)tableUpdates.get(0); //changes should consist of a create, an update, and a delete List<ColumnChange> changes = schemaChange.getChanges(); assertEquals(3, changes.size()); // colB should be deleted ColumnChange columnChange = getColumnChange("2", changes); assertNull(columnChange.getNewColumnId()); // colA should be modified columnChange = getColumnChange("1", changes); assertEquals("4", columnChange.getNewColumnId()); // colD should be new columnChange = getColumnChange(null, changes); assertEquals("5", columnChange.getNewColumnId()); } @Test public void testGetDefaultColumnsForView() throws RestServiceException, SynapseException{ ColumnModel colA, colB; colA = getColumnModel("1", ColumnType.STRING); colB = getColumnModel("2", ColumnType.STRING); List<ColumnModel> defaultColumns = Arrays.asList(colA, colB); when(mockSynapse.getDefaultColumnsForView(any(ViewType.class))).thenReturn(defaultColumns); List<ColumnModel> returnedColumns = synapseClient.getDefaultColumnsForView(ViewType.file); assertEquals(2, returnedColumns.size()); assertNull(returnedColumns.get(0).getId()); assertNull(returnedColumns.get(1).getId()); } }
test updateFileEntity with a file entity and file handle copy request
src/test/java/org/sagebionetworks/web/unitserver/SynapseClientImplTest.java
test updateFileEntity with a file entity and file handle copy request
Java
apache-2.0
7ed9583ef706f5b7940dc524c1f77edeaf608351
0
statsbiblioteket/doms-ingesters,statsbiblioteket/doms-ingesters
/* * $Id$ * $Revision$ * $Date$ * $Author$ * * The DOMS project. * Copyright (C) 2007-2010 The State and University Library * * 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 dk.statsbiblioteket.doms.ingesters.radiotv; import dk.statsbiblioteket.doms.client.DomsWSClient; import dk.statsbiblioteket.doms.client.DomsWSClientImpl; import dk.statsbiblioteket.doms.client.exceptions.NoObjectFound; import dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed; import dk.statsbiblioteket.doms.client.exceptions.XMLParseException; import dk.statsbiblioteket.doms.client.relations.LiteralRelation; import dk.statsbiblioteket.doms.client.relations.Relation; import dk.statsbiblioteket.doms.client.utils.FileInfo; import dk.statsbiblioteket.util.xml.DOM; import dk.statsbiblioteket.util.xml.XPathSelector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.validation.Schema; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** On added xml files with radio/tv metadata, add objects to DOMS describing these files. */ public class RadioTVMetadataProcessor implements HotFolderScannerClient { private static final String RITZAU_ORIGINALS_ELEMENT = "//program/originals/ritzau_original"; private static final String GALLUP_ORIGINALS_ELEMENT = "//program/originals/gallup_original"; private static final String HAS_METAFILE_RELATION_TYPE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#hasShard"; private static final String CONSISTS_OF_RELATION_TYPE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#consistsOf"; private static final String RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT = "//program/pbcore/pbc:PBCoreDescriptionDocument"; private static final String RECORDING_FILES_FILE_ELEMENT = "//program/program_recording_files/file"; private static final String FILE_URL_ELEMENT = "file_url"; private static final String FILE_NAME_ELEMENT = "file_name"; private static final String FORMAT_URI_ELEMENT = "format_uri"; private static final String MD5_SUM_ELEMENT = "md5_sum"; private static final String PROGRAM_TEMPLATE_PID = "doms:Template_Program"; private static final String PROGRAM_PBCORE_DS_ID = "PBCORE"; private static final String RITZAU_ORIGINAL_DS_ID = "RITZAU_ORIGINAL"; private static final String GALLUP_ORIGINAL_DS_ID = "GALLUP_ORIGINAL"; private static final String META_FILE_TEMPLATE_PID = "doms:Template_Shard"; private static final String META_FILE_METADATA_DS_ID = "SHARD_METADATA"; private static final String RADIO_TV_FILE_TEMPLATE_PID = "doms:Template_RadioTVFile"; private static final int MAX_FAIL_COUNT = 10; private static final XPathSelector XPATH_SELECTOR = DOM .createXPathSelector("pbc", "http://www.pbcore.org/PBCore/PBCoreNamespace.html"); private static final String COMMENT = "Ingest of Radio/TV data"; private static final String FAILED_COMMENT = COMMENT + ": Something failed, rolling back"; private int exceptionCount = 0; /** Folder to move failed files to. */ private final File failedFilesFolder; /** Folder to move processed files to. */ private final File processedFilesFolder; /** Document builder that fails on XML files not conforming to the preingest schema. */ private final DocumentBuilder preingestFilesBuilder; /** Document builder that does not require a specific schema. */ private final DocumentBuilder unSchemaedBuilder; /** Client for communicating with DOMS. */ private final DomsWSClient domsClient; /** * Initialise the processor. * * @param domsLoginInfo Information used for contacting DOMS. * @param failedFilesFolder Folder to move failed files to. * @param processedFilesFolder Folder to move processed files to. * @param preIngestFileSchema Schema for Raio/TV metadata to process. */ public RadioTVMetadataProcessor(DOMSLoginInfo domsLoginInfo, File failedFilesFolder, File processedFilesFolder, Schema preIngestFileSchema) { this.failedFilesFolder = failedFilesFolder; this.processedFilesFolder = processedFilesFolder; this.domsClient = new DomsWSClientImpl(); this.domsClient.setCredentials(domsLoginInfo.getDomsWSAPIUrl(), domsLoginInfo.getLogin(), domsLoginInfo.getPassword()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory unschemaedFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setSchema(preIngestFileSchema); documentBuilderFactory.setNamespaceAware(true); try { preingestFilesBuilder = documentBuilderFactory.newDocumentBuilder(); unSchemaedBuilder = unschemaedFactory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); fatalException(); throw new RuntimeException();// will never be reached, but no matter } ErrorHandler documentErrorHandler = new org.xml.sax.ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }; preingestFilesBuilder.setErrorHandler(documentErrorHandler); } /** * Will parse the metadata and add relevant objects to DOMS. * @param addedFile Full path to the new file. */ @Override public void fileAdded(File addedFile) { List<String> pidsToPublish = new ArrayList<String>(); //This method acts as fault barrier try { Document radioTVMetadata = preingestFilesBuilder.parse(addedFile); createRecord(radioTVMetadata, addedFile, pidsToPublish); } catch (Exception e) { // Handle anything unanticipated. failed(addedFile, pidsToPublish); e.printStackTrace(); incrementFailedTries(); } } @Override public void fileDeleted(File deletedFile) { // Not relevant. } /** * Acts exactly as fileAdded. * @param modifiedFile Full path to the modified file. */ @Override public void fileModified(File modifiedFile) { fileAdded(modifiedFile); } /** * Create objects in DOMS for given program metadata. On success, the originating file will be moved to the folder * for processed files. On failure, a file in the folder of failed files will contain the pids that were not * published. * * @param radioTVMetadata The Metadata for the program. * @param addedFile The file containing the program metadata * @param pidsToPublish Initially empty list of pids to update with pids collected during process, to be published * in the end. * * @throws IOException On io trouble communicating. * @throws ServerOperationFailed On trouble updating DOMS. * @throws URISyntaxException Should never happen. Means shard URI generated is invalid. * @throws XPathExpressionException Should never happen. Means program is broken with wrong XPath exception. * @throws XMLParseException On trouble parsing XML. */ private void createRecord(Document radioTVMetadata, File addedFile, List<String> pidsToPublish) throws IOException, ServerOperationFailed, URISyntaxException, XPathExpressionException, XMLParseException { // Check if program is already in DOMS String originalPid; try { originalPid = alreadyExistsInRepo(radioTVMetadata); } catch (NoObjectFound noObjectFound) { originalPid = null; } // Find or create files containing this program // TODO: Fill out metadata for file List<String> filePIDs = ingestFiles(radioTVMetadata); pidsToPublish.addAll(filePIDs); writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Create or update shard for this program // TODO: Fill out datastreams in program instead String shardPid = null; if (originalPid != null) { //program already exists shardPid = getShardPidFromProgram(originalPid); } String metaFilePID = ingestMetaFile(radioTVMetadata, filePIDs, shardPid); pidsToPublish.add(metaFilePID); writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Create or update program object for this program // TODO: May require some updates? String programPID = ingestProgram(radioTVMetadata, metaFilePID, originalPid); pidsToPublish.add(programPID); File allWrittenPIDs = writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Publish the objects created in the process domsClient.publishObjects(COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()])); // The ingest was successful, if we make it here... // Move the processed file to the finished files folder. moveFile(addedFile, processedFilesFolder); // And it is now safe to delete the "in progress" PID file. allWrittenPIDs.delete(); } /** * Lookup a program in DOMS. * If program exists, returns the PID of the program. Otherwise throws exception {@link NoObjectFound}. * * @param radioTVMetadata The document containing the program metadata. * @return PID of program, if found. * * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath. * @throws ServerOperationFailed Could not communicate with DOMS. * @throws NoObjectFound The program was not found in DOMS. */ private String alreadyExistsInRepo(Document radioTVMetadata) throws XPathExpressionException, ServerOperationFailed, NoObjectFound { String oldId = getOldIdentifier(radioTVMetadata); List<String> pids = domsClient.getPidFromOldIdentifier(oldId); if (!pids.isEmpty()) { return pids.get(0); } throw new NoObjectFound("No object found"); } /** * Find old identifier in program metadata, and use them for looking up programs in DOMS. * * @param radioTVMetadata The document containing the program metadata. * @return Old indentifier found. * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath. */ private String getOldIdentifier(Document radioTVMetadata) throws XPathExpressionException { // TODO Should support TVMeter identifiers as well, and return a list! Node radioTVPBCoreElement = XPATH_SELECTOR .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT); Node oldPIDNode = XPATH_SELECTOR .selectNode(radioTVPBCoreElement, "pbc:pbcoreIdentifier[pbc:identifierSource=\"id\"]/pbc:identifier"); if (oldPIDNode != null && !oldPIDNode.getTextContent().isEmpty()) { return oldPIDNode.getTextContent(); } else { return null; } } /** * queries the list of relations in the program, and extracts the shard-pid from these * * @param pid the program object pid * @return the shard pid, or null if none found * * @throws ServerOperationFailed if something failed */ private String getShardPidFromProgram(String pid) throws ServerOperationFailed { List<Relation> shardrelations = domsClient.listObjectRelations(pid, HAS_METAFILE_RELATION_TYPE); return shardrelations.size() > 0 ? shardrelations.get(0).getSubjectPid() : null; } /** * Iteratively (over)write the pid the <code>InProcessPIDs</code> file * associated with the <code>preIngestFile</code>. * * @param outputDirectory absolute path to the directory where the PID file must be * written. * @param preIngestFile The file containing the Metadata for a program. * @param PIDs A list of PIDs to write. * @return The <code>File</code> which the PIDs were written to. * * @throws IOException thrown if the file cannot be written to. */ private File writePIDs(File outputDirectory, File preIngestFile, List<String> PIDs) throws IOException { final File pidFile = new File(outputDirectory, preIngestFile.getName() + ".InProcessPIDs"); if (!pidFile.exists()) { pidFile.createNewFile(); } if (pidFile.canWrite()) { final PrintWriter writer = new PrintWriter(pidFile); for (String currentPID : PIDs) { writer.println(currentPID); } writer.flush(); writer.close(); return pidFile; } else { throw new IOException("Cannot write file " + pidFile.getAbsolutePath()); } } /** * Move the failed pre-ingest file to the "failedFilesFolder" folder and * rename the in-progress PID list file to a failed PID list file, also * stored in the "failedFilesFolder" folder. * <p/> * This method should be called before "pulling the plug". * * @param addedFile The file attempted to have added to the doms * @param pidsToPublish The failed PIDs */ private void failed(File addedFile, List<String> pidsToPublish) { try { moveFile(addedFile, failedFilesFolder); // Rename the in-progress PIDs to failed PIDs. writeFailedPIDs(addedFile); domsClient.deleteObjects(FAILED_COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()])); } catch (Exception exception) { // If this bail-out error handling fails, then nothing can save // us... exception.printStackTrace(System.err); } } /** * Ingests or update a program object * * * @param radioTVMetadata Bibliographical metadata about the program. * @param metafilePID PID to the metafile which represents the program data. * @param existingPid the existing pid of the program object, or null if it does not exist * @return PID of the newly created program object, created by the DOMS. * * @throws ServerOperationFailed if creation or manipulation of the program object fails. * @throws XPathExpressionException should never happen. Means error in program with invalid XPath. * @throws XMLParseException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. */ private String ingestProgram(Document radioTVMetadata, String metafilePID, String existingPid) throws ServerOperationFailed, XPathExpressionException, XMLParseException { // First, fetch the PBCore metadata document node from the pre-ingest // document. Node radioTVPBCoreElement = XPATH_SELECTOR .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT); // Extract the ritzauID from the pre-ingest file. List<String> listOfOldPIDs = new ArrayList<String>(); String oldId = getOldIdentifier(radioTVMetadata); if (oldId != null) { listOfOldPIDs.add(oldId); } String programObjectPID; if (existingPid == null) {//not Exist // Create a program object in the DOMS and update the PBCore metadata // datastream with the PBCore metadata from the pre-ingest file. programObjectPID = domsClient.createObjectFromTemplate(PROGRAM_TEMPLATE_PID, listOfOldPIDs, COMMENT); // Create relations to the metafile/shard domsClient.addObjectRelation(programObjectPID, HAS_METAFILE_RELATION_TYPE, metafilePID, COMMENT); } else { //Exists domsClient.unpublishObjects(COMMENT, existingPid); programObjectPID = existingPid; } final Document pbCoreDataStreamDocument = createPBCoreDocForDoms(radioTVPBCoreElement); domsClient.updateDataStream(programObjectPID, PROGRAM_PBCORE_DS_ID, pbCoreDataStreamDocument, COMMENT); // Get the program title from the PBCore metadata and use that as the // object label for this program object. Node titleNode = XPATH_SELECTOR .selectNode(radioTVPBCoreElement, "pbc:pbcoreTitle[pbc:titleType=\"titel\"]/pbc:title"); final String programTitle = titleNode.getTextContent(); domsClient.setObjectLabel(programObjectPID, programTitle, COMMENT); // Get the Ritzau metadata from the pre-ingest document and add it to // the Ritzau metadata data stream of the program object. final Document ritzauOriginalDocument = createRitzauDocument(radioTVMetadata); domsClient.updateDataStream(programObjectPID, RITZAU_ORIGINAL_DS_ID, ritzauOriginalDocument, COMMENT); // Add the Gallup metadata Document gallupOriginalDocument = createGallupDocument(radioTVMetadata); domsClient.updateDataStream(programObjectPID, GALLUP_ORIGINAL_DS_ID, gallupOriginalDocument, COMMENT); return programObjectPID; } /** * Utility method to create the Ritzau document to ingest * * @param radioTVMetadata Bibliographical metadata about the program. * @return A document containing the Ritzau metadata. */ private Document createRitzauDocument(Document radioTVMetadata) { final Node ritzauPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, RITZAU_ORIGINALS_ELEMENT); // Build a Ritzau data document for the Ritzau data stream in the // program object. final Document ritzauOriginalDocument = unSchemaedBuilder.newDocument(); final Element ritzauOriginalRootElement = ritzauOriginalDocument.createElement("ritzau_original"); ritzauOriginalRootElement.setAttribute("xmlns", "http://doms.statsbiblioteket.dk/types/ritzau_original/0/1/#"); ritzauOriginalDocument.appendChild(ritzauOriginalRootElement); ritzauOriginalRootElement.setTextContent(ritzauPreingestElement.getTextContent()); return ritzauOriginalDocument; } /** * Utility method to create the Gallup document to ingest * * @param radioTVMetadata Bibliographical metadata about the program. * @return A document containing the Gallup metadata */ private Document createGallupDocument(Node radioTVMetadata) { final Node gallupPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, GALLUP_ORIGINALS_ELEMENT); final Document gallupOriginalDocument = unSchemaedBuilder.newDocument(); final Element gallupOriginalRootElement = gallupOriginalDocument.createElement("gallup_original"); gallupOriginalRootElement.setAttribute("xmlns", "http://doms.statsbiblioteket.dk/types/gallup_original/0/1/#"); gallupOriginalRootElement.setTextContent(gallupPreingestElement.getTextContent()); gallupOriginalDocument.appendChild(gallupOriginalRootElement); return gallupOriginalDocument; } /** * Utility method to create the PBCore document to ingest * * @param radioTVPBCoreElement Element containing PBCore. * @return A document containing the PBCore metadata */ private Document createPBCoreDocForDoms(Node radioTVPBCoreElement) { final Document pbCoreDataStreamDocument = unSchemaedBuilder.newDocument(); // Import the PBCore metadata from the pre-ingest document and use it as // the contents for the PBCore metadata data stream of the program // object. final Node newPBCoreElement = pbCoreDataStreamDocument.importNode(radioTVPBCoreElement, true); pbCoreDataStreamDocument.appendChild(newPBCoreElement); return pbCoreDataStreamDocument; } /** * Ingest a metafile (aka. shard) object which represents the program data * (i.e. video and/or audio). A metafile may consist of data chunks from * multiple physical files identified by the PIDs in the * <code>filePIDs</code> list. The metadata provided by * <code>radioTVMetadata</code> contains, among other things, information * about location and duration of the chunks of data from the physical files * which constitutes the contents of the metafile. * <p/> * TODO: Consider cleaning up/consolidating the exceptions * * @param radioTVMetadata Metadata about location and duration of the relevant data * chunks from the physical files. * @param filePIDs List of PIDs for the physical files containing the data * represented by this metafile. * @param metaFilePID The PID of the object, if it exists already. Otherwise null * @return PID of the newly created metafile object, created by the DOMS. * * @throws ServerOperationFailed if creation or manipulation of the metafile object fails. * @throws IOException if io exceptions occur while communicating. * @throws XPathExpressionException should never happen. Means error in program with invalid XPath. * @throws URISyntaxException if shard URL could not be generated * @throws XMLParseException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. */ private String ingestMetaFile(Document radioTVMetadata, List<String> filePIDs, String metaFilePID) throws ServerOperationFailed, IOException, XPathExpressionException, URISyntaxException, XMLParseException { if (metaFilePID == null) { // Create a file object from the file object template. metaFilePID = domsClient.createObjectFromTemplate(META_FILE_TEMPLATE_PID, COMMENT); // TODO: Do something about this. final FileInfo fileInfo = new FileInfo("shard/" + metaFilePID, new URL("http://www.statsbiblioteket.dk/doms/shard/" + metaFilePID), "", new URI("info:pronom/fmt/199")); domsClient.addFileToFileObject(metaFilePID, fileInfo, COMMENT); } else { domsClient.unpublishObjects(COMMENT, metaFilePID); } final Document metadataDataStreamDocument = unSchemaedBuilder.newDocument(); final Element metadataDataStreamRootElement = metadataDataStreamDocument.createElement("shard_metadata"); metadataDataStreamDocument.appendChild(metadataDataStreamRootElement); // Add all the "file" elements from the radio-tv metadata document. // TODO: Note that this is just a first-shot implementation until a // proper metadata format has been defined. final NodeList recordingFileElements = XPATH_SELECTOR .selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT); for (int fileElementIdx = 0; fileElementIdx < recordingFileElements.getLength(); fileElementIdx++) { final Node currentRecordingFile = recordingFileElements.item(fileElementIdx); // Append to the end of the list of child nodes. final Node newMetadataElement = metadataDataStreamDocument.importNode(currentRecordingFile, true); metadataDataStreamRootElement.appendChild(newMetadataElement); } domsClient.updateDataStream(metaFilePID, META_FILE_METADATA_DS_ID, metadataDataStreamDocument, COMMENT); List<Relation> relations = domsClient.listObjectRelations(metaFilePID, CONSISTS_OF_RELATION_TYPE); HashSet<String> existingRels = new HashSet<String>(); for (Relation relation : relations) { if (!filePIDs.contains(relation.getSubjectPid())) { domsClient.removeObjectRelation((LiteralRelation) relation, COMMENT); } else { existingRels.add(relation.getSubjectPid()); } } for (String filePID : filePIDs) { if (!existingRels.contains(filePID)) { domsClient.addObjectRelation(metaFilePID, CONSISTS_OF_RELATION_TYPE, filePID, COMMENT); } } return metaFilePID; } /** * Ingest any missing file objects into the DOMS and return a list of PIDs * for all the DOMS file objects corresponding to the files listed in the * <code>radioTVMetadata</code> document. * * @param radioTVMetadata Metadata XML document containing the file information. * @return A <code>List</code> of PIDs of the radio-tv file objects created * by the DOMS. * * @throws XPathExpressionException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. * @throws MalformedURLException if a file element contains an invalid URL. * @throws ServerOperationFailed if creation and retrieval of a radio-tv file object fails. * @throws URISyntaxException if the format URI for the file is invalid. */ private List<String> ingestFiles(Document radioTVMetadata) throws XPathExpressionException, MalformedURLException, ServerOperationFailed, URISyntaxException { // Get the recording files XML element and process the file information. final NodeList recordingFiles = XPATH_SELECTOR.selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT); // Ensure that the DOMS contains a file object for each recording file // element in the radio-tv XML document. final List<String> fileObjectPIDs = new ArrayList<String>(); for (int nodeIndex = 0; nodeIndex < recordingFiles.getLength(); nodeIndex++) { final Node currentFileNode = recordingFiles.item(nodeIndex); final Node fileURLNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_URL_ELEMENT); final String fileURLString = fileURLNode.getTextContent(); final URL fileURL = new URL(fileURLString); String fileObjectPID; try { fileObjectPID = domsClient.getFileObjectPID(fileURL); } catch (NoObjectFound nof) { // The DOMS contains no file object for this file URL. // Create a new one now. final Node fileNameNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_NAME_ELEMENT); final String fileName = fileNameNode.getTextContent(); final Node formatURINode = XPATH_SELECTOR.selectNode(currentFileNode, FORMAT_URI_ELEMENT); final URI formatURI = new URI(formatURINode.getTextContent()); final Node md5SumNode = XPATH_SELECTOR.selectNode(currentFileNode, MD5_SUM_ELEMENT); // The MD5 check sum is optional. Just leave it empty if the // pre-ingest file does not provide it. String md5String = ""; if (md5SumNode != null) { md5String = md5SumNode.getTextContent(); } final FileInfo fileInfo = new FileInfo(fileName, fileURL, md5String, formatURI); fileObjectPID = domsClient.createFileObject(RADIO_TV_FILE_TEMPLATE_PID, fileInfo, COMMENT); } fileObjectPIDs.add(fileObjectPID); } return fileObjectPIDs; } /** * Move <code>fileToMove</code> to the folder specified by * <code>destinationFolder</code>. * * @param fileToMove Path to the file to move to <code>destinationFolder</code>. * @param destinationFolder Path of the destination folder to move the file to. */ private void moveFile(File fileToMove, File destinationFolder) { fileToMove.renameTo(new File(destinationFolder.getAbsolutePath(), fileToMove.getName())); } /** * Rename the file with a list of PIDs in progress and never published to a file with a list of failed PIDs. * @param failedMetadataFile The originating file. * */ private void writeFailedPIDs(File failedMetadataFile) { final File activePIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + ".InProcessPIDs"); final File failedPIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + ".failedPIDs"); activePIDsFile.renameTo(failedPIDsFile); } /** * ends all attempts to ingest from the current list of file descriptions in * the pre-ingest file Violent exit needed "system.exit() */ private void fatalException() { System.exit(-1); } /** The number of tries is incremented by one. * If this exceeds the maximum number of allowed failures, */ private void incrementFailedTries() { exceptionCount += 1; if (exceptionCount >= MAX_FAIL_COUNT) { System.err.println("Too many errors (" + exceptionCount + ") in ingest. Exiting."); fatalException(); } } }
radio-tv/src/main/java/dk/statsbiblioteket/doms/ingesters/radiotv/RadioTVMetadataProcessor.java
/* * $Id$ * $Revision$ * $Date$ * $Author$ * * The DOMS project. * Copyright (C) 2007-2010 The State and University Library * * 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 dk.statsbiblioteket.doms.ingesters.radiotv; import dk.statsbiblioteket.doms.client.DomsWSClient; import dk.statsbiblioteket.doms.client.DomsWSClientImpl; import dk.statsbiblioteket.doms.client.exceptions.NoObjectFound; import dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed; import dk.statsbiblioteket.doms.client.exceptions.XMLParseException; import dk.statsbiblioteket.doms.client.relations.LiteralRelation; import dk.statsbiblioteket.doms.client.relations.Relation; import dk.statsbiblioteket.doms.client.utils.FileInfo; import dk.statsbiblioteket.util.xml.DOM; import dk.statsbiblioteket.util.xml.XPathSelector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.validation.Schema; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** On added xml files with radio/tv metadata, add objects to DOMS describing these files. */ public class RadioTVMetadataProcessor implements HotFolderScannerClient { private static final String RITZAU_ORIGINALS_ELEMENT = "//program/originals/ritzau_original"; private static final String GALLUP_ORIGINALS_ELEMENT = "//program/originals/gallup_original"; private static final String HAS_METAFILE_RELATION_TYPE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#hasShard"; private static final String CONSISTS_OF_RELATION_TYPE = "http://doms.statsbiblioteket.dk/relations/default/0/1/#consistsOf"; private static final String RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT = "//program/pbcore/pbc:PBCoreDescriptionDocument"; private static final String RECORDING_FILES_FILE_ELEMENT = "//program/program_recording_files/file"; private static final String FILE_URL_ELEMENT = "file_url"; private static final String FILE_NAME_ELEMENT = "file_name"; private static final String FORMAT_URI_ELEMENT = "format_uri"; private static final String MD5_SUM_ELEMENT = "md5_sum"; private static final String PROGRAM_TEMPLATE_PID = "doms:Template_Program"; private static final String PROGRAM_PBCORE_DS_ID = "PBCORE"; private static final String RITZAU_ORIGINAL_DS_ID = "RITZAU_ORIGINAL"; private static final String GALLUP_ORIGINAL_DS_ID = "GALLUP_ORIGINAL"; private static final String META_FILE_TEMPLATE_PID = "doms:Template_Shard"; private static final String META_FILE_METADATA_DS_ID = "SHARD_METADATA"; private static final String RADIO_TV_FILE_TEMPLATE_PID = "doms:Template_RadioTVFile"; private static final int MAX_FAIL_COUNT = 3; private static final XPathSelector XPATH_SELECTOR = DOM .createXPathSelector("pbc", "http://www.pbcore.org/PBCore/PBCoreNamespace.html"); private static final String COMMENT = "Ingest of Radio/TV data"; private static final String FAILED_COMMENT = COMMENT + ": Something failed, rolling back"; private int exceptionCount = 0; /** Folder to move failed files to. */ private final File failedFilesFolder; /** Folder to move processed files to. */ private final File processedFilesFolder; /** Document builder that fails on XML files not conforming to the preingest schema. */ private final DocumentBuilder preingestFilesBuilder; /** Document builder that does not require a specific schema. */ private final DocumentBuilder unSchemaedBuilder; /** Client for communicating with DOMS. */ private final DomsWSClient domsClient; /** * Initialise the processor. * * @param domsLoginInfo Information used for contacting DOMS. * @param failedFilesFolder Folder to move failed files to. * @param processedFilesFolder Folder to move processed files to. * @param preIngestFileSchema Schema for Raio/TV metadata to process. */ public RadioTVMetadataProcessor(DOMSLoginInfo domsLoginInfo, File failedFilesFolder, File processedFilesFolder, Schema preIngestFileSchema) { this.failedFilesFolder = failedFilesFolder; this.processedFilesFolder = processedFilesFolder; this.domsClient = new DomsWSClientImpl(); this.domsClient.setCredentials(domsLoginInfo.getDomsWSAPIUrl(), domsLoginInfo.getLogin(), domsLoginInfo.getPassword()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory unschemaedFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setSchema(preIngestFileSchema); documentBuilderFactory.setNamespaceAware(true); try { preingestFilesBuilder = documentBuilderFactory.newDocumentBuilder(); unSchemaedBuilder = unschemaedFactory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); fatalException(); throw new RuntimeException();// will never be reached, but no matter } ErrorHandler documentErrorHandler = new org.xml.sax.ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }; preingestFilesBuilder.setErrorHandler(documentErrorHandler); } /** * Will parse the metadata and add relevant objects to DOMS. * @param addedFile Full path to the new file. */ @Override public void fileAdded(File addedFile) { List<String> pidsToPublish = new ArrayList<String>(); //This method acts as fault barrier try { Document radioTVMetadata = preingestFilesBuilder.parse(addedFile); createRecord(radioTVMetadata, addedFile, pidsToPublish); } catch (Exception e) { // Handle anything unanticipated. failed(addedFile, pidsToPublish); e.printStackTrace(); incrementFailedTries(); } } @Override public void fileDeleted(File deletedFile) { // Not relevant. } /** * Acts exactly as fileAdded. * @param modifiedFile Full path to the modified file. */ @Override public void fileModified(File modifiedFile) { fileAdded(modifiedFile); } /** * Create objects in DOMS for given program metadata. On success, the originating file will be moved to the folder * for processed files. On failure, a file in the folder of failed files will contain the pids that were not * published. * * @param radioTVMetadata The Metadata for the program. * @param addedFile The file containing the program metadata * @param pidsToPublish Initially empty list of pids to update with pids collected during process, to be published * in the end. * * @throws IOException On io trouble communicating. * @throws ServerOperationFailed On trouble updating DOMS. * @throws URISyntaxException Should never happen. Means shard URI generated is invalid. * @throws XPathExpressionException Should never happen. Means program is broken with wrong XPath exception. * @throws XMLParseException On trouble parsing XML. */ private void createRecord(Document radioTVMetadata, File addedFile, List<String> pidsToPublish) throws IOException, ServerOperationFailed, URISyntaxException, XPathExpressionException, XMLParseException { // Check if program is already in DOMS String originalPid; try { originalPid = alreadyExistsInRepo(radioTVMetadata); } catch (NoObjectFound noObjectFound) { originalPid = null; } // Find or create files containing this program // TODO: Fill out metadata for file List<String> filePIDs = ingestFiles(radioTVMetadata); pidsToPublish.addAll(filePIDs); writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Create or update shard for this program // TODO: Fill out datastreams in program instead String shardPid = null; if (originalPid != null) { //program already exists shardPid = getShardPidFromProgram(originalPid); } String metaFilePID = ingestMetaFile(radioTVMetadata, filePIDs, shardPid); pidsToPublish.add(metaFilePID); writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Create or update program object for this program // TODO: May require some updates? String programPID = ingestProgram(radioTVMetadata, metaFilePID, originalPid); pidsToPublish.add(programPID); File allWrittenPIDs = writePIDs(failedFilesFolder, addedFile, pidsToPublish); // Publish the objects created in the process domsClient.publishObjects(COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()])); // The ingest was successful, if we make it here... // Move the processed file to the finished files folder. moveFile(addedFile, processedFilesFolder); // And it is now safe to delete the "in progress" PID file. allWrittenPIDs.delete(); } /** * Lookup a program in DOMS. * If program exists, returns the PID of the program. Otherwise throws exception {@link NoObjectFound}. * * @param radioTVMetadata The document containing the program metadata. * @return PID of program, if found. * * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath. * @throws ServerOperationFailed Could not communicate with DOMS. * @throws NoObjectFound The program was not found in DOMS. */ private String alreadyExistsInRepo(Document radioTVMetadata) throws XPathExpressionException, ServerOperationFailed, NoObjectFound { String oldId = getOldIdentifier(radioTVMetadata); List<String> pids = domsClient.getPidFromOldIdentifier(oldId); if (!pids.isEmpty()) { return pids.get(0); } throw new NoObjectFound("No object found"); } /** * Find old identifier in program metadata, and use them for looking up programs in DOMS. * * @param radioTVMetadata The document containing the program metadata. * @return Old indentifier found. * @throws XPathExpressionException Should never happen. Means program is broken with faulty XPath. */ private String getOldIdentifier(Document radioTVMetadata) throws XPathExpressionException { // TODO Should support TVMeter identifiers as well, and return a list! Node radioTVPBCoreElement = XPATH_SELECTOR .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT); Node oldPIDNode = XPATH_SELECTOR .selectNode(radioTVPBCoreElement, "pbc:pbcoreIdentifier[pbc:identifierSource=\"id\"]/pbc:identifier"); if (oldPIDNode != null && !oldPIDNode.getTextContent().isEmpty()) { return oldPIDNode.getTextContent(); } else { return null; } } /** * queries the list of relations in the program, and extracts the shard-pid from these * * @param pid the program object pid * @return the shard pid, or null if none found * * @throws ServerOperationFailed if something failed */ private String getShardPidFromProgram(String pid) throws ServerOperationFailed { List<Relation> shardrelations = domsClient.listObjectRelations(pid, HAS_METAFILE_RELATION_TYPE); return shardrelations.size() > 0 ? shardrelations.get(0).getSubjectPid() : null; } /** * Iteratively (over)write the pid the <code>InProcessPIDs</code> file * associated with the <code>preIngestFile</code>. * * @param outputDirectory absolute path to the directory where the PID file must be * written. * @param preIngestFile The file containing the Metadata for a program. * @param PIDs A list of PIDs to write. * @return The <code>File</code> which the PIDs were written to. * * @throws IOException thrown if the file cannot be written to. */ private File writePIDs(File outputDirectory, File preIngestFile, List<String> PIDs) throws IOException { final File pidFile = new File(outputDirectory, preIngestFile.getName() + ".InProcessPIDs"); if (!pidFile.exists()) { pidFile.createNewFile(); } if (pidFile.canWrite()) { final PrintWriter writer = new PrintWriter(pidFile); for (String currentPID : PIDs) { writer.println(currentPID); } writer.flush(); writer.close(); return pidFile; } else { throw new IOException("Cannot write file " + pidFile.getAbsolutePath()); } } /** * Move the failed pre-ingest file to the "failedFilesFolder" folder and * rename the in-progress PID list file to a failed PID list file, also * stored in the "failedFilesFolder" folder. * <p/> * This method should be called before "pulling the plug". * * @param addedFile The file attempted to have added to the doms * @param pidsToPublish The failed PIDs */ private void failed(File addedFile, List<String> pidsToPublish) { try { moveFile(addedFile, failedFilesFolder); // Rename the in-progress PIDs to failed PIDs. writeFailedPIDs(addedFile); domsClient.deleteObjects(FAILED_COMMENT, pidsToPublish.toArray(new String[pidsToPublish.size()])); } catch (Exception exception) { // If this bail-out error handling fails, then nothing can save // us... exception.printStackTrace(System.err); } } /** * Ingests or update a program object * * * @param radioTVMetadata Bibliographical metadata about the program. * @param metafilePID PID to the metafile which represents the program data. * @param existingPid the existing pid of the program object, or null if it does not exist * @return PID of the newly created program object, created by the DOMS. * * @throws ServerOperationFailed if creation or manipulation of the program object fails. * @throws XPathExpressionException should never happen. Means error in program with invalid XPath. * @throws XMLParseException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. */ private String ingestProgram(Document radioTVMetadata, String metafilePID, String existingPid) throws ServerOperationFailed, XPathExpressionException, XMLParseException { // First, fetch the PBCore metadata document node from the pre-ingest // document. Node radioTVPBCoreElement = XPATH_SELECTOR .selectNode(radioTVMetadata, RECORDING_PBCORE_DESCRIPTION_DOCUMENT_ELEMENT); // Extract the ritzauID from the pre-ingest file. List<String> listOfOldPIDs = new ArrayList<String>(); String oldId = getOldIdentifier(radioTVMetadata); if (oldId != null) { listOfOldPIDs.add(oldId); } String programObjectPID; if (existingPid == null) {//not Exist // Create a program object in the DOMS and update the PBCore metadata // datastream with the PBCore metadata from the pre-ingest file. programObjectPID = domsClient.createObjectFromTemplate(PROGRAM_TEMPLATE_PID, listOfOldPIDs, COMMENT); // Create relations to the metafile/shard domsClient.addObjectRelation(programObjectPID, HAS_METAFILE_RELATION_TYPE, metafilePID, COMMENT); } else { //Exists domsClient.unpublishObjects(COMMENT, existingPid); programObjectPID = existingPid; } final Document pbCoreDataStreamDocument = createPBCoreDocForDoms(radioTVPBCoreElement); domsClient.updateDataStream(programObjectPID, PROGRAM_PBCORE_DS_ID, pbCoreDataStreamDocument, COMMENT); // Get the program title from the PBCore metadata and use that as the // object label for this program object. Node titleNode = XPATH_SELECTOR .selectNode(radioTVPBCoreElement, "pbc:pbcoreTitle[pbc:titleType=\"titel\"]/pbc:title"); final String programTitle = titleNode.getTextContent(); domsClient.setObjectLabel(programObjectPID, programTitle, COMMENT); // Get the Ritzau metadata from the pre-ingest document and add it to // the Ritzau metadata data stream of the program object. final Document ritzauOriginalDocument = createRitzauDocument(radioTVMetadata); domsClient.updateDataStream(programObjectPID, RITZAU_ORIGINAL_DS_ID, ritzauOriginalDocument, COMMENT); // Add the Gallup metadata Document gallupOriginalDocument = createGallupDocument(radioTVMetadata); domsClient.updateDataStream(programObjectPID, GALLUP_ORIGINAL_DS_ID, gallupOriginalDocument, COMMENT); return programObjectPID; } /** * Utility method to create the Ritzau document to ingest * * @param radioTVMetadata Bibliographical metadata about the program. * @return A document containing the Ritzau metadata. */ private Document createRitzauDocument(Document radioTVMetadata) { final Node ritzauPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, RITZAU_ORIGINALS_ELEMENT); // Build a Ritzau data document for the Ritzau data stream in the // program object. final Document ritzauOriginalDocument = unSchemaedBuilder.newDocument(); final Element ritzauOriginalRootElement = ritzauOriginalDocument.createElement("ritzau_original"); ritzauOriginalRootElement.setAttribute("xmlns", "http://doms.statsbiblioteket.dk/types/ritzau_original/0/1/#"); ritzauOriginalDocument.appendChild(ritzauOriginalRootElement); ritzauOriginalRootElement.setTextContent(ritzauPreingestElement.getTextContent()); return ritzauOriginalDocument; } /** * Utility method to create the Gallup document to ingest * * @param radioTVMetadata Bibliographical metadata about the program. * @return A document containing the Gallup metadata */ private Document createGallupDocument(Node radioTVMetadata) { final Node gallupPreingestElement = XPATH_SELECTOR.selectNode(radioTVMetadata, GALLUP_ORIGINALS_ELEMENT); final Document gallupOriginalDocument = unSchemaedBuilder.newDocument(); final Element gallupOriginalRootElement = gallupOriginalDocument.createElement("gallup_original"); gallupOriginalRootElement.setAttribute("xmlns", "http://doms.statsbiblioteket.dk/types/gallup_original/0/1/#"); gallupOriginalRootElement.setTextContent(gallupPreingestElement.getTextContent()); gallupOriginalDocument.appendChild(gallupOriginalRootElement); return gallupOriginalDocument; } /** * Utility method to create the PBCore document to ingest * * @param radioTVPBCoreElement Element containing PBCore. * @return A document containing the PBCore metadata */ private Document createPBCoreDocForDoms(Node radioTVPBCoreElement) { final Document pbCoreDataStreamDocument = unSchemaedBuilder.newDocument(); // Import the PBCore metadata from the pre-ingest document and use it as // the contents for the PBCore metadata data stream of the program // object. final Node newPBCoreElement = pbCoreDataStreamDocument.importNode(radioTVPBCoreElement, true); pbCoreDataStreamDocument.appendChild(newPBCoreElement); return pbCoreDataStreamDocument; } /** * Ingest a metafile (aka. shard) object which represents the program data * (i.e. video and/or audio). A metafile may consist of data chunks from * multiple physical files identified by the PIDs in the * <code>filePIDs</code> list. The metadata provided by * <code>radioTVMetadata</code> contains, among other things, information * about location and duration of the chunks of data from the physical files * which constitutes the contents of the metafile. * <p/> * TODO: Consider cleaning up/consolidating the exceptions * * @param radioTVMetadata Metadata about location and duration of the relevant data * chunks from the physical files. * @param filePIDs List of PIDs for the physical files containing the data * represented by this metafile. * @param metaFilePID The PID of the object, if it exists already. Otherwise null * @return PID of the newly created metafile object, created by the DOMS. * * @throws ServerOperationFailed if creation or manipulation of the metafile object fails. * @throws IOException if io exceptions occur while communicating. * @throws XPathExpressionException should never happen. Means error in program with invalid XPath. * @throws URISyntaxException if shard URL could not be generated * @throws XMLParseException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. */ private String ingestMetaFile(Document radioTVMetadata, List<String> filePIDs, String metaFilePID) throws ServerOperationFailed, IOException, XPathExpressionException, URISyntaxException, XMLParseException { if (metaFilePID == null) { // Create a file object from the file object template. metaFilePID = domsClient.createObjectFromTemplate(META_FILE_TEMPLATE_PID, COMMENT); // TODO: Do something about this. final FileInfo fileInfo = new FileInfo("shard/" + metaFilePID, new URL("http://www.statsbiblioteket.dk/doms/shard/" + metaFilePID), "", new URI("info:pronom/fmt/199")); domsClient.addFileToFileObject(metaFilePID, fileInfo, COMMENT); } else { domsClient.unpublishObjects(COMMENT, metaFilePID); } final Document metadataDataStreamDocument = unSchemaedBuilder.newDocument(); final Element metadataDataStreamRootElement = metadataDataStreamDocument.createElement("shard_metadata"); metadataDataStreamDocument.appendChild(metadataDataStreamRootElement); // Add all the "file" elements from the radio-tv metadata document. // TODO: Note that this is just a first-shot implementation until a // proper metadata format has been defined. final NodeList recordingFileElements = XPATH_SELECTOR .selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT); for (int fileElementIdx = 0; fileElementIdx < recordingFileElements.getLength(); fileElementIdx++) { final Node currentRecordingFile = recordingFileElements.item(fileElementIdx); // Append to the end of the list of child nodes. final Node newMetadataElement = metadataDataStreamDocument.importNode(currentRecordingFile, true); metadataDataStreamRootElement.appendChild(newMetadataElement); } domsClient.updateDataStream(metaFilePID, META_FILE_METADATA_DS_ID, metadataDataStreamDocument, COMMENT); List<Relation> relations = domsClient.listObjectRelations(metaFilePID, CONSISTS_OF_RELATION_TYPE); HashSet<String> existingRels = new HashSet<String>(); for (Relation relation : relations) { if (!filePIDs.contains(relation.getSubjectPid())) { domsClient.removeObjectRelation((LiteralRelation) relation, COMMENT); } else { existingRels.add(relation.getSubjectPid()); } } for (String filePID : filePIDs) { if (!existingRels.contains(filePID)) { domsClient.addObjectRelation(metaFilePID, CONSISTS_OF_RELATION_TYPE, filePID, COMMENT); } } return metaFilePID; } /** * Ingest any missing file objects into the DOMS and return a list of PIDs * for all the DOMS file objects corresponding to the files listed in the * <code>radioTVMetadata</code> document. * * @param radioTVMetadata Metadata XML document containing the file information. * @return A <code>List</code> of PIDs of the radio-tv file objects created * by the DOMS. * * @throws XPathExpressionException if any errors were encountered while processing the * <code>radioTVMetadata</code> XML document. * @throws MalformedURLException if a file element contains an invalid URL. * @throws ServerOperationFailed if creation and retrieval of a radio-tv file object fails. * @throws URISyntaxException if the format URI for the file is invalid. */ private List<String> ingestFiles(Document radioTVMetadata) throws XPathExpressionException, MalformedURLException, ServerOperationFailed, URISyntaxException { // Get the recording files XML element and process the file information. final NodeList recordingFiles = XPATH_SELECTOR.selectNodeList(radioTVMetadata, RECORDING_FILES_FILE_ELEMENT); // Ensure that the DOMS contains a file object for each recording file // element in the radio-tv XML document. final List<String> fileObjectPIDs = new ArrayList<String>(); for (int nodeIndex = 0; nodeIndex < recordingFiles.getLength(); nodeIndex++) { final Node currentFileNode = recordingFiles.item(nodeIndex); final Node fileURLNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_URL_ELEMENT); final String fileURLString = fileURLNode.getTextContent(); final URL fileURL = new URL(fileURLString); String fileObjectPID; try { fileObjectPID = domsClient.getFileObjectPID(fileURL); } catch (NoObjectFound nof) { // The DOMS contains no file object for this file URL. // Create a new one now. final Node fileNameNode = XPATH_SELECTOR.selectNode(currentFileNode, FILE_NAME_ELEMENT); final String fileName = fileNameNode.getTextContent(); final Node formatURINode = XPATH_SELECTOR.selectNode(currentFileNode, FORMAT_URI_ELEMENT); final URI formatURI = new URI(formatURINode.getTextContent()); final Node md5SumNode = XPATH_SELECTOR.selectNode(currentFileNode, MD5_SUM_ELEMENT); // The MD5 check sum is optional. Just leave it empty if the // pre-ingest file does not provide it. String md5String = ""; if (md5SumNode != null) { md5String = md5SumNode.getTextContent(); } final FileInfo fileInfo = new FileInfo(fileName, fileURL, md5String, formatURI); fileObjectPID = domsClient.createFileObject(RADIO_TV_FILE_TEMPLATE_PID, fileInfo, COMMENT); } fileObjectPIDs.add(fileObjectPID); } return fileObjectPIDs; } /** * Move <code>fileToMove</code> to the folder specified by * <code>destinationFolder</code>. * * @param fileToMove Path to the file to move to <code>destinationFolder</code>. * @param destinationFolder Path of the destination folder to move the file to. */ private void moveFile(File fileToMove, File destinationFolder) { fileToMove.renameTo(new File(destinationFolder.getAbsolutePath(), fileToMove.getName())); } /** * Rename the file with a list of PIDs in progress and never published to a file with a list of failed PIDs. * @param failedMetadataFile The originating file. * */ private void writeFailedPIDs(File failedMetadataFile) { final File activePIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + ".InProcessPIDs"); final File failedPIDsFile = new File(failedFilesFolder, failedMetadataFile.getName() + ".failedPIDs"); activePIDsFile.renameTo(failedPIDsFile); } /** * ends all attempts to ingest from the current list of file descriptions in * the pre-ingest file Violent exit needed "system.exit() */ private void fatalException() { System.exit(-1); } /** The number of tries is incremented by one. * If this exceeds the maximum number of allowed failures, */ private void incrementFailedTries() { exceptionCount += 1; if (exceptionCount >= MAX_FAIL_COUNT) { System.err.println("Too many errors (" + exceptionCount + ") in ingest. Exiting."); fatalException(); } } }
Increased allowed number of failures during ingest
radio-tv/src/main/java/dk/statsbiblioteket/doms/ingesters/radiotv/RadioTVMetadataProcessor.java
Increased allowed number of failures during ingest
Java
apache-2.0
fffdcc380d44af3e763d989c8567c2a52d530da0
0
PavelGirkalo/java_pft,PavelGirkalo/java_pft
package ru.stqa.pft.addressbook.generators; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.XStream; import ru.stqa.pft.addressbook.model.ContactData; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class ContactDataGenetator { @Parameter(names = "-c", description = "Contact count") public int count; @Parameter(names = "-f", description = "Target contact file") public String file; @Parameter(names = "-d", description = "Data format") public String format; public static void main(String[] args) throws IOException { ContactDataGenetator genetator = new ContactDataGenetator(); JCommander jCommander = new JCommander(genetator); try { jCommander.parse(args); } catch (ParameterException ex) { jCommander.usage(); return; } genetator.run(); } private void run() throws IOException { List<ContactData> contacts = generateContacts(count); if (format.equals("csv")) { saveAsCsv(contacts, new File(file)); } else if (format.equals("xml")) { saveAsXml(contacts, new File(file)); } else if (format.equals("json")) { saveAsJson(contacts, new File(file)); } else { System.out.println("Unrecognized format " + format); } } private void saveAsJson(List<ContactData> contacts, File file) throws IOException { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); String json = gson.toJson(contacts); Writer writer = new FileWriter(file); writer.write(json); writer.close(); } private void saveAsXml(List<ContactData> contacts, File file) throws IOException { XStream xstream = new XStream(); xstream.processAnnotations(ContactData.class); //xstream.alias("group", GroupData.class); String xml = xstream.toXML(contacts); Writer writer = new FileWriter(file); writer.write(xml); writer.close(); } private void saveAsCsv(List<ContactData> contacts, File file) throws IOException { System.out.println(new File(".").getAbsolutePath()); Writer writer = new FileWriter(file); for (ContactData contact : contacts) { writer.write(String.format("%s;%s;%s;%s;%s\n", contact.getFirstname(), contact.getLastname(), contact.getAddress(), contact.getEmail(), contact.getMobile())); } writer.close(); } private List<ContactData> generateContacts(int count) { List<ContactData> contacts = new ArrayList<ContactData>(); for (int i = 0; i <count; i++) { contacts.add(new ContactData().withFirstname((String.format("First %s", i))) .withLastname(String.format("Last %s", i)).withAddress(String.format("Address %s", i)) .withEmail(String.format("Email%[email protected]", i)).withMobile(String.format("+7901000%s", i))); } return contacts; } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/generators/ContactDataGenetator.java
package ru.stqa.pft.addressbook.generators; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.XStream; import ru.stqa.pft.addressbook.model.ContactData; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class ContactDataGenetator { @Parameter(names = "-cc", description = "Contact count") public int count; @Parameter(names = "-cf", description = "Target contact file") public String file; @Parameter(names = "-d", description = "Data format") public String format; public static void main(String[] args) throws IOException { ContactDataGenetator genetator = new ContactDataGenetator(); JCommander jCommander = new JCommander(genetator); try { jCommander.parse(args); } catch (ParameterException ex) { jCommander.usage(); return; } genetator.run(); } private void run() throws IOException { List<ContactData> contacts = generateContacts(count); if (format.equals("csv")) { saveAsCsv(contacts, new File(file)); } else if (format.equals("xml")) { saveAsXml(contacts, new File(file)); } else if (format.equals("json")) { saveAsJson(contacts, new File(file)); } else { System.out.println("Unrecognized format " + format); } } private void saveAsJson(List<ContactData> contacts, File file) throws IOException { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); String json = gson.toJson(contacts); Writer writer = new FileWriter(file); writer.write(json); writer.close(); } private void saveAsXml(List<ContactData> contacts, File file) throws IOException { XStream xstream = new XStream(); xstream.processAnnotations(ContactData.class); //xstream.alias("group", GroupData.class); String xml = xstream.toXML(contacts); Writer writer = new FileWriter(file); writer.write(xml); writer.close(); } private void saveAsCsv(List<ContactData> contacts, File file) throws IOException { System.out.println(new File(".").getAbsolutePath()); Writer writer = new FileWriter(file); for (ContactData contact : contacts) { writer.write(String.format("%s;%s;%s;%s;%s\n", contact.getFirstname(), contact.getLastname(), contact.getAddress(), contact.getEmail(), contact.getMobile())); } writer.close(); } private List<ContactData> generateContacts(int count) { List<ContactData> contacts = new ArrayList<ContactData>(); for (int i = 0; i <count; i++) { contacts.add(new ContactData().withFirstname((String.format("First %s", i))) .withLastname(String.format("Last %s", i)).withAddress(String.format("Address %s", i)) .withEmail(String.format("Email%[email protected]", i)).withMobile(String.format("+7901000%s", i))); } return contacts; } }
Рефакторинг генератора контактов
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/generators/ContactDataGenetator.java
Рефакторинг генератора контактов
Java
apache-2.0
1b82f4df76f111ee94e102e083a33be2505d753f
0
rodriguezdevera/sakai,liubo404/sakai,whumph/sakai,lorenamgUMU/sakai,liubo404/sakai,bkirschn/sakai,kingmook/sakai,hackbuteer59/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,joserabal/sakai,rodriguezdevera/sakai,puramshetty/sakai,clhedrick/sakai,colczr/sakai,zqian/sakai,hackbuteer59/sakai,liubo404/sakai,ouit0408/sakai,zqian/sakai,kwedoff1/sakai,frasese/sakai,puramshetty/sakai,hackbuteer59/sakai,zqian/sakai,clhedrick/sakai,Fudan-University/sakai,kingmook/sakai,introp-software/sakai,wfuedu/sakai,whumph/sakai,lorenamgUMU/sakai,willkara/sakai,whumph/sakai,kwedoff1/sakai,introp-software/sakai,ktakacs/sakai,frasese/sakai,bzhouduke123/sakai,bzhouduke123/sakai,kwedoff1/sakai,bkirschn/sakai,ouit0408/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,hackbuteer59/sakai,bzhouduke123/sakai,Fudan-University/sakai,whumph/sakai,bkirschn/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,wfuedu/sakai,kwedoff1/sakai,OpenCollabZA/sakai,conder/sakai,liubo404/sakai,wfuedu/sakai,whumph/sakai,udayg/sakai,frasese/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,kingmook/sakai,lorenamgUMU/sakai,bkirschn/sakai,lorenamgUMU/sakai,frasese/sakai,introp-software/sakai,surya-janani/sakai,udayg/sakai,noondaysun/sakai,pushyamig/sakai,rodriguezdevera/sakai,introp-software/sakai,ouit0408/sakai,kingmook/sakai,buckett/sakai-gitflow,surya-janani/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,puramshetty/sakai,conder/sakai,introp-software/sakai,clhedrick/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,ktakacs/sakai,willkara/sakai,buckett/sakai-gitflow,joserabal/sakai,kingmook/sakai,pushyamig/sakai,joserabal/sakai,frasese/sakai,pushyamig/sakai,lorenamgUMU/sakai,noondaysun/sakai,colczr/sakai,clhedrick/sakai,puramshetty/sakai,udayg/sakai,udayg/sakai,introp-software/sakai,joserabal/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,joserabal/sakai,zqian/sakai,noondaysun/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,bkirschn/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,wfuedu/sakai,udayg/sakai,bzhouduke123/sakai,joserabal/sakai,ktakacs/sakai,bkirschn/sakai,colczr/sakai,ktakacs/sakai,willkara/sakai,puramshetty/sakai,hackbuteer59/sakai,pushyamig/sakai,hackbuteer59/sakai,zqian/sakai,kingmook/sakai,whumph/sakai,joserabal/sakai,clhedrick/sakai,bkirschn/sakai,Fudan-University/sakai,conder/sakai,Fudan-University/sakai,OpenCollabZA/sakai,introp-software/sakai,kingmook/sakai,willkara/sakai,introp-software/sakai,surya-janani/sakai,buckett/sakai-gitflow,noondaysun/sakai,conder/sakai,bzhouduke123/sakai,puramshetty/sakai,ouit0408/sakai,udayg/sakai,frasese/sakai,pushyamig/sakai,ouit0408/sakai,hackbuteer59/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,frasese/sakai,hackbuteer59/sakai,Fudan-University/sakai,liubo404/sakai,zqian/sakai,frasese/sakai,Fudan-University/sakai,ktakacs/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,noondaysun/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,kwedoff1/sakai,lorenamgUMU/sakai,noondaysun/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,willkara/sakai,liubo404/sakai,ktakacs/sakai,udayg/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,colczr/sakai,surya-janani/sakai,OpenCollabZA/sakai,surya-janani/sakai,clhedrick/sakai,zqian/sakai,clhedrick/sakai,conder/sakai,wfuedu/sakai,ouit0408/sakai,wfuedu/sakai,pushyamig/sakai,whumph/sakai,zqian/sakai,noondaysun/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,OpenCollabZA/sakai,conder/sakai,surya-janani/sakai,puramshetty/sakai,colczr/sakai,wfuedu/sakai,liubo404/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,bkirschn/sakai,joserabal/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,wfuedu/sakai,conder/sakai,kwedoff1/sakai,colczr/sakai,willkara/sakai,ktakacs/sakai,colczr/sakai,udayg/sakai,kwedoff1/sakai,willkara/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,conder/sakai,whumph/sakai,clhedrick/sakai,OpenCollabZA/sakai
package org.sakaiproject.tool.assessment.ui.bean.print; import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.io.StringReader; import java.io.Reader; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.ResourceBundle; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAnswer; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemText; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.pdf.HTMLWorker; import com.lowagie.text.html.simpleparser.StyleSheet; import com.lowagie.text.PageSize; import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean; import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean; import org.sakaiproject.tool.assessment.ui.bean.delivery.MatchingBean; import org.sakaiproject.tool.assessment.ui.bean.print.settings.PrintSettingsBean; import org.sakaiproject.tool.assessment.ui.listener.delivery.BeginDeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.util.FormattedText; import org.sakaiproject.component.cover.ServerConfigurationService; /** * * @author Joshua Ryan <a href="mailto:[email protected]">[email protected]</a> * * This class is basically just a conveinceince class for abstracting the creation of * PDF's from assessments * */ public class PDFAssessmentBean implements Serializable { private static final long serialVersionUID = 1L; private static Log log = LogFactory.getLog(PDFAssessmentBean.class); private static ResourceBundle printMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.PrintMessages"); private static ResourceBundle authorMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.AuthorMessages"); private static ResourceBundle commonMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.CommonMessages"); private String intro = ""; private String title = ""; private ArrayList parts = null; private ArrayList deliveryParts = null; private int baseFontSize = 5; private String actionString = ""; public PDFAssessmentBean() { if (log.isInfoEnabled()) log.info("Starting PDFAssessementBean with session scope"); } /** * Gets the pdf assessments intro * @return assessment intor in html */ public String getIntro() { return intro; } /** * sets the pdf assessments intro * @param intro in html */ public void setIntro(String intro) { this.intro = FormattedText.unEscapeHtml(intro); } /** * gets the delivery bean parts of the assessment * @return */ public ArrayList getDeliveryParts() { return deliveryParts; } /** * gets the parts of the assessment * @return */ public ArrayList getParts() { return parts; } /** * gets what should be the full set of html chunks for an assessment * @return */ public ArrayList getHtmlChunks() { return parts; } /** * sets the delivery parts * @param deliveryParts */ public void setDeliveryParts(ArrayList deliveryParts) { ArrayList parts = new ArrayList(); int numberQuestion = 1; for (int i=0; i<deliveryParts.size(); i++) { SectionContentsBean section = new SectionContentsBean((org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean)deliveryParts.get(i)); ArrayList items = section.getItemContents(); // Renumbering for (int j=0; items != null && j<items.size(); j++) { ItemContentsBean itemContents = (ItemContentsBean)items.get(j); itemContents.setNumber(numberQuestion++); // Order answers in order (A, B, C, D) ArrayList question = itemContents.getItemData().getItemTextArraySorted(); for (int k=0; k<question.size(); k++) { PublishedItemText itemtext = (PublishedItemText)question.get(k); ArrayList answers = itemtext.getAnswerArray(); for (int t=0; t<answers.size(); t++) { PublishedAnswer answer = (PublishedAnswer)answers.get(t); if (answer.getLabel() != null && !answer.getLabel().equals("")) answer.setSequence(new Long(answer.getLabel().charAt(0) - 64)); } } } parts.add(section); } this.deliveryParts = parts; } /** /** * sets the parts * @param parts */ public void setParts(ArrayList parts) { this.parts = parts; } /** * gets the Title * @return */ public String getTitle() { return title; } /** * sets the Title * @param title */ public void setTitle(String title) { this.title = title; } /** * generates the pdf file name * @return pdf file name */ public String genName() { //There has got to be a cleaner way to get a good time stamp in java? Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); String fTitle = FormattedText.convertFormattedTextToPlaintext(title); int end = Math.min(fTitle.length(), 9); if (log.isWarnEnabled()) log.warn(fTitle.substring(0, end) + year + month + day + hour + min + sec + ".pdf"); return (fTitle.substring(0, end) + year + month + day + hour + min + sec + ".pdf").replace(" ", "_"); } public String prepPDF() { DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery"); deliveryBean.setActionString("previewAssessment"); setActionString(ContextUtil.lookupParam("actionString")); // Call all the listeners needed to populate the deliveryBean... BeginDeliveryActionListener beginDeliveryAL = new BeginDeliveryActionListener(); DeliveryActionListener deliveryAL = new DeliveryActionListener(); beginDeliveryAL.processAction(null); deliveryAL.processAction(null); setDeliveryParts(deliveryBean.getTableOfContents().getPartsContents()); prepDocumentPDF(); return "print"; } public String prepDocumentPDF() { DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery"); PrintSettingsBean printSetting = (PrintSettingsBean) ContextUtil.lookupBean("printSettings"); if (printSetting.getShowPartIntros().booleanValue() && deliveryBean.getInstructorMessage() != null) setIntro(deliveryBean.getInstructorMessage()); ArrayList pdfParts = new ArrayList(); //for each part in an assessment we add a pdfPart to the pdfBean for (int i = 0; i < deliveryParts.size(); i++) { //get the current item SectionContentsBean section = (SectionContentsBean) deliveryParts.get(i); ArrayList items = section.getItemContents(); ArrayList resources = new ArrayList(); //create a new part and empty list to fill with items PDFPartBean pdfPart = new PDFPartBean(); pdfPart.setSectionId(section.getSectionId()); if (printSetting.getShowPartIntros().booleanValue() && deliveryParts.size() > 1) pdfPart.setIntro("<h2>" + authorMessages.getString("p") + " " + (i+1) + ": " + section.getTitle() + "</h2>"); ArrayList pdfItems = new ArrayList(); //for each item in a section we add a blank pdfItem to the pdfPart for (int j = 0; j < items.size(); j++) { PDFItemBean pdfItem = new PDFItemBean(); ItemContentsBean item = (ItemContentsBean) items.get(j); String legacy = "<h3>" + item.getNumber() +"</h3>"; pdfItem.setItemId(item.getItemData().getItemId()); String content = "<br />" + item.getItemData().getText() + "<br />"; if (item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING)) { content += printMessages.getString("time_allowed_seconds") + ": " + item.getItemData().getDuration(); content += "<br />" + printMessages.getString("number_of_tries") + ": " + item.getItemData().getTriesAllowed(); content += "<br />"; } if (item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += printMessages.getString("upload_instruction") + "<br />"; content += printMessages.getString("file") + ": "; content += "<input type='text' size='50' />"; content += "<input type='button' value='" + printMessages.getString("browse") + ":' />"; content += "<input type='button' value='" + printMessages.getString("upload") + ":' />"; content += "<br />"; } if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) { ArrayList question = item.getItemData().getItemTextArraySorted(); for (int k=0; k<question.size(); k++) { PublishedItemText itemtext = (PublishedItemText)question.get(k); ArrayList answers = itemtext.getAnswerArraySorted(); content += "<table cols='20' width='100%'>"; for (int t=0; t<answers.size(); t++) { PublishedAnswer answer = (PublishedAnswer)answers.get(t); if (answer.getText() == null) break; content += "<tr>" + getContentAnswer(item, answer, printSetting) + "</tr>"; } content += "</table>"; } } if (item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) { content += "<table cols='20' width='100%'>"; ArrayList question = item.getMatchingArray(); for (int k=0; k<question.size(); k++) { MatchingBean matching = (MatchingBean)question.get(k); String answer = (String)item.getAnswers().get(k); if (matching.getText() == null) break; content += "<tr><td colspan='10'>"; content += matching.getText(); content += "</td>"; content += "<td colspan='10'>"; content += answer + "</td></tr>"; } content += "</table>"; } if (printSetting.getShowKeys().booleanValue() || printSetting.getShowKeysFeedback().booleanValue()) { content += "<br />" + getContentQuestion(item, printSetting); } pdfItem.setContent(content); if (legacy != null) { pdfItem.setMeta(legacy); } pdfItems.add(pdfItem); } pdfPart.setQuestions(pdfItems); pdfPart.setResources(resources); if (resources.size() > 0) pdfPart.setHasResources(new Boolean(true)); pdfParts.add(pdfPart); } //set the new colleciton of PDF beans to be the contents of the pdfassessment setParts(pdfParts); setTitle(deliveryBean.getAssessmentTitle()); return "print"; } private String getContentAnswer(ItemContentsBean item, PublishedAnswer answer, PrintSettingsBean printSetting) { String content = ""; if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) { if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)) content += "<td colspan='1'><img src='/samigo-app/images/unchecked.gif' /></td>"; else content += "<td colspan='1'><img src='/samigo-app/images/radiounchecked.gif' /></td>"; content += "<td colspan='10'>"; if (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)) content += answer.getLabel() + ". "; content += answer.getText(); content += "</td>"; content += "<td colspan='9'>"; if (printSetting.getShowKeysFeedback()) { content += "<h6>" + commonMessages.getString("feedback") + ": "; if (answer.getGeneralAnswerFeedback() != null && !answer.getGeneralAnswerFeedback().equals("")) content += answer.getGeneralAnswerFeedback(); else content += "--------"; content += "</h6>"; } content += "</td>"; } if (item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) { content += "<td colspan='1'><img src='/samigo-app/images/radiounchecked.gif' /></td>"; content += "<td colspan='19'>"; content += answer.getText(); content += "</td>"; } return content; } private String getContentQuestion(ItemContentsBean item, PrintSettingsBean printSetting) { String content = "<h6>"; content += printMessages.getString("answer_point") + ": " + item.getItemData().getScore(); content += " " + authorMessages.getString("points_lower_case"); if (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) && !item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) && !item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += "<br />"; if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) content += printMessages.getString("answer_model") + ": "; else content += printMessages.getString("answer_key") + ": "; if (item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) content += item.getKey(); else if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) { if (item.getKey() != null && !item.getKey().equals("")) content += item.getKey(); else content += "--------"; } else content += item.getItemData().getAnswerKey(); } if (printSetting.getShowKeysFeedback().booleanValue()) { if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) || item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += "<br />"; content += commonMessages.getString("feedback") + ": "; if (item.getItemData().getGeneralItemFeedback() != null && !item.getItemData().getGeneralItemFeedback().equals("")) content += item.getItemData().getGeneralItemFeedback(); else content += "--------"; } if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) { content += "<br />"; content += printMessages.getString("correct_feedback") + ": "; if (item.getItemData().getCorrectItemFeedback() != null && !item.getItemData().getCorrectItemFeedback().equals("")) content += item.getItemData().getCorrectItemFeedback(); else content += "--------"; content += "<br />" + printMessages.getString("incorrect_feedback") + ": "; if (item.getItemData().getInCorrectItemFeedback() != null && !item.getItemData().getInCorrectItemFeedback().equals("")) content += item.getItemData().getInCorrectItemFeedback(); else content += "--------"; } } return content + "</h6>"; } public void getPDFAttachment() { prepDocumentPDF(); ByteArrayOutputStream pdf = getStream(); FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse(); response.reset(); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0"); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + genName()); response.setContentLength(pdf.toByteArray().length); OutputStream out = null; try { out = response.getOutputStream(); out.write(pdf.toByteArray()); out.flush(); } catch (IOException e) { log.error(e); e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { log.error(e); e.printStackTrace(); } } faces.responseComplete(); } /** * Converts all nice new school html into old school * font tagged up html that HTMLWorker will actually * parse right * * @param input */ private String oldschoolIfy(String input) { if (log.isDebugEnabled()) log.debug("starting oldschoolify with: " + input); input = input.replaceAll("<h1", "<div><font color='#01a5cb' size='" + (int)(baseFontSize * 1.1) + "'"); input = input.replaceAll("<h2", "<div><font color='#01a5cb' size='" + (int)(baseFontSize * 1.1) + "'"); input = input.replaceAll("<h3", "<div><font color='#CCCCCC' size='" + (int)(baseFontSize * 1) + "'"); input = input.replaceAll("<h4", "<div><font size='" + (int)(baseFontSize * .85) + "'"); input = input.replaceAll("<h5", "<div><font size='" + (int)(baseFontSize * .8) + "'"); input = input.replaceAll("<h6", "<div><font color='#333333' size='" + (int)(baseFontSize * .6) + "'"); input = input.replaceAll("</h.>", "</font></div>"); return input; } /** * Turns a string into a StringReader with out the fuss of an IOException * * @param input * @return StringReader */ private Reader safeReader(String input) { StringReader output = null; if (input == null) { input = ""; } else { input = oldschoolIfy(input); } try { output = new StringReader(input + "<br/>"); } catch(Exception e) { log.error("could not get StringReader for String " + input + " due to : " + e); } return output; } public ByteArrayOutputStream getStream() { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { if (log.isInfoEnabled()) log.info("starting PDF generation" ); Document document = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter docWriter = PdfWriter.getInstance(document, output); document.open(); document.resetPageCount(); HTMLWorker worker = new HTMLWorker(document); HashMap props = worker.getInterfaceProps(); if (props == null) { props = new HashMap(); } float prevs = 0; props.put("img_baseurl", ServerConfigurationService.getServerUrl()); worker.setInterfaceProps(props); //TODO make a real style sheet StyleSheet style = null; String head = printMessages.getString("print_name_form"); head += "<br />"; head += printMessages.getString("print_score_form"); head += "<br /><br />"; head += "<h1>" + title + "</h1><br />"; head += intro + "<br />"; //head = head.replaceAll("[ \t\n\f\r]+", " "); //parse out the elements from the html ArrayList elementBuffer = HTMLWorker.parseToList(safeReader(head), style, props); float[] singleWidth = {1f}; PdfPTable single = new PdfPTable(singleWidth); single.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.setBorderWidth(0); for (int k = 0; k < elementBuffer.size(); k++) { cell.addElement((Element)elementBuffer.get(k)); } single.addCell(cell); prevs += single.getTotalHeight() % document.getPageSize().height(); //TODO do we want a new page here ... thus giving the cover page look? document.add(single); document.add(Chunk.NEWLINE); //extract the html and parse it into pdf ArrayList parts = getHtmlChunks(); for (int i = 0; i < parts.size(); i++) { //add new page to start each new part if (i > 0) { document.newPage(); } PDFPartBean pBean = (PDFPartBean) parts.get(i); if (pBean.getIntro() != null && !"".equals(pBean.getIntro())) { elementBuffer = HTMLWorker.parseToList(safeReader(pBean.getIntro()), style, props); single = new PdfPTable(singleWidth); single.setWidthPercentage(100f); cell = new PdfPCell(); cell.setBorderWidth(0); for (int k = 0; k < elementBuffer.size(); k++) { cell.addElement((Element)elementBuffer.get(k)); } single.addCell(cell); prevs += single.getTotalHeight() % document.getPageSize().height(); document.add(single); } ArrayList items = pBean.getQuestions(); for (int j = 0; j < items.size(); j++) { PDFItemBean iBean = (PDFItemBean) items.get(j); float[] widths = {0.1f, 0.9f}; PdfPTable table = new PdfPTable(widths); table.setWidthPercentage(100f); PdfPCell leftCell = new PdfPCell(); PdfPCell rightCell = new PdfPCell(); leftCell.setBorderWidth(0); leftCell.setPadding(0); leftCell.setLeading(0.00f, 0.00f); leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT); leftCell.setVerticalAlignment(Element.ALIGN_TOP); rightCell.setBorderWidth(0); elementBuffer = HTMLWorker.parseToList(safeReader(iBean.getMeta()), style, props); for (int k = 0; k < elementBuffer.size(); k++) { Element element = (Element)elementBuffer.get(k); if (element instanceof Paragraph) { Paragraph p = (Paragraph)element; p.getFont().setColor(Color.GRAY); p.setAlignment(Paragraph.ALIGN_CENTER); } leftCell.addElement(element); } table.addCell(leftCell); elementBuffer = HTMLWorker.parseToList(safeReader(iBean.getContent()), style, props); for (int k = 0; k < elementBuffer.size(); k++) { Element element = (Element)elementBuffer.get(k); rightCell.addElement(element); } table.addCell(rightCell); if (table.getTotalHeight() + prevs > document.getPageSize().height()) document.newPage(); document.add(table); document.add(Chunk.NEWLINE); //TODO add PDFTable and a collumn //worker.parse(safeReader(iBean.getMeta())); //TODO column break //worker.parse(safeReader(iBean.getContent())); //TODO end column and table } } document.close(); docWriter.close(); } catch(Exception e) { e.printStackTrace(); System.err.println("document: " + e.getMessage()); } return output; } public String getBaseFontSize() { return "" + baseFontSize; } public void setBaseFontSize(String baseFontSize) { this.baseFontSize = Integer.parseInt(baseFontSize); } /** * @return the actionString */ public String getActionString() { return actionString; } /** * @param actionString the actionString to set */ public void setActionString(String actionString) { this.actionString = actionString; } public String getSizeDeliveryParts() { return "" + deliveryParts.size(); } public String getTotalQuestions() { int items = 0; for (int i=0; i<deliveryParts.size(); i++) { SectionContentsBean section = (SectionContentsBean) deliveryParts.get(i); items += section.getItemContents().size(); } return "" + items; } }
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/print/PDFAssessmentBean.java
package org.sakaiproject.tool.assessment.ui.bean.print; import java.awt.Color; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.io.StringReader; import java.io.Reader; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.ResourceBundle; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAnswer; import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemText; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.pdf.HTMLWorker; import com.lowagie.text.html.simpleparser.StyleSheet; import com.lowagie.text.PageSize; import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean; import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean; import org.sakaiproject.tool.assessment.ui.bean.delivery.MatchingBean; import org.sakaiproject.tool.assessment.ui.bean.print.settings.PrintSettingsBean; import org.sakaiproject.tool.assessment.ui.listener.delivery.BeginDeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.delivery.DeliveryActionListener; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.util.FormattedText; import org.sakaiproject.component.cover.ServerConfigurationService; /** * * @author Joshua Ryan <a href="mailto:[email protected]">[email protected]</a> * * This class is basically just a conveinceince class for abstracting the creation of * PDF's from assessments * */ public class PDFAssessmentBean implements Serializable { private static final long serialVersionUID = 1L; private static Log log = LogFactory.getLog(PDFAssessmentBean.class); private static ResourceBundle printMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.PrintMessages"); private static ResourceBundle authorMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.AuthorMessages"); private String intro = ""; private String title = ""; private ArrayList parts = null; private ArrayList deliveryParts = null; private int baseFontSize = 5; private String actionString = ""; public PDFAssessmentBean() { if (log.isInfoEnabled()) log.info("Starting PDFAssessementBean with session scope"); } /** * Gets the pdf assessments intro * @return assessment intor in html */ public String getIntro() { return intro; } /** * sets the pdf assessments intro * @param intro in html */ public void setIntro(String intro) { this.intro = FormattedText.unEscapeHtml(intro); } /** * gets the delivery bean parts of the assessment * @return */ public ArrayList getDeliveryParts() { return deliveryParts; } /** * gets the parts of the assessment * @return */ public ArrayList getParts() { return parts; } /** * gets what should be the full set of html chunks for an assessment * @return */ public ArrayList getHtmlChunks() { return parts; } /** * sets the delivery parts * @param deliveryParts */ public void setDeliveryParts(ArrayList deliveryParts) { ArrayList parts = new ArrayList(); int numberQuestion = 1; for (int i=0; i<deliveryParts.size(); i++) { SectionContentsBean section = new SectionContentsBean((org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean)deliveryParts.get(i)); ArrayList items = section.getItemContents(); // Renumbering for (int j=0; items != null && j<items.size(); j++) { ItemContentsBean itemContents = (ItemContentsBean)items.get(j); itemContents.setNumber(numberQuestion++); // Order answers in order (A, B, C, D) ArrayList question = itemContents.getItemData().getItemTextArraySorted(); for (int k=0; k<question.size(); k++) { PublishedItemText itemtext = (PublishedItemText)question.get(k); ArrayList answers = itemtext.getAnswerArray(); for (int t=0; t<answers.size(); t++) { PublishedAnswer answer = (PublishedAnswer)answers.get(t); if (answer.getLabel() != null && !answer.getLabel().equals("")) answer.setSequence(new Long(answer.getLabel().charAt(0) - 64)); } } } parts.add(section); } this.deliveryParts = parts; } /** /** * sets the parts * @param parts */ public void setParts(ArrayList parts) { this.parts = parts; } /** * gets the Title * @return */ public String getTitle() { return title; } /** * sets the Title * @param title */ public void setTitle(String title) { this.title = title; } /** * generates the pdf file name * @return pdf file name */ public String genName() { //There has got to be a cleaner way to get a good time stamp in java? Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int min = cal.get(Calendar.MINUTE); int sec = cal.get(Calendar.SECOND); String fTitle = FormattedText.convertFormattedTextToPlaintext(title); int end = Math.min(fTitle.length(), 9); if (log.isWarnEnabled()) log.warn(fTitle.substring(0, end) + year + month + day + hour + min + sec + ".pdf"); return (fTitle.substring(0, end) + year + month + day + hour + min + sec + ".pdf").replace(" ", "_"); } public String prepPDF() { DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery"); deliveryBean.setActionString("previewAssessment"); setActionString(ContextUtil.lookupParam("actionString")); // Call all the listeners needed to populate the deliveryBean... BeginDeliveryActionListener beginDeliveryAL = new BeginDeliveryActionListener(); DeliveryActionListener deliveryAL = new DeliveryActionListener(); beginDeliveryAL.processAction(null); deliveryAL.processAction(null); setDeliveryParts(deliveryBean.getTableOfContents().getPartsContents()); prepDocumentPDF(); return "print"; } public String prepDocumentPDF() { DeliveryBean deliveryBean = (DeliveryBean) ContextUtil.lookupBean("delivery"); PrintSettingsBean printSetting = (PrintSettingsBean) ContextUtil.lookupBean("printSettings"); if (printSetting.getShowPartIntros().booleanValue() && deliveryBean.getInstructorMessage() != null) setIntro(deliveryBean.getInstructorMessage()); ArrayList pdfParts = new ArrayList(); //for each part in an assessment we add a pdfPart to the pdfBean for (int i = 0; i < deliveryParts.size(); i++) { //get the current item SectionContentsBean section = (SectionContentsBean) deliveryParts.get(i); ArrayList items = section.getItemContents(); ArrayList resources = new ArrayList(); //create a new part and empty list to fill with items PDFPartBean pdfPart = new PDFPartBean(); pdfPart.setSectionId(section.getSectionId()); if (printSetting.getShowPartIntros().booleanValue() && deliveryParts.size() > 1) pdfPart.setIntro("<h2>" + authorMessages.getString("p") + " " + (i+1) + ": " + section.getTitle() + "</h2>"); ArrayList pdfItems = new ArrayList(); //for each item in a section we add a blank pdfItem to the pdfPart for (int j = 0; j < items.size(); j++) { PDFItemBean pdfItem = new PDFItemBean(); ItemContentsBean item = (ItemContentsBean) items.get(j); String legacy = "<h3>" + item.getNumber() +"</h3>"; pdfItem.setItemId(item.getItemData().getItemId()); String content = "<br />" + item.getItemData().getText() + "<br />"; if (item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING)) { content += printMessages.getString("time_allowed_seconds") + ": " + item.getItemData().getDuration(); content += "<br />" + printMessages.getString("number_of_tries") + ": " + item.getItemData().getTriesAllowed(); content += "<br />"; } if (item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += printMessages.getString("upload_instruction") + "<br />"; content += printMessages.getString("file") + ": "; content += "<input type='text' size='50' />"; content += "<input type='button' value='" + printMessages.getString("browse") + ":' />"; content += "<input type='button' value='" + printMessages.getString("upload") + ":' />"; content += "<br />"; } if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) { ArrayList question = item.getItemData().getItemTextArraySorted(); for (int k=0; k<question.size(); k++) { PublishedItemText itemtext = (PublishedItemText)question.get(k); ArrayList answers = itemtext.getAnswerArraySorted(); content += "<table cols='20' width='100%'>"; for (int t=0; t<answers.size(); t++) { PublishedAnswer answer = (PublishedAnswer)answers.get(t); if (answer.getText() == null) break; content += "<tr>" + getContentAnswer(item, answer, printSetting) + "</tr>"; } content += "</table>"; } } if (item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) { content += "<table cols='20' width='100%'>"; ArrayList question = item.getMatchingArray(); for (int k=0; k<question.size(); k++) { MatchingBean matching = (MatchingBean)question.get(k); String answer = (String)item.getAnswers().get(k); if (matching.getText() == null) break; content += "<tr><td colspan='10'>"; content += matching.getText(); content += "</td>"; content += "<td colspan='10'>"; content += answer + "</td></tr>"; } content += "</table>"; } if (printSetting.getShowKeys().booleanValue() || printSetting.getShowKeysFeedback().booleanValue()) { content += "<br />" + getContentQuestion(item, printSetting); } pdfItem.setContent(content); if (legacy != null) { pdfItem.setMeta(legacy); } pdfItems.add(pdfItem); } pdfPart.setQuestions(pdfItems); pdfPart.setResources(resources); if (resources.size() > 0) pdfPart.setHasResources(new Boolean(true)); pdfParts.add(pdfPart); } //set the new colleciton of PDF beans to be the contents of the pdfassessment setParts(pdfParts); setTitle(deliveryBean.getAssessmentTitle()); return "print"; } private String getContentAnswer(ItemContentsBean item, PublishedAnswer answer, PrintSettingsBean printSetting) { String content = ""; if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION)) { if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT)) content += "<td colspan='1'><img src='/samigo-app/images/unchecked.gif' /></td>"; else content += "<td colspan='1'><img src='/samigo-app/images/radiounchecked.gif' /></td>"; content += "<td colspan='10'>"; if (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY)) content += answer.getLabel() + ". "; content += answer.getText(); content += "</td>"; content += "<td colspan='9'>"; if (printSetting.getShowKeysFeedback()) { content += "<h6>" + printMessages.getString("feedback") + ": "; if (answer.getGeneralAnswerFeedback() != null && !answer.getGeneralAnswerFeedback().equals("")) content += answer.getGeneralAnswerFeedback(); else content += "--------"; content += "</h6>"; } content += "</td>"; } if (item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE)) { content += "<td colspan='1'><img src='/samigo-app/images/radiounchecked.gif' /></td>"; content += "<td colspan='19'>"; content += answer.getText(); content += "</td>"; } return content; } private String getContentQuestion(ItemContentsBean item, PrintSettingsBean printSetting) { String content = "<h6>"; content += printMessages.getString("answer_point") + ": " + item.getItemData().getScore(); content += " " + authorMessages.getString("points_lower_case"); if (!item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY) && !item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) && !item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += "<br />"; if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) content += printMessages.getString("answer_model") + ": "; else content += printMessages.getString("answer_key") + ": "; if (item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) content += item.getKey(); else if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION)) { if (item.getKey() != null && !item.getKey().equals("")) content += item.getKey(); else content += "--------"; } else content += item.getItemData().getAnswerKey(); } if (printSetting.getShowKeysFeedback().booleanValue()) { if (item.getItemData().getTypeId().equals(TypeIfc.ESSAY_QUESTION) || item.getItemData().getTypeId().equals(TypeIfc.AUDIO_RECORDING) || item.getItemData().getTypeId().equals(TypeIfc.FILE_UPLOAD)) { content += "<br />"; content += printMessages.getString("feedback") + ": "; if (item.getItemData().getGeneralItemFeedback() != null && !item.getItemData().getGeneralItemFeedback().equals("")) content += item.getItemData().getGeneralItemFeedback(); else content += "--------"; } if (item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CHOICE) || item.getItemData().getTypeId().equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION) || item.getItemData().getTypeId().equals(TypeIfc.TRUE_FALSE) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_BLANK) || item.getItemData().getTypeId().equals(TypeIfc.FILL_IN_NUMERIC) || item.getItemData().getTypeId().equals(TypeIfc.MATCHING)) { content += "<br />"; content += printMessages.getString("correct_feedback") + ": "; if (item.getItemData().getCorrectItemFeedback() != null && !item.getItemData().getCorrectItemFeedback().equals("")) content += item.getItemData().getCorrectItemFeedback(); else content += "--------"; content += "<br />" + printMessages.getString("incorrect_feedback") + ": "; if (item.getItemData().getInCorrectItemFeedback() != null && !item.getItemData().getInCorrectItemFeedback().equals("")) content += item.getItemData().getInCorrectItemFeedback(); else content += "--------"; } } return content + "</h6>"; } public void getPDFAttachment() { prepDocumentPDF(); ByteArrayOutputStream pdf = getStream(); FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse(); response.reset(); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0"); response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + genName()); response.setContentLength(pdf.toByteArray().length); OutputStream out = null; try { out = response.getOutputStream(); out.write(pdf.toByteArray()); out.flush(); } catch (IOException e) { log.error(e); e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { log.error(e); e.printStackTrace(); } } faces.responseComplete(); } /** * Converts all nice new school html into old school * font tagged up html that HTMLWorker will actually * parse right * * @param input */ private String oldschoolIfy(String input) { if (log.isDebugEnabled()) log.debug("starting oldschoolify with: " + input); input = input.replaceAll("<h1", "<div><font color='#01a5cb' size='" + (int)(baseFontSize * 1.1) + "'"); input = input.replaceAll("<h2", "<div><font color='#01a5cb' size='" + (int)(baseFontSize * 1.1) + "'"); input = input.replaceAll("<h3", "<div><font color='#CCCCCC' size='" + (int)(baseFontSize * 1) + "'"); input = input.replaceAll("<h4", "<div><font size='" + (int)(baseFontSize * .85) + "'"); input = input.replaceAll("<h5", "<div><font size='" + (int)(baseFontSize * .8) + "'"); input = input.replaceAll("<h6", "<div><font color='#333333' size='" + (int)(baseFontSize * .6) + "'"); input = input.replaceAll("</h.>", "</font></div>"); return input; } /** * Turns a string into a StringReader with out the fuss of an IOException * * @param input * @return StringReader */ private Reader safeReader(String input) { StringReader output = null; if (input == null) { input = ""; } else { input = oldschoolIfy(input); } try { output = new StringReader(input + "<br/>"); } catch(Exception e) { log.error("could not get StringReader for String " + input + " due to : " + e); } return output; } public ByteArrayOutputStream getStream() { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { if (log.isInfoEnabled()) log.info("starting PDF generation" ); Document document = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter docWriter = PdfWriter.getInstance(document, output); document.open(); document.resetPageCount(); HTMLWorker worker = new HTMLWorker(document); HashMap props = worker.getInterfaceProps(); if (props == null) { props = new HashMap(); } float prevs = 0; props.put("img_baseurl", ServerConfigurationService.getServerUrl()); worker.setInterfaceProps(props); //TODO make a real style sheet StyleSheet style = null; String head = printMessages.getString("print_name_form"); head += "<br />"; head += printMessages.getString("print_score_form"); head += "<br /><br />"; head += "<h1>" + title + "</h1><br />"; head += intro + "<br />"; //head = head.replaceAll("[ \t\n\f\r]+", " "); //parse out the elements from the html ArrayList elementBuffer = HTMLWorker.parseToList(safeReader(head), style, props); float[] singleWidth = {1f}; PdfPTable single = new PdfPTable(singleWidth); single.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.setBorderWidth(0); for (int k = 0; k < elementBuffer.size(); k++) { cell.addElement((Element)elementBuffer.get(k)); } single.addCell(cell); prevs += single.getTotalHeight() % document.getPageSize().height(); //TODO do we want a new page here ... thus giving the cover page look? document.add(single); document.add(Chunk.NEWLINE); //extract the html and parse it into pdf ArrayList parts = getHtmlChunks(); for (int i = 0; i < parts.size(); i++) { //add new page to start each new part if (i > 0) { document.newPage(); } PDFPartBean pBean = (PDFPartBean) parts.get(i); if (pBean.getIntro() != null && !"".equals(pBean.getIntro())) { elementBuffer = HTMLWorker.parseToList(safeReader(pBean.getIntro()), style, props); single = new PdfPTable(singleWidth); single.setWidthPercentage(100f); cell = new PdfPCell(); cell.setBorderWidth(0); for (int k = 0; k < elementBuffer.size(); k++) { cell.addElement((Element)elementBuffer.get(k)); } single.addCell(cell); prevs += single.getTotalHeight() % document.getPageSize().height(); document.add(single); } ArrayList items = pBean.getQuestions(); for (int j = 0; j < items.size(); j++) { PDFItemBean iBean = (PDFItemBean) items.get(j); float[] widths = {0.1f, 0.9f}; PdfPTable table = new PdfPTable(widths); table.setWidthPercentage(100f); PdfPCell leftCell = new PdfPCell(); PdfPCell rightCell = new PdfPCell(); leftCell.setBorderWidth(0); leftCell.setPadding(0); leftCell.setLeading(0.00f, 0.00f); leftCell.setHorizontalAlignment(Element.ALIGN_RIGHT); leftCell.setVerticalAlignment(Element.ALIGN_TOP); rightCell.setBorderWidth(0); elementBuffer = HTMLWorker.parseToList(safeReader(iBean.getMeta()), style, props); for (int k = 0; k < elementBuffer.size(); k++) { Element element = (Element)elementBuffer.get(k); if (element instanceof Paragraph) { Paragraph p = (Paragraph)element; p.getFont().setColor(Color.GRAY); p.setAlignment(Paragraph.ALIGN_CENTER); } leftCell.addElement(element); } table.addCell(leftCell); elementBuffer = HTMLWorker.parseToList(safeReader(iBean.getContent()), style, props); for (int k = 0; k < elementBuffer.size(); k++) { Element element = (Element)elementBuffer.get(k); rightCell.addElement(element); } table.addCell(rightCell); if (table.getTotalHeight() + prevs > document.getPageSize().height()) document.newPage(); document.add(table); document.add(Chunk.NEWLINE); //TODO add PDFTable and a collumn //worker.parse(safeReader(iBean.getMeta())); //TODO column break //worker.parse(safeReader(iBean.getContent())); //TODO end column and table } } document.close(); docWriter.close(); } catch(Exception e) { e.printStackTrace(); System.err.println("document: " + e.getMessage()); } return output; } public String getBaseFontSize() { return "" + baseFontSize; } public void setBaseFontSize(String baseFontSize) { this.baseFontSize = Integer.parseInt(baseFontSize); } /** * @return the actionString */ public String getActionString() { return actionString; } /** * @param actionString the actionString to set */ public void setActionString(String actionString) { this.actionString = actionString; } public String getSizeDeliveryParts() { return "" + deliveryParts.size(); } public String getTotalQuestions() { int items = 0; for (int i=0; i<deliveryParts.size(); i++) { SectionContentsBean section = (SectionContentsBean) deliveryParts.get(i); items += section.getItemContents().size(); } return "" + items; } }
SAM-1011 git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@84315 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/print/PDFAssessmentBean.java
SAM-1011
Java
apache-2.0
fa0b9d1ff003650d93d2ec774e0bd79f3885d3e2
0
Onegini/cordova-plugin-onegini,Onegini/cordova-plugin-onegini,Onegini/cordova-plugin-onegini
package com.onegini.actions; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import com.onegini.OneginiCordovaPlugin; public class AwaitInitialization implements OneginiPluginAction { private static CallbackContext pluginInitializedCallback; public static void notifyIfPluginInitialized() { if (pluginInitializedCallback == null) { return; } if (PluginInitializer.isConfigured() && isPinCallbackSessionSet()) { pluginInitializedCallback.success(); } } public static void notifyPluginInitializationFailed() { if (pluginInitializedCallback == null) { return; } pluginInitializedCallback.error("Failed to initialize plugin."); } @Override public void execute(final JSONArray args, final CallbackContext callbackContext, final OneginiCordovaPlugin client) { pluginInitializedCallback = callbackContext; notifyIfPluginInitialized(); } private static boolean isPinCallbackSessionSet() { return PinCallbackSession.getPinCallback() != null; } }
src/android/src/android/com/onegini/actions/AwaitInitialization.java
package com.onegini.actions; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import com.onegini.OneginiCordovaPlugin; public class AwaitInitialization implements OneginiPluginAction { private static CallbackContext pluginInitializedCallback; public static void notifyIfPluginInitialized() { if (pluginInitializedCallback == null) { return; } if (PluginInitializer.isConfigured() && isPinCallbackSessionSet()) { pluginInitializedCallback.success(); } else { notifyPluginInitializationFailed(); } } public static void notifyPluginInitializationFailed() { if (pluginInitializedCallback == null) { return; } pluginInitializedCallback.error("Failed to initialize plugin."); } @Override public void execute(final JSONArray args, final CallbackContext callbackContext, final OneginiCordovaPlugin client) { pluginInitializedCallback = callbackContext; notifyIfPluginInitialized(); } private static boolean isPinCallbackSessionSet() { return PinCallbackSession.getPinCallback() != null; } }
MS-217, error callback should not be sent during at this step as plugin may still be not initialised Former-commit-id: 0fc48b4814a9f80c658980479f9e16364814b757
src/android/src/android/com/onegini/actions/AwaitInitialization.java
MS-217, error callback should not be sent during at this step as plugin may still be not initialised
Java
apache-2.0
13dd48a263615bc32ae7b5ee8e1e1962bb354b7b
0
jankotek/titan,thinkaurelius/titan,mwpnava/titan,samanalysis/titan,ThiagoGarciaAlves/titan,infochimps-forks/titan,wangbf/titan,elkingtonmcb/titan,CYPP/titan,anuragkh/titan,englishtown/titan,evanv/titan,elkingtonmcb/titan,tomersagi/titan,kalatestimine/titan,infochimps-forks/titan,jamestyack/titan,jamestyack/titan,hortonworks/titan,englishtown/titan,evanv/titan,infochimps-forks/titan,jankotek/titan,wangbf/titan,anuragkh/titan,twilmes/titan,twilmes/titan,CYPP/titan,anvie/titan,xlcupid/titan,pluradj/titan,mwpnava/titan,banjiewen/titan,mwpnava/titan,hortonworks/titan,fengshao0907/titan,jankotek/titan,kalatestimine/titan,kangkot/titan,jamestyack/titan,elubow/titan,amcp/titan,fengshao0907/titan,evanv/titan,hortonworks/titan,graben1437/titan,mwpnava/titan,elubow/titan,dylanht/titan,graben1437/titan,nvoron23/titan,wangbf/titan,wangbf/titan,kangkot/titan,hortonworks/titan,samanalysis/titan,kangkot/titan,kangkot/titan,elkingtonmcb/titan,qiuqiyuan/titan,ThiagoGarciaAlves/titan,mwpnava/titan,xlcupid/titan,tomersagi/titan,hortonworks/titan,kalatestimine/titan,elkingtonmcb/titan,boorad/titan,dylanht/titan,CYPP/titan,nvoron23/titan,amcp/titan,twilmes/titan,CYPP/titan,mbrukman/titan,dylanht/titan,fengshao0907/titan,englishtown/titan,kalatestimine/titan,dylanht/titan,jankotek/titan,elubow/titan,mbrukman/titan,qiuqiyuan/titan,xlcupid/titan,qiuqiyuan/titan,banjiewen/titan,boorad/titan,anvie/titan,englishtown/titan,elkingtonmcb/titan,xlcupid/titan,graben1437/titan,qiuqiyuan/titan,mbrukman/titan,evanv/titan,evanv/titan,fengshao0907/titan,amcp/titan,graben1437/titan,fengshao0907/titan,thinkaurelius/titan,banjiewen/titan,nvoron23/titan,samanalysis/titan,jankotek/titan,tomersagi/titan,mbrukman/titan,xlcupid/titan,amcp/titan,kangkot/titan,thinkaurelius/titan,nvoron23/titan,ThiagoGarciaAlves/titan,twilmes/titan,infochimps-forks/titan,kalatestimine/titan,anvie/titan,twilmes/titan,pluradj/titan,elubow/titan,tomersagi/titan,anvie/titan,ThiagoGarciaAlves/titan,infochimps-forks/titan,anuragkh/titan,tomersagi/titan,banjiewen/titan,anuragkh/titan,pluradj/titan,anvie/titan,boorad/titan,samanalysis/titan,mbrukman/titan,boorad/titan,anuragkh/titan,ThiagoGarciaAlves/titan,jamestyack/titan,jamestyack/titan,wangbf/titan,qiuqiyuan/titan,thinkaurelius/titan,pluradj/titan
package com.thinkaurelius.titan.graphdb.transaction.vertexcache; import java.util.ArrayList; import java.util.List; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.graphdb.internal.InternalVertex; import com.thinkaurelius.titan.graphdb.util.ConcurrentLRUCache; import com.thinkaurelius.titan.util.datastructures.Retriever; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; public class LRUVertexCache implements VertexCache { private final NonBlockingHashMapLong<InternalVertex> volatileVertices; private final ConcurrentLRUCache<InternalVertex> cache; public LRUVertexCache(int capacity) { volatileVertices = new NonBlockingHashMapLong<InternalVertex>(); cache = new ConcurrentLRUCache<InternalVertex>(capacity * 2, // upper is double capacity capacity + capacity / 3, // lower is capacity + 1/3 capacity, // acceptable watermark is capacity 100, true, false, // 100 items initial size + use only one thread for items cleanup new ConcurrentLRUCache.EvictionListener<InternalVertex>() { @Override public void evictedEntry(Long vertexId, InternalVertex vertex) { if (vertexId == null || vertex == null) return; if (vertex.hasAddedRelations()) { volatileVertices.putIfAbsent(vertexId, vertex); } } }); cache.setAlive(true); //need counters to its actually LRU } @Override public boolean contains(long id) { Long vertexId = id; return cache.containsKey(vertexId) || volatileVertices.containsKey(vertexId); } @Override public InternalVertex get(long id, final Retriever<Long, InternalVertex> retriever) { final Long vertexId = id; InternalVertex vertex = cache.get(vertexId); if (vertex == null) { InternalVertex newVertex = volatileVertices.get(vertexId); if (newVertex == null) { newVertex = retriever.get(vertexId); } vertex = cache.putIfAbsent(vertexId, newVertex); if (vertex == null) vertex = newVertex; } return vertex; } @Override public void add(InternalVertex vertex, long id) { Preconditions.checkNotNull(vertex); Preconditions.checkArgument(id != 0); Long vertexId = id; cache.put(vertexId, vertex); if (vertex.isNew() || vertex.hasAddedRelations()) volatileVertices.put(vertexId, vertex); } @Override public List<InternalVertex> getAllNew() { List<InternalVertex> vertices = new ArrayList<InternalVertex>(10); for (InternalVertex v : volatileVertices.values()) { if (v.isNew()) vertices.add(v); } return vertices; } @Override public synchronized void close() { volatileVertices.clear(); cache.destroy(); } }
titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/vertexcache/LRUVertexCache.java
package com.thinkaurelius.titan.graphdb.transaction.vertexcache; import java.util.ArrayList; import java.util.List; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.graphdb.internal.InternalVertex; import com.thinkaurelius.titan.graphdb.util.ConcurrentLRUCache; import com.thinkaurelius.titan.util.datastructures.Retriever; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; public class LRUVertexCache implements VertexCache { private final NonBlockingHashMapLong<InternalVertex> volatileVertices; private final ConcurrentLRUCache<InternalVertex> cache; public LRUVertexCache(int capacity) { volatileVertices = new NonBlockingHashMapLong<InternalVertex>(); cache = new ConcurrentLRUCache<InternalVertex>(capacity * 2, // upper is double capacity capacity + capacity / 3, // lower is capacity + 1/3 capacity, // acceptable watermark is capacity 100, true, false, // 100 items initial size + use only one thread for items cleanup new ConcurrentLRUCache.EvictionListener<InternalVertex>() { @Override public void evictedEntry(Long vertexId, InternalVertex vertex) { if (vertexId == null || vertex == null) return; if (vertex.hasAddedRelations()) { volatileVertices.putIfAbsent(vertexId, vertex); } } }); cache.setAlive(true); //need counters to its actually LRU } @Override public boolean contains(long id) { Long vertexId = id; return cache.containsKey(vertexId) || volatileVertices.containsKey(vertexId); } @Override public InternalVertex get(long id, final Retriever<Long, InternalVertex> retriever) { final Long vertexId = id; InternalVertex vertex = cache.get(vertexId); if (vertex == null) { vertex = volatileVertices.get(vertexId); if (vertex == null) { InternalVertex newVertex = retriever.get(vertexId); vertex = cache.putIfAbsent(vertexId, vertex); if (vertex == null) vertex = newVertex; } } return vertex; } @Override public void add(InternalVertex vertex, long id) { Preconditions.checkNotNull(vertex); Preconditions.checkArgument(id != 0); Long vertexId = id; cache.put(vertexId, vertex); if (vertex.isNew() || vertex.hasAddedRelations()) volatileVertices.put(vertexId, vertex); } @Override public List<InternalVertex> getAllNew() { List<InternalVertex> vertices = new ArrayList<InternalVertex>(10); for (InternalVertex v : volatileVertices.values()) { if (v.isNew()) vertices.add(v); } return vertices; } @Override public synchronized void close() { volatileVertices.clear(); cache.destroy(); } }
fix VertexLRUCache get to actually cache non-existing vertices
titan-core/src/main/java/com/thinkaurelius/titan/graphdb/transaction/vertexcache/LRUVertexCache.java
fix VertexLRUCache get to actually cache non-existing vertices
Java
apache-2.0
779614dd629fd8d5815d4e087b3b8ee9c19c654e
0
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.cloudbreak.service.identitymapping; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.cloud.IdentityService; import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors; import com.sequenceiq.cloudbreak.cloud.model.Platform; import com.sequenceiq.cloudbreak.cloud.model.Variant; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.converter.spi.CredentialToCloudCredentialConverter; import com.sequenceiq.cloudbreak.dto.credential.Credential; @Component public class GcpMockAccountMappingService { private static final String FIXED_SERVICE_ACCOUNT_ROLE = "mock-idbroker-admin-role@${projectId}.iam.gserviceaccount.com"; private static final Map<String, String> MOCK_IDBROKER_USER_MAPPINGS = AccountMappingSubject.ALL_SPECIAL_USERS .stream() .map(user -> Map.entry(user, FIXED_SERVICE_ACCOUNT_ROLE)) .collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue)); private final CloudPlatformConnectors cloudPlatformConnectors; private final CredentialToCloudCredentialConverter credentialConverter; public GcpMockAccountMappingService(CloudPlatformConnectors cloudPlatformConnectors, CredentialToCloudCredentialConverter credentialConverter) { this.cloudPlatformConnectors = cloudPlatformConnectors; this.credentialConverter = credentialConverter; } public Map<String, String> getGroupMappings(String region, Credential credential, String adminGroupName) { String projectId = getProjectId(region, credential); if (StringUtils.isNotEmpty(adminGroupName)) { return replaceProjectName(getGroupMappings(adminGroupName), projectId); } else { throw new CloudbreakServiceException(String.format("Failed to get group mappings because of missing adminGroupName for getProjectId: %s", projectId)); } } public Map<String, String> getUserMappings(String region, Credential credential) { String projectName = getProjectId(region, credential); return replaceProjectName(MOCK_IDBROKER_USER_MAPPINGS, projectName); } private String getProjectId(String region, Credential credential) { IdentityService identityService = getIdentityService(credential.cloudPlatform()); return identityService.getAccountId(region, credentialConverter.convert(credential)); } private IdentityService getIdentityService(String platform) { return cloudPlatformConnectors.get(Platform.platform(platform), Variant.variant(platform)).identityService(); } private Map<String, String> replaceProjectName(Map<String, String> mappings, String projectId) { return mappings.entrySet() .stream() .map(e -> Map.entry(e.getKey(), e.getValue().replace("${projectId}", projectId))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); } private Map<String, String> getGroupMappings(String adminGroupName) { return Map.ofEntries( Map.entry(adminGroupName, FIXED_SERVICE_ACCOUNT_ROLE) ); } }
core/src/main/java/com/sequenceiq/cloudbreak/service/identitymapping/GcpMockAccountMappingService.java
package com.sequenceiq.cloudbreak.service.identitymapping; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.cloud.IdentityService; import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors; import com.sequenceiq.cloudbreak.cloud.model.Platform; import com.sequenceiq.cloudbreak.cloud.model.Variant; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.converter.spi.CredentialToCloudCredentialConverter; import com.sequenceiq.cloudbreak.dto.credential.Credential; @Component public class GcpMockAccountMappingService { private static final String FIXED_SERVICE_ACCOUNT_ROLE = " mock-idbroker-admin-role@${projectId}.iam.gserviceaccount.com"; private static final Map<String, String> MOCK_IDBROKER_USER_MAPPINGS = AccountMappingSubject.ALL_SPECIAL_USERS .stream() .map(user -> Map.entry(user, FIXED_SERVICE_ACCOUNT_ROLE)) .collect(Collectors.toUnmodifiableMap(Entry::getKey, Entry::getValue)); private final CloudPlatformConnectors cloudPlatformConnectors; private final CredentialToCloudCredentialConverter credentialConverter; public GcpMockAccountMappingService(CloudPlatformConnectors cloudPlatformConnectors, CredentialToCloudCredentialConverter credentialConverter) { this.cloudPlatformConnectors = cloudPlatformConnectors; this.credentialConverter = credentialConverter; } public Map<String, String> getGroupMappings(String region, Credential credential, String adminGroupName) { String projectId = getProjectId(region, credential); if (StringUtils.isNotEmpty(adminGroupName)) { return replaceProjectName(getGroupMappings(adminGroupName), projectId); } else { throw new CloudbreakServiceException(String.format("Failed to get group mappings because of missing adminGroupName for getProjectId: %s", projectId)); } } public Map<String, String> getUserMappings(String region, Credential credential) { String projectName = getProjectId(region, credential); return replaceProjectName(MOCK_IDBROKER_USER_MAPPINGS, projectName); } private String getProjectId(String region, Credential credential) { IdentityService identityService = getIdentityService(credential.cloudPlatform()); return identityService.getAccountId(region, credentialConverter.convert(credential)); } private IdentityService getIdentityService(String platform) { return cloudPlatformConnectors.get(Platform.platform(platform), Variant.variant(platform)).identityService(); } private Map<String, String> replaceProjectName(Map<String, String> mappings, String projectId) { return mappings.entrySet() .stream() .map(e -> Map.entry(e.getKey(), e.getValue().replace("${projectId}", projectId))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); } private Map<String, String> getGroupMappings(String adminGroupName) { return Map.ofEntries( Map.entry(adminGroupName, FIXED_SERVICE_ACCOUNT_ROLE) ); } }
CB-9250 fixing the current GCP mock idbroker role string to work correctly. This was testede with e2e cloud storage integration.
core/src/main/java/com/sequenceiq/cloudbreak/service/identitymapping/GcpMockAccountMappingService.java
CB-9250 fixing the current GCP mock idbroker role string to work correctly. This was testede with e2e cloud storage integration.
Java
apache-2.0
0c28ed51f4be7d8a178024d7b46bbcd11f05038b
0
kalatestimine/titan,nvoron23/titan,jankotek/titan,anuragkh/titan,elkingtonmcb/titan,ThiagoGarciaAlves/titan,kangkot/titan,qiuqiyuan/titan,evanv/titan,fengshao0907/titan,xlcupid/titan,jamestyack/titan,fengshao0907/titan,mwpnava/titan,wangbf/titan,kalatestimine/titan,jamestyack/titan,mwpnava/titan,elkingtonmcb/titan,nvoron23/titan,tomersagi/titan,kangkot/titan,mwpnava/titan,kangkot/titan,hortonworks/titan,kalatestimine/titan,anuragkh/titan,kalatestimine/titan,xlcupid/titan,jankotek/titan,wangbf/titan,nvoron23/titan,ThiagoGarciaAlves/titan,evanv/titan,jamestyack/titan,fengshao0907/titan,elkingtonmcb/titan,tomersagi/titan,anuragkh/titan,evanv/titan,elkingtonmcb/titan,kalatestimine/titan,ThiagoGarciaAlves/titan,hortonworks/titan,fengshao0907/titan,qiuqiyuan/titan,mwpnava/titan,xlcupid/titan,hortonworks/titan,kangkot/titan,hortonworks/titan,jamestyack/titan,jankotek/titan,tomersagi/titan,wangbf/titan,mwpnava/titan,wangbf/titan,xlcupid/titan,xlcupid/titan,evanv/titan,wangbf/titan,anuragkh/titan,fengshao0907/titan,elkingtonmcb/titan,qiuqiyuan/titan,anuragkh/titan,ThiagoGarciaAlves/titan,kangkot/titan,jamestyack/titan,nvoron23/titan,jankotek/titan,qiuqiyuan/titan,tomersagi/titan,jankotek/titan,hortonworks/titan,tomersagi/titan,ThiagoGarciaAlves/titan,evanv/titan,qiuqiyuan/titan
package com.thinkaurelius.titan.hadoop; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.hadoop.compat.HadoopCompatLoader; import com.thinkaurelius.titan.hadoop.compat.HadoopCompiler; import com.thinkaurelius.titan.hadoop.config.TitanHadoopConfiguration; import com.thinkaurelius.titan.hadoop.formats.EdgeCopyMapReduce; import com.thinkaurelius.titan.hadoop.formats.MapReduceFormat; import com.thinkaurelius.titan.hadoop.mapreduce.IdentityMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.BackFilterMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.filter.CyclicPathFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.DuplicateFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.FilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.IntervalFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.PropertyFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitEdgesMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitVerticesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.GroupCountMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.LinkMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ScriptMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.SideEffectMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ValueGroupCountMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesVerticesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.OrderMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PathMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMapMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.TransformMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VertexMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesEdgesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesVerticesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.util.CountMapReduce; import com.tinkerpop.blueprints.Compare; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.pipes.transform.TransformPipe; import com.tinkerpop.pipes.util.structures.Pair; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.util.ToolRunner; import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.tinkerpop.blueprints.Direction.*; /** * A HadoopPipeline defines a breadth-first traversal through a property graph representation. * Gremlin/Hadoop compiles down to a HadoopPipeline which is ultimately a series of MapReduce jobs. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class HadoopPipeline { private static final Logger log = LoggerFactory.getLogger(HadoopPipeline.class); // used to validate closure parse tree protected static final ScriptEngine engine = new GroovyScriptEngineImpl(); public static final String PIPELINE_IS_LOCKED = "No more steps are possible as pipeline is locked"; protected final HadoopCompiler compiler; protected final HadoopGraph graph; protected final State state; protected final List<String> stringRepresentation = new ArrayList<String>(); private Compare convert(final com.tinkerpop.gremlin.Tokens.T compare) { if (compare.equals(com.tinkerpop.gremlin.Tokens.T.eq)) return Compare.EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.neq)) return Compare.NOT_EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gt)) return Compare.GREATER_THAN; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gte)) return Compare.GREATER_THAN_EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.lt)) return Compare.LESS_THAN; else return Compare.LESS_THAN_EQUAL; } protected class State { private Class<? extends Element> elementType; private String propertyKey; private Class<? extends WritableComparable> propertyType; private int step = -1; private boolean locked = false; private Map<String, Integer> namedSteps = new HashMap<String, Integer>(); public State set(Class<? extends Element> elementType) { if (!elementType.equals(Vertex.class) && !elementType.equals(Edge.class)) throw new IllegalArgumentException("The element class type must be either Vertex or Edge"); this.elementType = elementType; return this; } public Class<? extends Element> getElementType() { return this.elementType; } public boolean atVertex() { if (null == this.elementType) throw new IllegalStateException("No element type can be inferred: start vertices (or edges) set must be defined"); return this.elementType.equals(Vertex.class); } public State setProperty(final String key, final Class type) { this.propertyKey = key; this.propertyType = convertJavaToHadoop(type); return this; } public Pair<String, Class<? extends WritableComparable>> popProperty() { if (null == this.propertyKey) return null; Pair<String, Class<? extends WritableComparable>> pair = new Pair<String, Class<? extends WritableComparable>>(this.propertyKey, this.propertyType); this.propertyKey = null; this.propertyType = null; return pair; } public int incrStep() { return ++this.step; } public int getStep() { return this.step; } public void assertNotLocked() { if (this.locked) throw new IllegalStateException(PIPELINE_IS_LOCKED); } public void assertNoProperty() { if (this.propertyKey != null) throw new IllegalStateException("This step can not follow a property reference"); } public void assertAtVertex() { if (!this.atVertex()) throw new IllegalStateException("This step can not follow an edge-based step"); } public void assertAtEdge() { if (this.atVertex()) throw new IllegalStateException("This step can not follow a vertex-based step"); } public boolean isLocked() { return this.locked; } public void lock() { this.locked = true; } public void addStep(final String name) { if (this.step == -1) throw new IllegalArgumentException("There is no previous step to name"); this.namedSteps.put(name, this.step); } public int getStep(final String name) { final Integer i = this.namedSteps.get(name); if (null == i) throw new IllegalArgumentException("There is no step identified by: " + name); else return i; } } //////////////////////////////// //////////////////////////////// //////////////////////////////// /** * Construct a HadoopPipeline * * @param graph the HadoopGraph that is the source of the traversal */ public HadoopPipeline(final HadoopGraph graph) { this.graph = graph; this.compiler = HadoopCompatLoader.getCompat().newCompiler(graph); this.state = new State(); if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) { try { ((Class<? extends MapReduceFormat>) this.graph.getGraphInputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } if (graph.hasEdgeCopyDirection()) { Direction ecDir = graph.getEdgeCopyDirection(); this.compiler.addMapReduce(EdgeCopyMapReduce.Map.class, null, EdgeCopyMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, EdgeCopyMapReduce.createConfiguration(ecDir)); } } //////// TRANSFORMS /** * The identity step does not alter the graph in anyway. * It has the benefit of emitting various useful graph statistic counters. * * @return the extended HadoopPipeline */ public HadoopPipeline _() { this.state.assertNotLocked(); this.compiler.addMap(IdentityMap.Map.class, NullWritable.class, FaunusVertex.class, IdentityMap.createConfiguration()); makeMapReduceString(IdentityMap.class); return this; } /** * Apply the provided closure to the current element and emit the result. * * @param closure the closure to apply to the element * @return the extended HadoopPipeline */ public HadoopPipeline transform(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(TransformMap.Map.class, NullWritable.class, FaunusVertex.class, TransformMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); this.state.lock(); makeMapReduceString(TransformMap.class); return this; } /** * Start a traversal at all vertices in the graph. * * @return the extended HadoopPipeline */ public HadoopPipeline V() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Vertex.class); this.compiler.addMap(VerticesMap.Map.class, NullWritable.class, FaunusVertex.class, VerticesMap.createConfiguration(this.state.incrStep() != 0)); makeMapReduceString(VerticesMap.class); return this; } /** * Start a traversal at all edges in the graph. * * @return the extended HadoopPipeline */ public HadoopPipeline E() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Edge.class); this.compiler.addMap(EdgesMap.Map.class, NullWritable.class, FaunusVertex.class, EdgesMap.createConfiguration(this.state.incrStep() != 0)); makeMapReduceString(EdgesMap.class); return this; } /** * Start a traversal at the vertices identified by the provided ids. * * @param ids the long ids of the vertices to start the traversal from * @return the extended HadoopPipeline */ public HadoopPipeline v(final long... ids) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Vertex.class); this.state.incrStep(); this.compiler.addMap(VertexMap.Map.class, NullWritable.class, FaunusVertex.class, VertexMap.createConfiguration(ids)); makeMapReduceString(VertexMap.class); return this; } /** * Take outgoing labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline out(final String... labels) { return this.inOutBoth(OUT, labels); } /** * Take incoming labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline in(final String... labels) { return this.inOutBoth(IN, labels); } /** * Take both incoming and outgoing labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline both(final String... labels) { return this.inOutBoth(BOTH, labels); } private HadoopPipeline inOutBoth(final Direction direction, final String... labels) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.state.incrStep(); this.compiler.addMapReduce(VerticesVerticesMapReduce.Map.class, null, VerticesVerticesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, VerticesVerticesMapReduce.createConfiguration(direction, labels)); this.state.set(Vertex.class); makeMapReduceString(VerticesVerticesMapReduce.class, direction.name(), Arrays.asList(labels)); return this; } /** * Take outgoing labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline outE(final String... labels) { return this.inOutBothE(OUT, labels); } /** * Take incoming labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline inE(final String... labels) { return this.inOutBothE(IN, labels); } /** * Take both incoming and outgoing labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline bothE(final String... labels) { return this.inOutBothE(BOTH, labels); } private HadoopPipeline inOutBothE(final Direction direction, final String... labels) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.state.incrStep(); this.compiler.addMapReduce(VerticesEdgesMapReduce.Map.class, null, VerticesEdgesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, VerticesEdgesMapReduce.createConfiguration(direction, labels)); this.state.set(Edge.class); makeMapReduceString(VerticesEdgesMapReduce.class, direction.name(), Arrays.asList(labels)); return this; } /** * Go to the outgoing/tail vertex of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline outV() { return this.inOutBothV(OUT); } /** * Go to the incoming/head vertex of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline inV() { return this.inOutBothV(IN); } /** * Go to both the incoming/head and outgoing/tail vertices of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline bothV() { return this.inOutBothV(BOTH); } private HadoopPipeline inOutBothV(final Direction direction) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtEdge(); this.state.incrStep(); this.compiler.addMap(EdgesVerticesMap.Map.class, NullWritable.class, FaunusVertex.class, EdgesVerticesMap.createConfiguration(direction)); this.state.set(Vertex.class); makeMapReduceString(EdgesVerticesMap.class, direction.name()); return this; } /** * Emit the property value of an element. * * @param key the key identifying the property * @param type the class of the property value (so Hadoop can intelligently handle the result) * @return the extended HadoopPipeline */ public HadoopPipeline property(final String key, final Class type) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.setProperty(key, type); return this; } /** * Emit the property value of an element. * * @param key the key identifying the property * @return the extended HadoopPipeline */ public HadoopPipeline property(final String key) { return this.property(key, String.class); } /** * Emit a string representation of the property map. * * @return the extended HadoopPipeline */ public HadoopPipeline map() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PropertyMapMap.Map.class, LongWritable.class, Text.class, PropertyMapMap.createConfiguration(this.state.getElementType())); makeMapReduceString(PropertyMap.class); this.state.lock(); return this; } /** * Emit the label of the current edge. * * @return the extended HadoopPipeline */ public HadoopPipeline label() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtEdge(); this.property(Tokens.LABEL, String.class); return this; } /** * Emit the path taken from start to current element. * * @return the extended HadoopPipeline */ public HadoopPipeline path() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PathMap.Map.class, NullWritable.class, Text.class, PathMap.createConfiguration(this.state.getElementType())); this.state.lock(); makeMapReduceString(PathMap.class); return this; } /** * Order the previous property value results and emit them with another element property value. * It is important to emit the previous property with a provided type else it is ordered lexigraphically. * * @param order increasing and descending order * @param elementKey the key of the element to associate it with * @return the extended HadoopPipeline */ public HadoopPipeline order(final TransformPipe.Order order, final String elementKey) { this.state.assertNotLocked(); final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null != pair) { this.compiler.addMapReduce(OrderMapReduce.Map.class, null, OrderMapReduce.Reduce.class, OrderMapReduce.createComparator(order, pair.getB()), pair.getB(), Text.class, Text.class, pair.getB(), OrderMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB(), elementKey)); makeMapReduceString(OrderMapReduce.class, order.name(), elementKey); } else { throw new IllegalArgumentException("There is no specified property to order on"); } this.state.lock(); return this; } /** * Order the previous property value results. * * @param order increasing and descending order * @return the extended HadoopPipeline */ public HadoopPipeline order(final TransformPipe.Order order) { return this.order(order, Tokens.ID); } /** * Order the previous property value results and emit them with another element property value. * It is important to emit the previous property with a provided type else it is ordered lexigraphically. * * @param order increasing and descending order * @param elementKey the key of the element to associate it with * @return the extended HadoopPipeline */ public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order, final String elementKey) { return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order), elementKey); } /** * Order the previous property value results. * * @param order increasing and descending order * @return the extended HadoopPipeline */ public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order) { return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order)); } //////// FILTERS /** * Emit or deny the current element based upon the provided boolean-based closure. * * @param closure return true to emit and false to remove. * @return the extended HadoopPipeline */ public HadoopPipeline filter(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(FilterMap.Map.class, NullWritable.class, FaunusVertex.class, FilterMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); makeMapReduceString(FilterMap.class); return this; } /** * Emit the current element if it has a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) { return this.has(key, convert(compare), values); } /** * Emit the current element if it does not have a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator (will be not'd) * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) { return this.hasNot(key, convert(compare), values); } /** * Emit the current element if it has a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final Compare compare, final Object... values) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PropertyFilterMap.Map.class, NullWritable.class, FaunusVertex.class, PropertyFilterMap.createConfiguration(this.state.getElementType(), key, compare, values)); makeMapReduceString(PropertyFilterMap.class, compare.name(), Arrays.asList(values)); return this; } /** * Emit the current element if it does not have a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator (will be not'd) * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final Compare compare, final Object... values) { return this.has(key, compare.opposite(), values); } /** * Emit the current element it has a property value equal to the provided values. * * @param key the property key of the element * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final Object... values) { return (values.length == 0) ? this.has(key, Compare.NOT_EQUAL, new Object[]{null}) : this.has(key, Compare.EQUAL, values); } /** * Emit the current element it does not have a property value equal to the provided values. * * @param key the property key of the element * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final Object... values) { return (values.length == 0) ? this.has(key, Compare.EQUAL, new Object[]{null}) : this.has(key, Compare.NOT_EQUAL, values); } /** * Emit the current element it has a property value equal within the provided range. * * @param key the property key of the element * @param startValue the start of the range (inclusive) * @param endValue the end of the range (exclusive) * @return the extended HadoopPipeline */ public HadoopPipeline interval(final String key, final Object startValue, final Object endValue) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(IntervalFilterMap.Map.class, NullWritable.class, FaunusVertex.class, IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue)); makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue); return this; } /** * Remove any duplicate traversers at a single element. * * @return the extended HadoopPipeline */ public HadoopPipeline dedup() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(DuplicateFilterMap.Map.class, NullWritable.class, FaunusVertex.class, DuplicateFilterMap.createConfiguration(this.state.getElementType())); makeMapReduceString(DuplicateFilterMap.class); return this; } /** * Go back to an element a named step ago. * Currently only backing up to vertices is supported. * * @param step the name of the step to back up to * @return the extended HadoopPipeline */ public HadoopPipeline back(final String step) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMapReduce(BackFilterMapReduce.Map.class, BackFilterMapReduce.Combiner.class, BackFilterMapReduce.Reduce.class, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, BackFilterMapReduce.createConfiguration(this.state.getElementType(), this.state.getStep(step))); makeMapReduceString(BackFilterMapReduce.class, step); return this; } /*public HadoopPipeline back(final int numberOfSteps) { this.state.assertNotLocked(); this.compiler.backFilterMapReduce(this.state.getElementType(), this.state.getStep() - numberOfSteps); this.compiler.setPathEnabled(true); makeMapReduceString(BackFilterMapReduce.class, numberOfSteps); return this; }*/ /** * Emit the element only if it was arrived at via a path that does not have cycles in it. * * @return the extended HadoopPipeline */ public HadoopPipeline simplePath() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(CyclicPathFilterMap.Map.class, NullWritable.class, FaunusVertex.class, CyclicPathFilterMap.createConfiguration(this.state.getElementType())); makeMapReduceString(CyclicPathFilterMap.class); return this; } //////// SIDEEFFECTS /** * Emit the element, but compute some sideeffect in the process. * For example, mutate the properties of the element. * * @param closure the sideeffect closure whose results are ignored. * @return the extended HadoopPipeline */ public HadoopPipeline sideEffect(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(SideEffectMap.Map.class, NullWritable.class, FaunusVertex.class, SideEffectMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); makeMapReduceString(SideEffectMap.class); return this; } /** * Name a step in order to reference it later in the expression. * * @param name the string representation of the name * @return the extended HadoopPipeline */ public HadoopPipeline as(final String name) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.addStep(name); final String string = "As(" + name + "," + this.stringRepresentation.get(this.state.getStep(name)) + ")"; this.stringRepresentation.set(this.state.getStep(name), string); return this; } /** * Have the elements for the named step previous project an edge to the current vertex with provided label. * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight. * No weight key is specified by "_" and then all duplicates are merged, but no weight is added to the resultant edge. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @param mergeWeightKey the property key to use for weight * @return the extended HadoopPipeline */ public HadoopPipeline linkIn(final String label, final String step, final String mergeWeightKey) { return this.link(IN, label, step, mergeWeightKey); } /** * Have the elements for the named step previous project an edge to the current vertex with provided label. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @return the extended HadoopPipeline */ public HadoopPipeline linkIn(final String label, final String step) { return this.link(IN, label, step, null); } /** * Have the elements for the named step previous project an edge from the current vertex with provided label. * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight. * No weight key is specified by "_" and then all duplicates are merged, but no weight is added to the resultant edge. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @param mergeWeightKey the property key to use for weight * @return the extended HadoopPipeline */ public HadoopPipeline linkOut(final String label, final String step, final String mergeWeightKey) { return link(OUT, label, step, mergeWeightKey); } /** * Have the elements for the named step previous project an edge from the current vertex with provided label. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @return the extended HadoopPipeline */ public HadoopPipeline linkOut(final String label, final String step) { return this.link(OUT, label, step, null); } private HadoopPipeline link(final Direction direction, final String label, final String step, final String mergeWeightKey) { this.state.assertNotLocked(); this.state.assertNoProperty(); Preconditions.checkNotNull(direction); this.compiler.addMapReduce(LinkMapReduce.Map.class, LinkMapReduce.Combiner.class, LinkMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, LinkMapReduce.createConfiguration(direction, label, this.state.getStep(step), mergeWeightKey)); log.debug("Added {} job with direction {}, label {}, step {}, merge weight key {}", LinkMapReduce.class.getSimpleName(), direction, label, step, mergeWeightKey); if (null != mergeWeightKey) makeMapReduceString(LinkMapReduce.class, direction.name(), label, step, mergeWeightKey); else makeMapReduceString(LinkMapReduce.class, direction.name(), label, step); return this; } /** * Count the number of times the previous element (or property) has been traversed to. * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount() { this.state.assertNotLocked(); final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null == pair) { return this.groupCount(null, null); } else { this.compiler.addMapReduce(ValueGroupCountMapReduce.Map.class, ValueGroupCountMapReduce.Combiner.class, ValueGroupCountMapReduce.Reduce.class, pair.getB(), LongWritable.class, pair.getB(), LongWritable.class, ValueGroupCountMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB())); makeMapReduceString(ValueGroupCountMapReduce.class, pair.getA()); } return this; } /** * Apply the provided closure to the incoming element to determine the grouping key. * The value of the count is incremented by 1 * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount(final String keyClosure) { return this.groupCount(keyClosure, null); } /** * Apply the provided closure to the incoming element to determine the grouping key. * Then apply the value closure to the current element to determine the count increment. * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount(final String keyClosure, final String valueClosure) { this.state.assertNotLocked(); this.compiler.addMapReduce(GroupCountMapReduce.Map.class, GroupCountMapReduce.Combiner.class, GroupCountMapReduce.Reduce.class, Text.class, LongWritable.class, Text.class, LongWritable.class, GroupCountMapReduce.createConfiguration(this.state.getElementType(), this.validateClosure(keyClosure), this.validateClosure(valueClosure))); makeMapReduceString(GroupCountMapReduce.class); return this; } private HadoopPipeline commit(final Tokens.Action action) { this.state.assertNotLocked(); this.state.assertNoProperty(); if (this.state.atVertex()) { this.compiler.addMapReduce(CommitVerticesMapReduce.Map.class, CommitVerticesMapReduce.Combiner.class, CommitVerticesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, CommitVerticesMapReduce.createConfiguration(action)); makeMapReduceString(CommitVerticesMapReduce.class, action.name()); } else { this.compiler.addMap(CommitEdgesMap.Map.class, NullWritable.class, FaunusVertex.class, CommitEdgesMap.createConfiguration(action)); makeMapReduceString(CommitEdgesMap.class, action.name()); } return this; } /** * Drop all the elements of respective type at the current step. Keep all others. * * @return the extended HadoopPipeline */ public HadoopPipeline drop() { return this.commit(Tokens.Action.DROP); } /** * Keep all the elements of the respetive type at the current step. Drop all others. * * @return the extended HadoopPipeline */ public HadoopPipeline keep() { return this.commit(Tokens.Action.KEEP); } public HadoopPipeline script(final String scriptUri, final String... args) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.compiler.addMap(ScriptMap.Map.class, NullWritable.class, FaunusVertex.class, ScriptMap.createConfiguration(scriptUri, args)); makeMapReduceString(CommitEdgesMap.class, scriptUri); // this.state.lock(); return this; } /////////////// UTILITIES /** * Count the number of traversers currently in the graph * * @return the count */ public HadoopPipeline count() { this.state.assertNotLocked(); this.compiler.addMapReduce(CountMapReduce.Map.class, CountMapReduce.Combiner.class, CountMapReduce.Reduce.class, NullWritable.class, LongWritable.class, NullWritable.class, LongWritable.class, CountMapReduce.createConfiguration(this.state.getElementType())); makeMapReduceString(CountMapReduce.class); this.state.lock(); return this; } public String toString() { return this.stringRepresentation.toString(); } private HadoopPipeline done() { if (!this.state.isLocked()) { final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null != pair) { this.compiler.addMap(PropertyMap.Map.class, LongWritable.class, pair.getB(), PropertyMap.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB())); makeMapReduceString(PropertyMap.class, pair.getA()); this.state.lock(); } } return this; } /** * Submit the HadoopPipeline to the Hadoop cluster. * * @throws Exception */ public int submit() throws Exception { return submit(Tokens.EMPTY_STRING, false); } /** * Submit the HadoopPipeline to the Hadoop cluster and ensure that a header is emitted in the logs. * * @param script the Gremlin script * @param showHeader the Titan/Hadoop header * @throws Exception */ public int submit(final String script, final Boolean showHeader) throws Exception { this.done(); if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphOutputFormat())) { this.state.assertNotLocked(); ((Class<? extends MapReduceFormat>) this.graph.getGraphOutputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler); } this.compiler.completeSequence(); return ToolRunner.run(this.compiler, new String[]{script, showHeader.toString()}); } /** * Get a reference to the graph currently being used in this HadoopPipeline. * * @return the HadoopGraph */ public HadoopGraph getGraph() { return this.graph; } public HadoopCompiler getCompiler() { return this.compiler; } private String validateClosure(String closure) { if (closure == null) return null; try { engine.eval(closure); return closure; } catch (ScriptException e) { closure = closure.trim(); closure = closure.replaceFirst("\\{", "{it->"); try { engine.eval(closure); return closure; } catch (ScriptException e1) { } throw new IllegalArgumentException("The provided closure does not compile: " + e.getMessage(), e); } } private void makeMapReduceString(final Class klass, final Object... arguments) { String result = klass.getSimpleName(); if (arguments.length > 0) { result = result + "("; for (final Object arg : arguments) { result = result + arg + ","; } result = result.substring(0, result.length() - 1) + ")"; } this.stringRepresentation.add(result); } private Class<? extends WritableComparable> convertJavaToHadoop(final Class klass) { if (klass.equals(String.class)) { return Text.class; } else if (klass.equals(Integer.class)) { return IntWritable.class; } else if (klass.equals(Double.class)) { return DoubleWritable.class; } else if (klass.equals(Long.class)) { return LongWritable.class; } else if (klass.equals(Float.class)) { return FloatWritable.class; } else if (klass.equals(Boolean.class)) { return BooleanWritable.class; } else { throw new IllegalArgumentException("The provided class is not supported: " + klass.getSimpleName()); } } }
titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/HadoopPipeline.java
package com.thinkaurelius.titan.hadoop; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.hadoop.compat.HadoopCompatLoader; import com.thinkaurelius.titan.hadoop.compat.HadoopCompiler; import com.thinkaurelius.titan.hadoop.config.TitanHadoopConfiguration; import com.thinkaurelius.titan.hadoop.formats.EdgeCopyMapReduce; import com.thinkaurelius.titan.hadoop.formats.MapReduceFormat; import com.thinkaurelius.titan.hadoop.mapreduce.IdentityMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.BackFilterMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.filter.CyclicPathFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.DuplicateFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.FilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.IntervalFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.filter.PropertyFilterMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitEdgesMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.CommitVerticesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.GroupCountMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.LinkMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ScriptMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.SideEffectMap; import com.thinkaurelius.titan.hadoop.mapreduce.sideeffect.ValueGroupCountMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.EdgesVerticesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.OrderMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PathMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.PropertyMapMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.TransformMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VertexMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesEdgesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesMap; import com.thinkaurelius.titan.hadoop.mapreduce.transform.VerticesVerticesMapReduce; import com.thinkaurelius.titan.hadoop.mapreduce.util.CountMapReduce; import com.tinkerpop.blueprints.Compare; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.pipes.transform.TransformPipe; import com.tinkerpop.pipes.util.structures.Pair; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.util.ToolRunner; import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.tinkerpop.blueprints.Direction.*; /** * A HadoopPipeline defines a breadth-first traversal through a property graph representation. * Gremlin/Hadoop compiles down to a HadoopPipeline which is ultimately a series of MapReduce jobs. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class HadoopPipeline { private static final Logger log = LoggerFactory.getLogger(HadoopPipeline.class); // used to validate closure parse tree protected static final ScriptEngine engine = new GroovyScriptEngineImpl(); public static final String PIPELINE_IS_LOCKED = "No more steps are possible as pipeline is locked"; protected final HadoopCompiler compiler; protected final HadoopGraph graph; protected final State state; protected final List<String> stringRepresentation = new ArrayList<String>(); private Compare convert(final com.tinkerpop.gremlin.Tokens.T compare) { if (compare.equals(com.tinkerpop.gremlin.Tokens.T.eq)) return Compare.EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.neq)) return Compare.NOT_EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gt)) return Compare.GREATER_THAN; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.gte)) return Compare.GREATER_THAN_EQUAL; else if (compare.equals(com.tinkerpop.gremlin.Tokens.T.lt)) return Compare.LESS_THAN; else return Compare.LESS_THAN_EQUAL; } protected class State { private Class<? extends Element> elementType; private String propertyKey; private Class<? extends WritableComparable> propertyType; private int step = -1; private boolean locked = false; private Map<String, Integer> namedSteps = new HashMap<String, Integer>(); public State set(Class<? extends Element> elementType) { if (!elementType.equals(Vertex.class) && !elementType.equals(Edge.class)) throw new IllegalArgumentException("The element class type must be either Vertex or Edge"); this.elementType = elementType; return this; } public Class<? extends Element> getElementType() { return this.elementType; } public boolean atVertex() { if (null == this.elementType) throw new IllegalStateException("No element type can be inferred: start vertices (or edges) set must be defined"); return this.elementType.equals(Vertex.class); } public State setProperty(final String key, final Class type) { this.propertyKey = key; this.propertyType = convertJavaToHadoop(type); return this; } public Pair<String, Class<? extends WritableComparable>> popProperty() { if (null == this.propertyKey) return null; Pair<String, Class<? extends WritableComparable>> pair = new Pair<String, Class<? extends WritableComparable>>(this.propertyKey, this.propertyType); this.propertyKey = null; this.propertyType = null; return pair; } public int incrStep() { return ++this.step; } public int getStep() { return this.step; } public void assertNotLocked() { if (this.locked) throw new IllegalStateException(PIPELINE_IS_LOCKED); } public void assertNoProperty() { if (this.propertyKey != null) throw new IllegalStateException("This step can not follow a property reference"); } public void assertAtVertex() { if (!this.atVertex()) throw new IllegalStateException("This step can not follow an edge-based step"); } public void assertAtEdge() { if (this.atVertex()) throw new IllegalStateException("This step can not follow a vertex-based step"); } public boolean isLocked() { return this.locked; } public void lock() { this.locked = true; } public void addStep(final String name) { if (this.step == -1) throw new IllegalArgumentException("There is no previous step to name"); this.namedSteps.put(name, this.step); } public int getStep(final String name) { final Integer i = this.namedSteps.get(name); if (null == i) throw new IllegalArgumentException("There is no step identified by: " + name); else return i; } } //////////////////////////////// //////////////////////////////// //////////////////////////////// /** * Construct a HadoopPipeline * * @param graph the HadoopGraph that is the source of the traversal */ public HadoopPipeline(final HadoopGraph graph) { this.graph = graph; this.compiler = HadoopCompatLoader.getCompat().newCompiler(graph); this.state = new State(); if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) { try { ((Class<? extends MapReduceFormat>) this.graph.getGraphInputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } if (graph.hasEdgeCopyDirection()) { Direction ecDir = graph.getEdgeCopyDirection(); this.compiler.addMapReduce(EdgeCopyMapReduce.Map.class, null, EdgeCopyMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, EdgeCopyMapReduce.createConfiguration(ecDir)); } } //////// TRANSFORMS /** * The identity step does not alter the graph in anyway. * It has the benefit of emitting various useful graph statistic counters. * * @return the extended HadoopPipeline */ public HadoopPipeline _() { this.state.assertNotLocked(); this.compiler.addMap(IdentityMap.Map.class, NullWritable.class, FaunusVertex.class, IdentityMap.createConfiguration()); makeMapReduceString(IdentityMap.class); return this; } /** * Apply the provided closure to the current element and emit the result. * * @param closure the closure to apply to the element * @return the extended HadoopPipeline */ public HadoopPipeline transform(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(TransformMap.Map.class, NullWritable.class, FaunusVertex.class, TransformMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); this.state.lock(); makeMapReduceString(TransformMap.class); return this; } /** * Start a traversal at all vertices in the graph. * * @return the extended HadoopPipeline */ public HadoopPipeline V() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Vertex.class); this.compiler.addMap(VerticesMap.Map.class, NullWritable.class, FaunusVertex.class, VerticesMap.createConfiguration(this.state.incrStep() != 0)); makeMapReduceString(VerticesMap.class); return this; } /** * Start a traversal at all edges in the graph. * * @return the extended HadoopPipeline */ public HadoopPipeline E() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Edge.class); this.compiler.addMap(EdgesMap.Map.class, NullWritable.class, FaunusVertex.class, EdgesMap.createConfiguration(this.state.incrStep() != 0)); makeMapReduceString(EdgesMap.class); return this; } /** * Start a traversal at the vertices identified by the provided ids. * * @param ids the long ids of the vertices to start the traversal from * @return the extended HadoopPipeline */ public HadoopPipeline v(final long... ids) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.set(Vertex.class); this.state.incrStep(); this.compiler.addMap(VertexMap.Map.class, NullWritable.class, FaunusVertex.class, VertexMap.createConfiguration(ids)); makeMapReduceString(VertexMap.class); return this; } /** * Take outgoing labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline out(final String... labels) { return this.inOutBoth(OUT, labels); } /** * Take incoming labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline in(final String... labels) { return this.inOutBoth(IN, labels); } /** * Take both incoming and outgoing labeled edges to adjacent vertices. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline both(final String... labels) { return this.inOutBoth(BOTH, labels); } private HadoopPipeline inOutBoth(final Direction direction, final String... labels) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.state.incrStep(); this.compiler.addMapReduce(VerticesVerticesMapReduce.Map.class, null, VerticesVerticesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, VerticesVerticesMapReduce.createConfiguration(direction, labels)); this.state.set(Vertex.class); makeMapReduceString(VerticesVerticesMapReduce.class, direction.name(), Arrays.asList(labels)); return this; } /** * Take outgoing labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline outE(final String... labels) { return this.inOutBothE(OUT, labels); } /** * Take incoming labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline inE(final String... labels) { return this.inOutBothE(IN, labels); } /** * Take both incoming and outgoing labeled edges to incident edges. * * @param labels the labels of the edges to traverse over * @return the extended HadoopPipeline */ public HadoopPipeline bothE(final String... labels) { return this.inOutBothE(BOTH, labels); } private HadoopPipeline inOutBothE(final Direction direction, final String... labels) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.state.incrStep(); this.compiler.addMapReduce(VerticesEdgesMapReduce.Map.class, null, VerticesEdgesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, VerticesEdgesMapReduce.createConfiguration(direction, labels)); this.state.set(Edge.class); makeMapReduceString(VerticesEdgesMapReduce.class, direction.name(), Arrays.asList(labels)); return this; } /** * Go to the outgoing/tail vertex of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline outV() { return this.inOutBothV(OUT); } /** * Go to the incoming/head vertex of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline inV() { return this.inOutBothV(IN); } /** * Go to both the incoming/head and outgoing/tail vertices of the edge. * * @return the extended HadoopPipeline */ public HadoopPipeline bothV() { return this.inOutBothV(BOTH); } private HadoopPipeline inOutBothV(final Direction direction) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtEdge(); this.state.incrStep(); this.compiler.addMap(EdgesVerticesMap.Map.class, NullWritable.class, FaunusVertex.class, EdgesVerticesMap.createConfiguration(direction)); this.state.set(Vertex.class); makeMapReduceString(EdgesVerticesMap.class, direction.name()); return this; } /** * Emit the property value of an element. * * @param key the key identifying the property * @param type the class of the property value (so Hadoop can intelligently handle the result) * @return the extended HadoopPipeline */ public HadoopPipeline property(final String key, final Class type) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.setProperty(key, type); return this; } /** * Emit the property value of an element. * * @param key the key identifying the property * @return the extended HadoopPipeline */ public HadoopPipeline property(final String key) { return this.property(key, String.class); } /** * Emit a string representation of the property map. * * @return the extended HadoopPipeline */ public HadoopPipeline map() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PropertyMapMap.Map.class, LongWritable.class, Text.class, PropertyMapMap.createConfiguration(this.state.getElementType())); makeMapReduceString(PropertyMap.class); this.state.lock(); return this; } /** * Emit the label of the current edge. * * @return the extended HadoopPipeline */ public HadoopPipeline label() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtEdge(); this.property(Tokens.LABEL, String.class); return this; } /** * Emit the path taken from start to current element. * * @return the extended HadoopPipeline */ public HadoopPipeline path() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PathMap.Map.class, NullWritable.class, Text.class, PathMap.createConfiguration(this.state.getElementType())); this.state.lock(); makeMapReduceString(PathMap.class); return this; } /** * Order the previous property value results and emit them with another element property value. * It is important to emit the previous property with a provided type else it is ordered lexigraphically. * * @param order increasing and descending order * @param elementKey the key of the element to associate it with * @return the extended HadoopPipeline */ public HadoopPipeline order(final TransformPipe.Order order, final String elementKey) { this.state.assertNotLocked(); final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null != pair) { this.compiler.addMapReduce(OrderMapReduce.Map.class, null, OrderMapReduce.Reduce.class, OrderMapReduce.createComparator(order, pair.getB()), pair.getB(), Text.class, Text.class, pair.getB(), OrderMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB(), elementKey)); makeMapReduceString(OrderMapReduce.class, order.name(), elementKey); } else { throw new IllegalArgumentException("There is no specified property to order on"); } this.state.lock(); return this; } /** * Order the previous property value results. * * @param order increasing and descending order * @return the extended HadoopPipeline */ public HadoopPipeline order(final TransformPipe.Order order) { return this.order(order, Tokens.ID); } /** * Order the previous property value results and emit them with another element property value. * It is important to emit the previous property with a provided type else it is ordered lexigraphically. * * @param order increasing and descending order * @param elementKey the key of the element to associate it with * @return the extended HadoopPipeline */ public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order, final String elementKey) { return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order), elementKey); } /** * Order the previous property value results. * * @param order increasing and descending order * @return the extended HadoopPipeline */ public HadoopPipeline order(final com.tinkerpop.gremlin.Tokens.T order) { return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order)); } //////// FILTERS /** * Emit or deny the current element based upon the provided boolean-based closure. * * @param closure return true to emit and false to remove. * @return the extended HadoopPipeline */ public HadoopPipeline filter(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(FilterMap.Map.class, NullWritable.class, FaunusVertex.class, FilterMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); makeMapReduceString(FilterMap.class); return this; } /** * Emit the current element if it has a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) { return this.has(key, convert(compare), values); } /** * Emit the current element if it does not have a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator (will be not'd) * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final com.tinkerpop.gremlin.Tokens.T compare, final Object... values) { return this.hasNot(key, convert(compare), values); } /** * Emit the current element if it has a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final Compare compare, final Object... values) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(PropertyFilterMap.Map.class, NullWritable.class, FaunusVertex.class, PropertyFilterMap.createConfiguration(this.state.getElementType(), key, compare, values)); makeMapReduceString(PropertyFilterMap.class, compare.name(), Arrays.asList(values)); return this; } /** * Emit the current element if it does not have a property value comparable to the provided values. * * @param key the property key of the element * @param compare the comparator (will be not'd) * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final Compare compare, final Object... values) { return this.has(key, compare.opposite(), values); } /** * Emit the current element it has a property value equal to the provided values. * * @param key the property key of the element * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline has(final String key, final Object... values) { return (values.length == 0) ? this.has(key, Compare.NOT_EQUAL, new Object[]{null}) : this.has(key, Compare.EQUAL, values); } /** * Emit the current element it does not have a property value equal to the provided values. * * @param key the property key of the element * @param values the values to compare against where only one needs to succeed (or'd) * @return the extended HadoopPipeline */ public HadoopPipeline hasNot(final String key, final Object... values) { return (values.length == 0) ? this.has(key, Compare.EQUAL, new Object[]{null}) : this.has(key, Compare.NOT_EQUAL, values); } /** * Emit the current element it has a property value equal within the provided range. * * @param key the property key of the element * @param startValue the start of the range (inclusive) * @param endValue the end of the range (exclusive) * @return the extended HadoopPipeline */ public HadoopPipeline interval(final String key, final Object startValue, final Object endValue) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(IntervalFilterMap.Map.class, NullWritable.class, FaunusVertex.class, IntervalFilterMap.createConfiguration(this.state.getElementType(), key, startValue, endValue)); makeMapReduceString(IntervalFilterMap.class, key, startValue, endValue); return this; } /** * Remove any duplicate traversers at a single element. * * @return the extended HadoopPipeline */ public HadoopPipeline dedup() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(DuplicateFilterMap.Map.class, NullWritable.class, FaunusVertex.class, DuplicateFilterMap.createConfiguration(this.state.getElementType())); makeMapReduceString(DuplicateFilterMap.class); return this; } /** * Go back to an element a named step ago. * Currently only backing up to vertices is supported. * * @param step the name of the step to back up to * @return the extended HadoopPipeline */ public HadoopPipeline back(final String step) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMapReduce(BackFilterMapReduce.Map.class, BackFilterMapReduce.Combiner.class, BackFilterMapReduce.Reduce.class, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, BackFilterMapReduce.createConfiguration(this.state.getElementType(), this.state.getStep(step))); makeMapReduceString(BackFilterMapReduce.class, step); return this; } /*public HadoopPipeline back(final int numberOfSteps) { this.state.assertNotLocked(); this.compiler.backFilterMapReduce(this.state.getElementType(), this.state.getStep() - numberOfSteps); this.compiler.setPathEnabled(true); makeMapReduceString(BackFilterMapReduce.class, numberOfSteps); return this; }*/ /** * Emit the element only if it was arrived at via a path that does not have cycles in it. * * @return the extended HadoopPipeline */ public HadoopPipeline simplePath() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(CyclicPathFilterMap.Map.class, NullWritable.class, FaunusVertex.class, CyclicPathFilterMap.createConfiguration(this.state.getElementType())); makeMapReduceString(CyclicPathFilterMap.class); return this; } //////// SIDEEFFECTS /** * Emit the element, but compute some sideeffect in the process. * For example, mutate the properties of the element. * * @param closure the sideeffect closure whose results are ignored. * @return the extended HadoopPipeline */ public HadoopPipeline sideEffect(final String closure) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(SideEffectMap.Map.class, NullWritable.class, FaunusVertex.class, SideEffectMap.createConfiguration(this.state.getElementType(), this.validateClosure(closure))); makeMapReduceString(SideEffectMap.class); return this; } /** * Name a step in order to reference it later in the expression. * * @param name the string representation of the name * @return the extended HadoopPipeline */ public HadoopPipeline as(final String name) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.addStep(name); final String string = "As(" + name + "," + this.stringRepresentation.get(this.state.getStep(name)) + ")"; this.stringRepresentation.set(this.state.getStep(name), string); return this; } /** * Have the elements for the named step previous project an edge to the current vertex with provided label. * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight. * No weight key is specified by "_" and then all duplicates are merged, but no weight is added to the resultant edge. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @param mergeWeightKey the property key to use for weight * @return the extended HadoopPipeline */ public HadoopPipeline linkIn(final String label, final String step, final String mergeWeightKey) { return this.link(IN, label, step, mergeWeightKey); } /** * Have the elements for the named step previous project an edge to the current vertex with provided label. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @return the extended HadoopPipeline */ public HadoopPipeline linkIn(final String label, final String step) { return this.link(IN, label, step, null); } /** * Have the elements for the named step previous project an edge from the current vertex with provided label. * If a merge weight key is provided, then count the number of duplicate edges between the same two vertices and add a weight. * No weight key is specified by "_" and then all duplicates are merged, but no weight is added to the resultant edge. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @param mergeWeightKey the property key to use for weight * @return the extended HadoopPipeline */ public HadoopPipeline linkOut(final String label, final String step, final String mergeWeightKey) { return link(OUT, label, step, mergeWeightKey); } /** * Have the elements for the named step previous project an edge from the current vertex with provided label. * * @param step the name of the step where the source vertices were * @param label the label of the edge to project * @return the extended HadoopPipeline */ public HadoopPipeline linkOut(final String label, final String step) { return this.link(OUT, label, step, null); } private HadoopPipeline link(final Direction direction, final String label, final String step, final String mergeWeightKey) { this.state.assertNotLocked(); this.state.assertNoProperty(); Preconditions.checkNotNull(direction); this.compiler.addMapReduce(LinkMapReduce.Map.class, LinkMapReduce.Combiner.class, LinkMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, LinkMapReduce.createConfiguration(direction, label, this.state.getStep(step), mergeWeightKey)); log.debug("Added {} job with direction {}, label {}, step {}, merge weight key {}", LinkMapReduce.class.getSimpleName(), direction, label, step, mergeWeightKey); if (null != mergeWeightKey) makeMapReduceString(LinkMapReduce.class, direction.name(), label, step, mergeWeightKey); else makeMapReduceString(LinkMapReduce.class, direction.name(), label, step); return this; } /** * Count the number of times the previous element (or property) has been traversed to. * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount() { this.state.assertNotLocked(); final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null == pair) { return this.groupCount(null, null); } else { this.compiler.addMapReduce(ValueGroupCountMapReduce.Map.class, ValueGroupCountMapReduce.Combiner.class, ValueGroupCountMapReduce.Reduce.class, pair.getB(), LongWritable.class, pair.getB(), LongWritable.class, ValueGroupCountMapReduce.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB())); makeMapReduceString(ValueGroupCountMapReduce.class, pair.getA()); } return this; } /** * Apply the provided closure to the incoming element to determine the grouping key. * The value of the count is incremented by 1 * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount(final String keyClosure) { return this.groupCount(keyClosure, null); } /** * Apply the provided closure to the incoming element to determine the grouping key. * Then apply the value closure to the current element to determine the count increment. * The results are stored in the jobs sideeffect file in HDFS. * * @return the extended HadoopPipeline. */ public HadoopPipeline groupCount(final String keyClosure, final String valueClosure) { this.state.assertNotLocked(); this.compiler.addMapReduce(GroupCountMapReduce.Map.class, GroupCountMapReduce.Combiner.class, GroupCountMapReduce.Reduce.class, Text.class, LongWritable.class, Text.class, LongWritable.class, GroupCountMapReduce.createConfiguration(this.state.getElementType(), this.validateClosure(keyClosure), this.validateClosure(valueClosure))); makeMapReduceString(GroupCountMapReduce.class); return this; } private HadoopPipeline commit(final Tokens.Action action) { this.state.assertNotLocked(); this.state.assertNoProperty(); if (this.state.atVertex()) { this.compiler.addMapReduce(CommitVerticesMapReduce.Map.class, CommitVerticesMapReduce.Combiner.class, CommitVerticesMapReduce.Reduce.class, null, LongWritable.class, Holder.class, NullWritable.class, FaunusVertex.class, CommitVerticesMapReduce.createConfiguration(action)); makeMapReduceString(CommitVerticesMapReduce.class, action.name()); } else { this.compiler.addMap(CommitEdgesMap.Map.class, NullWritable.class, FaunusVertex.class, CommitEdgesMap.createConfiguration(action)); makeMapReduceString(CommitEdgesMap.class, action.name()); } return this; } /** * Drop all the elements of respective type at the current step. Keep all others. * * @return the extended HadoopPipeline */ public HadoopPipeline drop() { return this.commit(Tokens.Action.DROP); } /** * Keep all the elements of the respetive type at the current step. Drop all others. * * @return the extended HadoopPipeline */ public HadoopPipeline keep() { return this.commit(Tokens.Action.KEEP); } public HadoopPipeline script(final String scriptUri, final String... args) { this.state.assertNotLocked(); this.state.assertNoProperty(); this.state.assertAtVertex(); this.compiler.addMap(ScriptMap.Map.class, NullWritable.class, FaunusVertex.class, ScriptMap.createConfiguration(scriptUri, args)); makeMapReduceString(CommitEdgesMap.class, scriptUri); // this.state.lock(); return this; } /////////////// UTILITIES /** * Count the number of traversers currently in the graph * * @return the count */ public HadoopPipeline count() { this.state.assertNotLocked(); this.compiler.addMapReduce(CountMapReduce.Map.class, CountMapReduce.Combiner.class, CountMapReduce.Reduce.class, NullWritable.class, LongWritable.class, NullWritable.class, LongWritable.class, CountMapReduce.createConfiguration(this.state.getElementType())); makeMapReduceString(CountMapReduce.class); this.state.lock(); return this; } public String toString() { return this.stringRepresentation.toString(); } private HadoopPipeline done() { if (!this.state.isLocked()) { final Pair<String, Class<? extends WritableComparable>> pair = this.state.popProperty(); if (null != pair) { this.compiler.addMap(PropertyMap.Map.class, LongWritable.class, pair.getB(), PropertyMap.createConfiguration(this.state.getElementType(), pair.getA(), pair.getB())); makeMapReduceString(PropertyMap.class, pair.getA()); this.state.lock(); } } return this; } /** * Submit the HadoopPipeline to the Hadoop cluster. * * @throws Exception */ public void submit() throws Exception { submit(Tokens.EMPTY_STRING, false); } /** * Submit the HadoopPipeline to the Hadoop cluster and ensure that a header is emitted in the logs. * * @param script the Gremlin script * @param showHeader the Titan/Hadoop header * @throws Exception */ public void submit(final String script, final Boolean showHeader) throws Exception { this.done(); if (MapReduceFormat.class.isAssignableFrom(this.graph.getGraphOutputFormat())) { this.state.assertNotLocked(); ((Class<? extends MapReduceFormat>) this.graph.getGraphOutputFormat()).getConstructor().newInstance().addMapReduceJobs(this.compiler); } this.compiler.completeSequence(); ToolRunner.run(this.compiler, new String[]{script, showHeader.toString()}); } /** * Get a reference to the graph currently being used in this HadoopPipeline. * * @return the HadoopGraph */ public HadoopGraph getGraph() { return this.graph; } public HadoopCompiler getCompiler() { return this.compiler; } private String validateClosure(String closure) { if (closure == null) return null; try { engine.eval(closure); return closure; } catch (ScriptException e) { closure = closure.trim(); closure = closure.replaceFirst("\\{", "{it->"); try { engine.eval(closure); return closure; } catch (ScriptException e1) { } throw new IllegalArgumentException("The provided closure does not compile: " + e.getMessage(), e); } } private void makeMapReduceString(final Class klass, final Object... arguments) { String result = klass.getSimpleName(); if (arguments.length > 0) { result = result + "("; for (final Object arg : arguments) { result = result + arg + ","; } result = result.substring(0, result.length() - 1) + ")"; } this.stringRepresentation.add(result); } private Class<? extends WritableComparable> convertJavaToHadoop(final Class klass) { if (klass.equals(String.class)) { return Text.class; } else if (klass.equals(Integer.class)) { return IntWritable.class; } else if (klass.equals(Double.class)) { return DoubleWritable.class; } else if (klass.equals(Long.class)) { return LongWritable.class; } else if (klass.equals(Float.class)) { return FloatWritable.class; } else if (klass.equals(Boolean.class)) { return BooleanWritable.class; } else { throw new IllegalArgumentException("The provided class is not supported: " + klass.getSimpleName()); } } }
Making HadoopPipeline.submit return Tool status This submit method is a thin wrapper around ToolRunner.run. ToolRunner.run returns the integer exit status produced by the Tool implementation it executes. Prior to this commit, submit returned void and threw the status away. Now the status is returned from submit. This change is groundwork for a new integration test method related to #806 and #826 that will submit a HadoopPipeline that submits a typical graphson-to-sequencefile dump job and needs to know whether the job succeeded.
titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/HadoopPipeline.java
Making HadoopPipeline.submit return Tool status
Java
apache-2.0
eb134def7c2d629a4fec3b507e45cdefaf204421
0
willkara/sakai,willkara/sakai,frasese/sakai,Fudan-University/sakai,Fudan-University/sakai,OpenCollabZA/sakai,willkara/sakai,frasese/sakai,frasese/sakai,ouit0408/sakai,frasese/sakai,frasese/sakai,OpenCollabZA/sakai,willkara/sakai,ouit0408/sakai,ouit0408/sakai,willkara/sakai,OpenCollabZA/sakai,frasese/sakai,OpenCollabZA/sakai,Fudan-University/sakai,frasese/sakai,willkara/sakai,OpenCollabZA/sakai,ouit0408/sakai,Fudan-University/sakai,ouit0408/sakai,OpenCollabZA/sakai,ouit0408/sakai,OpenCollabZA/sakai,ouit0408/sakai,Fudan-University/sakai,ouit0408/sakai,willkara/sakai,Fudan-University/sakai,OpenCollabZA/sakai,Fudan-University/sakai,willkara/sakai,frasese/sakai,Fudan-University/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.portal.service; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.api.AliasService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.PortalService; import org.sakaiproject.portal.api.SiteNeighbourhoodService; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.tool.api.Session; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.user.api.PreferencesService; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; /** * @author ieb */ public class SiteNeighbourhoodServiceImpl implements SiteNeighbourhoodService { private static final String SITE_ALIAS = "/sitealias/"; private static final Logger log = LoggerFactory.getLogger(SiteNeighbourhoodServiceImpl.class); private SiteService siteService; private PreferencesService preferencesService; private UserDirectoryService userDirectoryService; private ServerConfigurationService serverConfigurationService; private AliasService aliasService; private ThreadLocalManager threadLocalManager; /** Should all site aliases have a prefix */ private boolean useAliasPrefix = false; private boolean useSiteAliases = false; public void init() { useSiteAliases = serverConfigurationService.getBoolean("portal.use.site.aliases", false); } public void destroy() { } /* * (non-Javadoc) * * @see org.sakaiproject.portal.api.SiteNeighbourhoodService#getSitesAtNode(javax.servlet.http.HttpServletRequest, * org.sakaiproject.tool.api.Session, boolean) */ public List<Site> getSitesAtNode(HttpServletRequest request, Session session, boolean includeMyWorkspace) { return getAllSites(request, session, includeMyWorkspace); } /** * Get All Sites for the current user. If the user is not logged in we * return the list of publically viewable gateway sites. * * @param includeMyWorkspace * When this is true - include the user's My Workspace as the first * parameter. If false, do not include the MyWorkspace anywhere in * the list. Some uses - such as the portlet styled portal or the rss * styled portal simply want all of the sites with the MyWorkspace * first. Other portals like the basic tabbed portal treats My * Workspace separately from all of the rest of the workspaces. * @see org.sakaiproject.portal.api.PortalSiteHelper#getAllSites(javax.servlet.http.HttpServletRequest, * org.sakaiproject.tool.api.Session, boolean) */ public List<Site> getAllSites(HttpServletRequest req, Session session, boolean includeMyWorkspace) { boolean loggedIn = session.getUserId() != null; List<Site> mySites; // collect the Publically Viewable Sites if (!loggedIn) { mySites = getGatewaySites(); return mySites; } // collect the user's sites - don't care whether long descriptions are loaded mySites = siteService.getUserSites(false); // collect the user's preferences List prefExclude = new ArrayList(); List prefOrder = new ArrayList(); if (session.getUserId() != null) { Preferences prefs = preferencesService.getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); List l = props.getPropertyList("exclude"); if (l != null) { prefExclude = l; } l = props.getPropertyList("order"); if (l != null) { prefOrder = l; } } // remove all in exclude from mySites List<Site> visibleSites = new ArrayList<Site>(); for (Site site: mySites) { if ( ! prefExclude.contains(site.getId())) { visibleSites.add(site); } } mySites = visibleSites; // Prepare to put sites in the right order Vector<Site> ordered = new Vector<Site>(); Set<String> added = new HashSet<String>(); // First, place or remove MyWorkspace as requested Site myWorkspace = getMyWorkspace(session); if (myWorkspace != null) { if (includeMyWorkspace) { ordered.add(myWorkspace); added.add(myWorkspace.getId()); } else { int pos = listIndexOf(myWorkspace.getId(), mySites); if (pos != -1) mySites.remove(pos); } } // re-order mySites to have order first, the rest later for (Iterator i = prefOrder.iterator(); i.hasNext();) { String id = (String) i.next(); // find this site in the mySites list int pos = listIndexOf(id, mySites); if (pos != -1) { Site s = mySites.get(pos); if (!added.contains(s.getId())) { ordered.add(s); added.add(s.getId()); } } } // We only do the child processing if we have less than 200 sites boolean haveChildren = false; int siteCount = mySites.size(); // pick up the rest of the top-level-sites for (int i = 0; i < mySites.size(); i++) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; // Once the user takes over the order, // ignore parent/child sorting put all the sites // at the top String ourParent = null; if ( prefOrder.size() == 0 ) { ResourceProperties rp = s.getProperties(); ourParent = rp.getProperty(SiteService.PROP_PARENT_ID); } // System.out.println("Top Site:"+s.getTitle()+" // parent="+ourParent); if (siteCount > 200 || ourParent == null) { // System.out.println("Added at root"); ordered.add(s); added.add(s.getId()); } else { haveChildren = true; } } // If and only if we have some child nodes, we repeatedly // pull up children nodes to be behind their parents // This is O N**2 - so if we had thousands of sites it // it would be costly - hence we only do it for < 200 sites // and limited depth - that makes it O(N) not O(N**2) boolean addedSites = true; int depth = 0; while (depth < 20 && addedSites && haveChildren) { depth++; addedSites = false; haveChildren = false; for (int i = mySites.size() - 1; i >= 0; i--) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; ResourceProperties rp = s.getProperties(); String ourParent = rp.getProperty(SiteService.PROP_PARENT_ID); if (ourParent == null) continue; haveChildren = true; // System.out.println("Child Site:"+s.getTitle()+ // "parent="+ourParent); // Search the already added pages for a parent // or sibling node boolean found = false; int j = -1; for (j = ordered.size() - 1; j >= 0; j--) { Site ps = ordered.get(j); // See if this site is our parent if (ourParent.equals(ps.getId())) { found = true; break; } // See if this site is our sibling rp = ps.getProperties(); String peerParent = rp.getProperty(SiteService.PROP_PARENT_ID); if (ourParent.equals(peerParent)) { found = true; break; } } // We want to insert *after* the identified node j = j + 1; if (found && j >= 0 && j < ordered.size()) { // System.out.println("Added after parent"); ordered.insertElementAt(s, j); added.add(s.getId()); addedSites = true; // Worth going another level deeper } } } // End while depth // If we still have children drop them at the end if (haveChildren) for (int i = 0; i < mySites.size(); i++) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; // System.out.println("Orphan Site:"+s.getId()+" "+s.getTitle()); ordered.add(s); } // All done mySites = ordered; return mySites; } // Get the sites which are to be displayed for the gateway /** * @return */ private List<Site> getGatewaySites() { List<Site> mySites = new ArrayList<Site>(); String[] gatewaySiteIds = getGatewaySiteList(); if (gatewaySiteIds == null) { return mySites; // An empty list - deal with this higher up in the // food chain } // Loop throught the sites making sure they exist and are visitable for (int i = 0; i < gatewaySiteIds.length; i++) { String siteId = gatewaySiteIds[i]; Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { continue; } catch (PermissionException e) { continue; } if (site != null) { mySites.add(site); } } if (mySites.size() < 1) { log.warn("No suitable gateway sites found, gatewaySiteList preference had " + gatewaySiteIds.length + " sites."); } return mySites; } /** * @see org.sakaiproject.portal.api.PortalSiteHelper#getMyWorkspace(org.sakaiproject.tool.api.Session) */ private Site getMyWorkspace(Session session) { String siteId = siteService.getUserSiteId(session.getUserId()); // Make sure we can visit Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { site = null; } catch (PermissionException e) { site = null; } return site; } /** * Find the site in the list that has this id - return the position. * * @param value * The site id to find. * @param siteList * The list of Site objects. * @return The index position in siteList of the site with site id = value, * or -1 if not found. */ private int listIndexOf(String value, List siteList) { for (int i = 0; i < siteList.size(); i++) { Site site = (Site) siteList.get(i); if (site.getId().equals(value)) { return i; } } return -1; } // Return the list of tabs for the anonymous view (Gateway) // If we have a list of sites, return that - if not simply pull in the // single // Gateway site /** * @return */ private String[] getGatewaySiteList() { String gatewaySiteListPref = serverConfigurationService .getString("gatewaySiteList"); if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) { gatewaySiteListPref = serverConfigurationService.getGatewaySiteId(); } if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) return null; String[] gatewaySites = gatewaySiteListPref.split(","); if (gatewaySites.length < 1) return null; return gatewaySites; } /** * Do the getSiteVisit, but if not found and the id is a user site, try * translating from user EID to ID. * * @param siteId * The Site Id. * @return The Site. * @throws PermissionException * If not allowed. * @throws IdUnusedException * If not found. */ public Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException { try { return siteService.getSiteVisit(siteId); } catch (IdUnusedException e) { if (siteService.isUserSite(siteId)) { try { String userEid = siteService.getSiteUserId(siteId); String userId = userDirectoryService.getUserId(userEid); String alternateSiteId = siteService.getUserSiteId(userId); return siteService.getSiteVisit(alternateSiteId); } catch (UserNotDefinedException ee) { } } // re-throw if that didn't work throw e; } } /** * @return the preferencesService */ public PreferencesService getPreferencesService() { return preferencesService; } /** * @param preferencesService * the preferencesService to set */ public void setPreferencesService(PreferencesService preferencesService) { this.preferencesService = preferencesService; } /** * @return the serverConfigurationService */ public ServerConfigurationService getServerConfigurationService() { return serverConfigurationService; } /** * @param serverConfigurationService * the serverConfigurationService to set */ public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } /** * @return the siteService */ public SiteService getSiteService() { return siteService; } /** * @param siteService * the siteService to set */ public void setSiteService(SiteService siteService) { this.siteService = siteService; } /** * @return the userDirectoryService */ public UserDirectoryService getUserDirectoryService() { return userDirectoryService; } /** * @param userDirectoryService * the userDirectoryService to set */ public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } public void setThreadLocalManager(ThreadLocalManager threadLocalManager) { this.threadLocalManager = threadLocalManager; } public String lookupSiteAlias(String id, String context) { // TODO Constant extraction if ("/site/!error".equals(id)) { Object originalId = threadLocalManager.get(PortalService.SAKAI_PORTAL_ORIGINAL_SITEID); if (originalId instanceof String) { return (String)originalId; } } if (!useSiteAliases) { return null; } List<Alias> aliases = aliasService.getAliases(id); if (aliases.size() > 0) { if (aliases.size() > 1 && log.isInfoEnabled()) { if (log.isDebugEnabled()) { log.debug("More than one alias for "+ id+ " sorting."); } Collections.sort(aliases, new Comparator<Alias>() { public int compare(Alias o1, Alias o2) { return o1.getId().compareTo(o2.getId()); } }); } for (Alias alias : aliases) { String aliasId = alias.getId(); boolean startsWithPrefix = aliasId.startsWith(SITE_ALIAS); if (startsWithPrefix) { if (useAliasPrefix) { return aliasId.substring(SITE_ALIAS.length()); } } else { if (!useAliasPrefix) { return aliasId; } } } } return null; } public String parseSiteAlias(String alias) { if (alias == null) { return null; } // Prepend site alias prefix if it's being used. String id = ((useAliasPrefix)?SITE_ALIAS:"")+alias; try { String reference = aliasService.getTarget(id); return reference; } catch (IdUnusedException e) { if (log.isDebugEnabled()) { log.debug("No alias found for "+ id); } } return null; } public void setAliasService(AliasService aliasService) { this.aliasService = aliasService; } public boolean isUseAliasPrefix() { return useAliasPrefix; } public void setUseAliasPrefix(boolean useAliasPrefix) { this.useAliasPrefix = useAliasPrefix; } }
portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/SiteNeighbourhoodServiceImpl.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.portal.service; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.api.AliasService; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.PortalService; import org.sakaiproject.portal.api.SiteNeighbourhoodService; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.tool.api.Session; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.user.api.PreferencesService; import org.sakaiproject.user.api.UserDirectoryService; import org.sakaiproject.user.api.UserNotDefinedException; /** * @author ieb */ public class SiteNeighbourhoodServiceImpl implements SiteNeighbourhoodService { private static final String SITE_ALIAS = "/sitealias/"; private static final Logger log = LoggerFactory.getLogger(SiteNeighbourhoodServiceImpl.class); private SiteService siteService; private PreferencesService preferencesService; private UserDirectoryService userDirectoryService; private ServerConfigurationService serverConfigurationService; private AliasService aliasService; private ThreadLocalManager threadLocalManager; /** Should all site aliases have a prefix */ private boolean useAliasPrefix = false; private boolean useSiteAliases = false; public void init() { useSiteAliases = serverConfigurationService.getBoolean("portal.use.site.aliases", false); } public void destroy() { } /* * (non-Javadoc) * * @see org.sakaiproject.portal.api.SiteNeighbourhoodService#getSitesAtNode(javax.servlet.http.HttpServletRequest, * org.sakaiproject.tool.api.Session, boolean) */ public List<Site> getSitesAtNode(HttpServletRequest request, Session session, boolean includeMyWorkspace) { return getAllSites(request, session, includeMyWorkspace); } /** * Get All Sites for the current user. If the user is not logged in we * return the list of publically viewable gateway sites. * * @param includeMyWorkspace * When this is true - include the user's My Workspace as the first * parameter. If false, do not include the MyWorkspace anywhere in * the list. Some uses - such as the portlet styled portal or the rss * styled portal simply want all of the sites with the MyWorkspace * first. Other portals like the basic tabbed portal treats My * Workspace separately from all of the rest of the workspaces. * @see org.sakaiproject.portal.api.PortalSiteHelper#getAllSites(javax.servlet.http.HttpServletRequest, * org.sakaiproject.tool.api.Session, boolean) */ public List<Site> getAllSites(HttpServletRequest req, Session session, boolean includeMyWorkspace) { boolean loggedIn = session.getUserId() != null; List<Site> mySites; // collect the Publically Viewable Sites if (!loggedIn) { mySites = getGatewaySites(); return mySites; } // collect the user's sites - don't care whether long descriptions are loaded mySites = siteService.getUserSites(false); // collect the user's preferences List prefExclude = new ArrayList(); List prefOrder = new ArrayList(); if (session.getUserId() != null) { Preferences prefs = preferencesService.getPreferences(session.getUserId()); ResourceProperties props = prefs.getProperties("sakai:portal:sitenav"); List l = props.getPropertyList("exclude"); if (l != null) { prefExclude = l; } l = props.getPropertyList("order"); if (l != null) { prefOrder = l; } } // remove all in exclude from mySites List<Site> visibleSites = new ArrayList<Site>(); for (Site site: mySites) { if ( ! prefExclude.contains(site.getId())) { visibleSites.add(site); } } mySites = visibleSites; // Prepare to put sites in the right order Vector<Site> ordered = new Vector<Site>(); Set<String> added = new HashSet<String>(); // First, place or remove MyWorkspace as requested Site myWorkspace = getMyWorkspace(session); if (myWorkspace != null) { if (includeMyWorkspace) { ordered.add(myWorkspace); added.add(myWorkspace.getId()); } else { int pos = listIndexOf(myWorkspace.getId(), mySites); if (pos != -1) mySites.remove(pos); } } // re-order mySites to have order first, the rest later for (Iterator i = prefOrder.iterator(); i.hasNext();) { String id = (String) i.next(); // find this site in the mySites list int pos = listIndexOf(id, mySites); if (pos != -1) { Site s = mySites.get(pos); if (!added.contains(s.getId())) { ordered.add(s); added.add(s.getId()); } } } // We only do the child processing if we have less than 200 sites boolean haveChildren = false; int siteCount = mySites.size(); // pick up the rest of the top-level-sites for (int i = 0; i < mySites.size(); i++) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; // Once the user takes over the order, // ignore parent/child sorting put all the sites // at the top String ourParent = null; if ( prefOrder.size() == 0 ) { ResourceProperties rp = s.getProperties(); ourParent = rp.getProperty(SiteService.PROP_PARENT_ID); } // System.out.println("Top Site:"+s.getTitle()+" // parent="+ourParent); if (siteCount > 200 || ourParent == null) { // System.out.println("Added at root"); ordered.add(s); added.add(s.getId()); } else { haveChildren = true; } } // If and only if we have some child nodes, we repeatedly // pull up children nodes to be behind their parents // This is O N**2 - so if we had thousands of sites it // it would be costly - hence we only do it for < 200 sites // and limited depth - that makes it O(N) not O(N**2) boolean addedSites = true; int depth = 0; while (depth < 20 && addedSites && haveChildren) { depth++; addedSites = false; haveChildren = false; for (int i = mySites.size() - 1; i >= 0; i--) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; ResourceProperties rp = s.getProperties(); String ourParent = rp.getProperty(SiteService.PROP_PARENT_ID); if (ourParent == null) continue; haveChildren = true; // System.out.println("Child Site:"+s.getTitle()+ // "parent="+ourParent); // Search the already added pages for a parent // or sibling node boolean found = false; int j = -1; for (j = ordered.size() - 1; j >= 0; j--) { Site ps = ordered.get(j); // See if this site is our parent if (ourParent.equals(ps.getId())) { found = true; break; } // See if this site is our sibling rp = ps.getProperties(); String peerParent = rp.getProperty(SiteService.PROP_PARENT_ID); if (ourParent.equals(peerParent)) { found = true; break; } } // We want to insert *after* the identified node j = j + 1; if (found && j >= 0 && j < ordered.size()) { // System.out.println("Added after parent"); ordered.insertElementAt(s, j); added.add(s.getId()); addedSites = true; // Worth going another level deeper } } } // End while depth // If we still have children drop them at the end if (haveChildren) for (int i = 0; i < mySites.size(); i++) { Site s = mySites.get(i); if (added.contains(s.getId())) continue; // System.out.println("Orphan Site:"+s.getId()+" "+s.getTitle()); ordered.add(s); } // All done mySites = ordered; return mySites; } // Get the sites which are to be displayed for the gateway /** * @return */ private List<Site> getGatewaySites() { List<Site> mySites = new ArrayList<Site>(); String[] gatewaySiteIds = getGatewaySiteList(); if (gatewaySiteIds == null) { return mySites; // An empty list - deal with this higher up in the // food chain } // Loop throught the sites making sure they exist and are visitable for (int i = 0; i < gatewaySiteIds.length; i++) { String siteId = gatewaySiteIds[i]; Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { continue; } catch (PermissionException e) { continue; } if (site != null) { mySites.add(site); } } if (mySites.size() < 1) { log.warn("No suitable gateway sites found, gatewaySiteList preference had " + gatewaySiteIds.length + " sites."); } return mySites; } /** * @see org.sakaiproject.portal.api.PortalSiteHelper#getMyWorkspace(org.sakaiproject.tool.api.Session) */ private Site getMyWorkspace(Session session) { String siteId = siteService.getUserSiteId(session.getUserId()); // Make sure we can visit Site site = null; try { site = getSiteVisit(siteId); } catch (IdUnusedException e) { site = null; } catch (PermissionException e) { site = null; } return site; } /** * Find the site in the list that has this id - return the position. * * @param value * The site id to find. * @param siteList * The list of Site objects. * @return The index position in siteList of the site with site id = value, * or -1 if not found. */ private int listIndexOf(String value, List siteList) { for (int i = 0; i < siteList.size(); i++) { Site site = (Site) siteList.get(i); if (site.getId().equals(value)) { return i; } } return -1; } // Return the list of tabs for the anonymous view (Gateway) // If we have a list of sites, return that - if not simply pull in the // single // Gateway site /** * @return */ private String[] getGatewaySiteList() { String gatewaySiteListPref = serverConfigurationService .getString("gatewaySiteList"); if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) { gatewaySiteListPref = serverConfigurationService.getGatewaySiteId(); } if (gatewaySiteListPref == null || gatewaySiteListPref.trim().length() < 1) return null; String[] gatewaySites = gatewaySiteListPref.split(","); if (gatewaySites.length < 1) return null; return gatewaySites; } /** * Do the getSiteVisit, but if not found and the id is a user site, try * translating from user EID to ID. * * @param siteId * The Site Id. * @return The Site. * @throws PermissionException * If not allowed. * @throws IdUnusedException * If not found. */ public Site getSiteVisit(String siteId) throws PermissionException, IdUnusedException { try { return siteService.getSiteVisit(siteId); } catch (IdUnusedException e) { if (siteService.isUserSite(siteId)) { try { String userEid = siteService.getSiteUserId(siteId); String userId = userDirectoryService.getUserId(userEid); String alternateSiteId = siteService.getUserSiteId(userId); return siteService.getSiteVisit(alternateSiteId); } catch (UserNotDefinedException ee) { } } // re-throw if that didn't work throw e; } } /** * @return the preferencesService */ public PreferencesService getPreferencesService() { return preferencesService; } /** * @param preferencesService * the preferencesService to set */ public void setPreferencesService(PreferencesService preferencesService) { this.preferencesService = preferencesService; } /** * @return the serverConfigurationService */ public ServerConfigurationService getServerConfigurationService() { return serverConfigurationService; } /** * @param serverConfigurationService * the serverConfigurationService to set */ public void setServerConfigurationService( ServerConfigurationService serverConfigurationService) { this.serverConfigurationService = serverConfigurationService; } /** * @return the siteService */ public SiteService getSiteService() { return siteService; } /** * @param siteService * the siteService to set */ public void setSiteService(SiteService siteService) { this.siteService = siteService; } /** * @return the userDirectoryService */ public UserDirectoryService getUserDirectoryService() { return userDirectoryService; } /** * @param userDirectoryService * the userDirectoryService to set */ public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } public void setThreadLocalManager(ThreadLocalManager threadLocalManager) { this.threadLocalManager = threadLocalManager; } public String lookupSiteAlias(String id, String context) { // TODO Constant extraction if ("/site/!error".equals(id)) { Object originalId = threadLocalManager.get(PortalService.SAKAI_PORTAL_ORIGINAL_SITEID); if (originalId instanceof String) { return (String)originalId; } } List<Alias> aliases = aliasService.getAliases(id); if (!useSiteAliases) { return null; } if (aliases.size() > 0) { if (aliases.size() > 1 && log.isInfoEnabled()) { if (log.isDebugEnabled()) { log.debug("More than one alias for "+ id+ " sorting."); } Collections.sort(aliases, new Comparator<Alias>() { public int compare(Alias o1, Alias o2) { return o1.getId().compareTo(o2.getId()); } }); } for (Alias alias : aliases) { String aliasId = alias.getId(); boolean startsWithPrefix = aliasId.startsWith(SITE_ALIAS); if (startsWithPrefix) { if (useAliasPrefix) { return aliasId.substring(SITE_ALIAS.length()); } } else { if (!useAliasPrefix) { return aliasId; } } } } return null; } public String parseSiteAlias(String alias) { if (alias == null) { return null; } // Prepend site alias prefix if it's being used. String id = ((useAliasPrefix)?SITE_ALIAS:"")+alias; try { String reference = aliasService.getTarget(id); return reference; } catch (IdUnusedException e) { if (log.isDebugEnabled()) { log.debug("No alias found for "+ id); } } return null; } public void setAliasService(AliasService aliasService) { this.aliasService = aliasService; } public boolean isUseAliasPrefix() { return useAliasPrefix; } public void setUseAliasPrefix(boolean useAliasPrefix) { this.useAliasPrefix = useAliasPrefix; } }
SAK-31670 When aliases disabled don’t query DB. (#3185) If aliases are disabled we would still look in the DB for any aliases. This is wrong and we should only be looking when aliases are enabled.
portal/portal-service-impl/impl/src/java/org/sakaiproject/portal/service/SiteNeighbourhoodServiceImpl.java
SAK-31670 When aliases disabled don’t query DB. (#3185)
Java
apache-2.0
a6c881f8c42433b49eb378881b9bdd63a1a52202
0
apache/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs,mohanaraosv/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs
/* * 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.commons.jcs.jcache; import org.junit.Test; import javax.cache.annotation.BeanProvider; import java.util.Iterator; import java.util.ServiceLoader; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; // useless test but without it we are not sure // CDI TCKs passed public class EnsureCDIIsTestedWhenTCKsRunTest { @Test public void checkOWBProvider() { try { final Iterator<BeanProvider> iterator = ServiceLoader.load(BeanProvider.class).iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), instanceOf(OWBBeanProvider.class)); } catch (java.lang.UnsupportedClassVersionError e) { System.err.println("Ignoring checkOWBProvider test failure on " + System.getProperty("java.version")); } } }
commons-jcs-tck-tests/src/test/java/org/apache/commons/jcs/jcache/EnsureCDIIsTestedWhenTCKsRunTest.java
/* * 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.commons.jcs.jcache; import org.junit.Test; import javax.cache.annotation.BeanProvider; import java.util.Iterator; import java.util.ServiceLoader; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; // useless test but without it we are not sure // CDI TCKs passed public class EnsureCDIIsTestedWhenTCKsRunTest { @Test public void checkOWBProvider() { final Iterator<BeanProvider> iterator = ServiceLoader.load(BeanProvider.class).iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), instanceOf(OWBBeanProvider.class)); } }
JCS-132 EnsureCDIIsTestedWhenTCKsRunTest fails on Java 1.6 git-svn-id: fd52ae19693b7be904def34076a5ebbd6e132215@1632295 13f79535-47bb-0310-9956-ffa450edef68
commons-jcs-tck-tests/src/test/java/org/apache/commons/jcs/jcache/EnsureCDIIsTestedWhenTCKsRunTest.java
JCS-132 EnsureCDIIsTestedWhenTCKsRunTest fails on Java 1.6
Java
apache-2.0
ab558f105adf48c895400c154e3ee5dec966ab47
0
sangramjadhav/testrs
2270c6b8-2ece-11e5-905b-74de2bd44bed
hello.java
22703716-2ece-11e5-905b-74de2bd44bed
2270c6b8-2ece-11e5-905b-74de2bd44bed
hello.java
2270c6b8-2ece-11e5-905b-74de2bd44bed
Java
apache-2.0
0c5c7644972757fea8db0821fd69e62891f7d7ae
0
klehmann/domino-jna
package com.mindoo.domino.jna.formula; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import com.mindoo.domino.jna.IAdaptable; import com.mindoo.domino.jna.NotesItem; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesTimeDate; import com.mindoo.domino.jna.constants.FormulaAttributes; import com.mindoo.domino.jna.errors.FormulaCompilationError; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.errors.UnsupportedItemValueError; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.ItemDecoder; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMCMDSPROC; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMFUNCPROC; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMCMDSPROCWin32; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMFUNCPROCWin32; import com.mindoo.domino.jna.internal.handles.DHANDLE; import com.mindoo.domino.jna.internal.handles.DHANDLE32; import com.mindoo.domino.jna.internal.handles.DHANDLE64; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.PlatformUtils; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * Utility class to execute a Domino formula on one or more {@link NotesNote} objects.<br> * <br> * The implementation supports more than the usual 64K of return value, e.g. to use * <code>@DBColumn</code> to read the column values in views with many entries. * * @author Karsten Lehmann */ public class FormulaExecution implements IRecyclableNotesObject, IAdaptable { public enum Disallow { /** Setting of environment variables */ SETENVIRONMENT(NotesConstants.COMPUTE_CAPABILITY_SETENVIRONMENT), /** Commands like @Prompt */ UICOMMANDS(NotesConstants.COMPUTE_CAPABILITY_UICOMMANDS), /** FIELD Foo := */ ASSIGN(NotesConstants.COMPUTE_CAPABILITY_ASSIGN), /** @SetDocField, @DocMark. */ SIDEEFFECTS(NotesConstants.COMPUTE_CAPABILITY_SIDEEFFECTS), /** Any compute extension. */ EXTENSION(NotesConstants.COMPUTE_CAPABILITY_EXTENSION), /** Any compute extension with side-effects */ UNSAFE_EXTENSION(NotesConstants.COMPUTE_CAPABILITY_UNSAFE_EXTENSION), /** Built-in compute extensions */ FALLBACK_EXT(NotesConstants.COMPUTE_CAPABILITY_FALLBACK_EXT), /** Unsafe is any @func that creates/modifies anything (i.e. not "read only") */ UNSAFE(NotesConstants.COMPUTE_CAPABILITY_UNSAFE); private final int m_value; private Disallow(int value) { m_value = value; } public int getValue() { return m_value; } } private String m_formula; private long m_hFormula64; private long m_hCompute64; private int m_hFormula32; private int m_hCompute32; private int m_compiledFormulaLength; private Pointer m_ptrCompiledFormula; private Boolean m_preferNotesTimeDates; private Set<Disallow> m_disallowedActions = new HashSet<>(); /** * Creates a new instance. The constructure compiles the formula and throws a {@link FormulaCompilationError}, * if there are any compilation errors * * @param formula formula * @throws FormulaCompilationError if formula has wrong syntax */ public FormulaExecution(String formula) throws FormulaCompilationError { m_formula = formula; Memory formulaName = null; short formulaNameLength = 0; Memory formulaText = NotesStringUtils.toLMBCS(formula, false, false); short formulaTextLength = (short) formulaText.size(); short computeFlags = 0; if (PlatformUtils.is64Bit()) { m_hFormula64 = 0; LongByReference rethFormula = new LongByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI64.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula64 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); LongByReference rethCompute = new LongByReference(); m_ptrCompiledFormula = Mem64.OSLockObject(m_hFormula64); result = NotesNativeAPI64.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute64 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } else { m_hFormula32 = 0; IntByReference rethFormula = new IntByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI32.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula32 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); IntByReference rethCompute = new IntByReference(); m_ptrCompiledFormula = Mem32.OSLockObject(m_hFormula32); result = NotesNativeAPI32.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute32 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } } @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> clazz) { checkHandle(); if (clazz == byte[].class) { //return compiled formula as byte array byte[] compiledFormula = m_ptrCompiledFormula.getByteArray(0, m_compiledFormulaLength); return (T) compiledFormula; } return null; } public String getFormula() { return m_formula; } /** * Sets whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @param b true to prefer NotesTimeDate (false by default) * @return this instance */ public FormulaExecution setPreferNotesTimeDates(boolean b) { m_preferNotesTimeDates = b; return this; } /** * Returns whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @return true to prefer NotesTimeDate */ public boolean isPreferNotesTimeDates() { if (m_preferNotesTimeDates==null) { return NotesGC.isPreferNotesTimeDate(); } return m_preferNotesTimeDates.booleanValue(); } /** * Blocks execution of certain unsafe actions * * @param val action * @return this instance */ public FormulaExecution disallow(Disallow val) { m_disallowedActions.add(val); return this; } public boolean isDisallowed(Disallow val) { return m_disallowedActions.contains(val); } public String toString() { if (isRecycled()) { return "Compiled formula [recycled, formula="+m_formula+"]"; } else { return "Compiled formula [formula="+m_formula+"]"; } } /** * Convenience method to execute a formula on a single note and return the result as a string.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result as string; if the formula returns a list, we pick the first value * @throws FormulaCompilationError if formula has wrong syntax */ public static String evaluateAsString(String formula, NotesNote note) throws FormulaCompilationError { List<Object> result = evaluate(formula, note); if (result.isEmpty()) return ""; else { return result.get(0).toString(); } } /** * Convenience method to execute a formula on a single note.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static List<Object> evaluate(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { List<Object> result = instance.evaluate(note); return result; } finally { instance.recycle(); } } /** * Convenience method to execute a formula on a single note. Provides extended information.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static FormulaExecutionResult evaluateExt(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { FormulaExecutionResult result = instance.evaluateExt(note); return result; } finally { instance.recycle(); } } private void checkHandle() { if (PlatformUtils.is64Bit()) { if (m_hCompute64==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula64==0) { throw new NotesError(0, "Object already recycled"); } } else { if (m_hCompute32==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula32==0) { throw new NotesError(0, "Object already recycled"); } } } private List<Object> parseFormulaResult(Pointer valuePtr, int valueLength) { short dataType = valuePtr.getShort(0); int dataTypeAsInt = (int) (dataType & 0xffff); boolean supportedType = false; if (dataTypeAsInt == NotesItem.TYPE_TEXT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { supportedType = true; } if (!supportedType) { throw new UnsupportedItemValueError("Data type is currently unsupported: "+dataTypeAsInt); } int checkDataType = valuePtr.getShort(0) & 0xffff; Pointer valueDataPtr = valuePtr.share(2); int valueDataLength = valueLength - 2; if (checkDataType!=dataTypeAsInt) { throw new IllegalStateException("Value data type does not meet expected date type: found "+checkDataType+", expected "+dataTypeAsInt); } if (dataTypeAsInt == NotesItem.TYPE_TEXT) { String txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false); return txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal); } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { List<Object> textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false); return textList==null ? Collections.emptyList() : textList; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { double numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength); return Arrays.asList((Object) Double.valueOf(numVal)); } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { List<Object> numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength); return numberList==null ? Collections.emptyList() : numberList; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { if (isPreferNotesTimeDates()) { NotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength); return td==null ? Collections.emptyList() : Arrays.asList((Object) td); } else { Calendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength); return cal==null ? Collections.emptyList() : Arrays.asList((Object) cal); } } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { if (isPreferNotesTimeDates()) { List<Object> tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr); return tdValues==null ? Collections.emptyList() : tdValues; } else { List<Object> calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr); return calendarValues==null ? Collections.emptyList() : calendarValues; } } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { //e.g. returned by formula "@DeleteDocument" return Collections.emptyList(); } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { if (valueLength>=2) { short formulaErrorCode = valueDataPtr.getShort(0); String errMsg = NotesErrorUtils.errToString(formulaErrorCode); throw new NotesError(formulaErrorCode, "Could not evaluate formula "+m_formula+"\nError: "+errMsg); } else { throw new NotesError(0, "Could not evaluate formula "+m_formula); } } else { throw new UnsupportedItemValueError("Data is currently unsupported: "+dataTypeAsInt); } } /** * Evaluates the formula on a note * * @param note note * @return formula computation result */ public List<Object> evaluate(NotesNote note) { return evaluateExt(note).getValue(); } /** * Evaluates the formula on a note. Provides extended information. * * @param note note to be used as additional variables available to the formula or null * @return formula computation result with flags */ public FormulaExecutionResult evaluateExt(NotesNote note) { checkHandle(); if (note!=null) { if (note.isRecycled()) { throw new NotesError(0, "Note is already recycled"); } } if (PlatformUtils.is64Bit()) { if (!m_disallowedActions.isEmpty()) { int disallowedFlags = 0; for (Disallow currAction : m_disallowedActions) { disallowedFlags |= currAction.getValue(); } NotesNativeAPI64.get().NSFComputeSetDisallowFlags(m_hCompute64, disallowedFlags); } LongByReference rethResult = new LongByReference(); IntByReference retResultLength = new IntByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); //NSFComputeEvaluateExt supports more than the usual 64K of formula result data final int retDWordResultLength = 1; short result = NotesNativeAPI64.get().NSFComputeEvaluateExt(m_hCompute64, note==null ? 0 : note.getHandle64(), rethResult, retResultLength, retDWordResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified ); NotesErrorUtils.checkResult(result); int valueLength = retResultLength.getValue(); List<Object> formulaResult = null; long hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem64.OSLockObject(hResult); try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem64.OSUnlockObject(hResult); result = Mem64.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } else { if (!m_disallowedActions.isEmpty()) { int disallowedFlags = 0; for (Disallow currAction : m_disallowedActions) { disallowedFlags |= currAction.getValue(); } NotesNativeAPI64.get().NSFComputeSetDisallowFlags(m_hCompute64, disallowedFlags); } IntByReference rethResult = new IntByReference(); IntByReference retResultLength = new IntByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); //NSFComputeEvaluateExt supports more than the usual 64K of formula result data final int retDWordResultLength = 1; short result = NotesNativeAPI32.get().NSFComputeEvaluateExt(m_hCompute32, note==null ? 0 : note.getHandle32(), rethResult, retResultLength, retDWordResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified ); NotesErrorUtils.checkResult(result); List<Object> formulaResult = null; int hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem32.OSLockObject(hResult); int valueLength = retResultLength.getValue(); try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem32.OSUnlockObject(hResult); result = Mem32.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } } /** * Formula computation result * * @author Karsten Lehmann */ public static class FormulaExecutionResult { private List<Object> m_result; private boolean m_matchesFormula; private boolean m_shouldBeDeleted; private boolean m_noteModified; public FormulaExecutionResult(List<Object> result, boolean matchesFormula, boolean shouldBeDeleted, boolean noteModified) { m_result = result; m_matchesFormula = matchesFormula; m_shouldBeDeleted = shouldBeDeleted; m_noteModified = noteModified; } public List<Object> getValue() { return m_result; } public boolean matchesFormula() { return m_matchesFormula; } public boolean shouldBeDeleted() { return m_shouldBeDeleted; } public boolean isNoteModified() { return m_noteModified; } } @Override public void recycle() { if (isRecycled()) return; if (PlatformUtils.is64Bit()) { if (m_hCompute64!=0) { short result = NotesNativeAPI64.get().NSFComputeStop(m_hCompute64); NotesErrorUtils.checkResult(result); m_hCompute64=0; } if (m_hFormula64!=0) { Mem64.OSUnlockObject(m_hFormula64); short result = Mem64.OSMemFree(m_hFormula64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula64 = 0; m_ptrCompiledFormula=null; } } else { if (m_hCompute32!=0) { short result = NotesNativeAPI32.get().NSFComputeStop(m_hCompute32); NotesErrorUtils.checkResult(result); m_hCompute32=0; } if (m_hFormula32!=0) { Mem32.OSUnlockObject(m_hFormula32); short result = Mem32.OSMemFree(m_hFormula32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula32 = 0; m_ptrCompiledFormula=null; } } } @Override public boolean isRecycled() { if (PlatformUtils.is64Bit()) { if (m_hFormula64==0) { return true; } } else { if (m_hFormula32==0) { return true; } } return false; } @Override public boolean isNoRecycle() { return false; } @Override public int getHandle32() { return m_hFormula32; } @Override public long getHandle64() { return m_hFormula64; } public DHANDLE getHandle() { if (PlatformUtils.is64Bit()) { return DHANDLE64.newInstance(m_hFormula64); } else { return DHANDLE32.newInstance(m_hFormula32); } } /** * Returns a list of all registered (public) formula functions. Use {@link #getFunctionParameters(String)} * to get a list of function parameters. * * @return functions, e.g. "@Left(" */ public static List<String> getAllFunctions() { List<String> retNames = new ArrayList<>(); NSFFORMFUNCPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMFUNCPROCWin32() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMFUNCPROC() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaFunctions(callback); NotesErrorUtils.checkResult(result); return retNames; } /** * Returns a list of all registered (public) formula commands. Use {@link #getFunctionParameters(String)} * to get a list of command parameters. * * @return commands, e.g. "MailSend" */ public static List<String> getAllCommands() { List<String> retNames = new ArrayList<>(); NSFFORMCMDSPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMCMDSPROCWin32() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMCMDSPROC() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaCommands(callback); NotesErrorUtils.checkResult(result); return retNames; } public static class FormulaAnalyzeResult { private EnumSet<FormulaAttributes> attributes; private FormulaAnalyzeResult(EnumSet<FormulaAttributes> attributes) { this.attributes = attributes; } public Set<FormulaAttributes> getAttributes() { return Collections.unmodifiableSet(this.attributes); } @Override public String toString() { return "FormulaAnalyzeResult [attributes=" + attributes + "]"; } } /** * Scan through the function table (ftable) or keyword table (ktable) * to find parameters of an @ function or an @ command. * * @param formulaName name returned by {@link FormulaExecution#getAllFunctions()}, e.g. "@Left(" * @return function parameters, e.g. "stringToSearch; numberOfChars)stringToSearch; subString)" for the function "@Left(" */ public static List<String> getFunctionParameters(String formulaName) { Memory formulaMem = NotesStringUtils.toLMBCS(formulaName, true); Pointer ptr = NotesNativeAPI.get().NSFFindFormulaParameters(formulaMem); if (ptr==null) { return Collections.emptyList(); } else { //example format for @Middle(: //string; offset; numberchars)string; offset; endstring)string; startString; endstring)string; startString; numberchars) List<String> params = new ArrayList<>(); String paramsConc = NotesStringUtils.fromLMBCS(ptr, -1); StringBuilder sb = new StringBuilder(); for (int i=0; i<paramsConc.length(); i++) { char c = paramsConc.charAt(i); sb.append(c); if (c==')') { params.add(sb.toString()); sb.setLength(0); } } return params; } } /** * Analyzes the @-function * * @return result with flags, e.g. whether the function returns a constant value or is time based */ public FormulaAnalyzeResult analyze() { checkHandle(); DHANDLE hFormula = getHandle(); IntByReference retAttributes = new IntByReference(); ShortByReference retSummaryNamesOffset = new ShortByReference(); short result = NotesNativeAPI.get().NSFFormulaAnalyze(hFormula.getByValue(), retAttributes, retSummaryNamesOffset); NotesErrorUtils.checkResult(result); EnumSet<FormulaAttributes> attributes = FormulaAttributes.toFormulaAttributes(retAttributes.getValue()); return new FormulaAnalyzeResult(attributes); } }
domino-jna/src/main/java/com/mindoo/domino/jna/formula/FormulaExecution.java
package com.mindoo.domino.jna.formula; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import com.mindoo.domino.jna.IAdaptable; import com.mindoo.domino.jna.NotesItem; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesTimeDate; import com.mindoo.domino.jna.constants.FormulaAttributes; import com.mindoo.domino.jna.errors.FormulaCompilationError; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.errors.UnsupportedItemValueError; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.ItemDecoder; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMCMDSPROC; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMFUNCPROC; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMCMDSPROCWin32; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMFUNCPROCWin32; import com.mindoo.domino.jna.internal.handles.DHANDLE; import com.mindoo.domino.jna.internal.handles.DHANDLE32; import com.mindoo.domino.jna.internal.handles.DHANDLE64; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.PlatformUtils; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * Utility class to execute a Domino formula on one or more {@link NotesNote} objects.<br> * <br> * The implementation supports more than the usual 64K of return value, e.g. to use * <code>@DBColumn</code> to read the column values in views with many entries. * * @author Karsten Lehmann */ public class FormulaExecution implements IRecyclableNotesObject, IAdaptable { private String m_formula; private long m_hFormula64; private long m_hCompute64; private int m_hFormula32; private int m_hCompute32; private int m_compiledFormulaLength; private Pointer m_ptrCompiledFormula; private boolean m_preferNotesTimeDates; /** * Creates a new instance. The constructure compiles the formula and throws a {@link FormulaCompilationError}, * if there are any compilation errors * * @param formula formula * @throws FormulaCompilationError if formula has wrong syntax */ public FormulaExecution(String formula) throws FormulaCompilationError { m_formula = formula; Memory formulaName = null; short formulaNameLength = 0; Memory formulaText = NotesStringUtils.toLMBCS(formula, false, false); short formulaTextLength = (short) formulaText.size(); short computeFlags = 0; if (PlatformUtils.is64Bit()) { m_hFormula64 = 0; LongByReference rethFormula = new LongByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI64.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula64 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); LongByReference rethCompute = new LongByReference(); m_ptrCompiledFormula = Mem64.OSLockObject(m_hFormula64); result = NotesNativeAPI64.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute64 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } else { m_hFormula32 = 0; IntByReference rethFormula = new IntByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI32.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula32 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); IntByReference rethCompute = new IntByReference(); m_ptrCompiledFormula = Mem32.OSLockObject(m_hFormula32); result = NotesNativeAPI32.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute32 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } } @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> clazz) { checkHandle(); if (clazz == byte[].class) { //return compiled formula as byte array byte[] compiledFormula = m_ptrCompiledFormula.getByteArray(0, m_compiledFormulaLength); return (T) compiledFormula; } return null; } public String getFormula() { return m_formula; } /** * Sets whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @param b true to prefer NotesTimeDate (false by default) */ public void setPreferNotesTimeDates(boolean b) { m_preferNotesTimeDates = b; } /** * Returns whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @return true to prefer NotesTimeDate */ public boolean isPreferNotesTimeDates() { return m_preferNotesTimeDates; } public String toString() { if (isRecycled()) { return "Compiled formula [recycled, formula="+m_formula+"]"; } else { return "Compiled formula [formula="+m_formula+"]"; } } /** * Convenience method to execute a formula on a single note and return the result as a string.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result as string; if the formula returns a list, we pick the first value * @throws FormulaCompilationError if formula has wrong syntax */ public static String evaluateAsString(String formula, NotesNote note) throws FormulaCompilationError { List<Object> result = evaluate(formula, note); if (result.isEmpty()) return ""; else { return result.get(0).toString(); } } /** * Convenience method to execute a formula on a single note.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static List<Object> evaluate(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { List<Object> result = instance.evaluate(note); return result; } finally { instance.recycle(); } } /** * Convenience method to execute a formula on a single note. Provides extended information.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static FormulaExecutionResult evaluateExt(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { FormulaExecutionResult result = instance.evaluateExt(note); return result; } finally { instance.recycle(); } } private void checkHandle() { if (PlatformUtils.is64Bit()) { if (m_hCompute64==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula64==0) { throw new NotesError(0, "Object already recycled"); } } else { if (m_hCompute32==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula32==0) { throw new NotesError(0, "Object already recycled"); } } } private List<Object> parseFormulaResult(Pointer valuePtr, int valueLength) { short dataType = valuePtr.getShort(0); int dataTypeAsInt = (int) (dataType & 0xffff); boolean supportedType = false; if (dataTypeAsInt == NotesItem.TYPE_TEXT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { supportedType = true; } if (!supportedType) { throw new UnsupportedItemValueError("Data type is currently unsupported: "+dataTypeAsInt); } int checkDataType = valuePtr.getShort(0) & 0xffff; Pointer valueDataPtr = valuePtr.share(2); int valueDataLength = valueLength - 2; if (checkDataType!=dataTypeAsInt) { throw new IllegalStateException("Value data type does not meet expected date type: found "+checkDataType+", expected "+dataTypeAsInt); } if (dataTypeAsInt == NotesItem.TYPE_TEXT) { String txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false); return txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal); } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { List<Object> textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false); return textList==null ? Collections.emptyList() : textList; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { double numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength); return Arrays.asList((Object) Double.valueOf(numVal)); } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { List<Object> numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength); return numberList==null ? Collections.emptyList() : numberList; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { if (isPreferNotesTimeDates()) { NotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength); return td==null ? Collections.emptyList() : Arrays.asList((Object) td); } else { Calendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength); return cal==null ? Collections.emptyList() : Arrays.asList((Object) cal); } } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { if (isPreferNotesTimeDates()) { List<Object> tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr); return tdValues==null ? Collections.emptyList() : tdValues; } else { List<Object> calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr); return calendarValues==null ? Collections.emptyList() : calendarValues; } } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { //e.g. returned by formula "@DeleteDocument" return Collections.emptyList(); } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { if (valueLength>=2) { short formulaErrorCode = valueDataPtr.getShort(0); String errMsg = NotesErrorUtils.errToString(formulaErrorCode); throw new NotesError(formulaErrorCode, "Could not evaluate formula "+m_formula+"\nError: "+errMsg); } else { throw new NotesError(0, "Could not evaluate formula "+m_formula); } } else { throw new UnsupportedItemValueError("Data is currently unsupported: "+dataTypeAsInt); } } /** * Evaluates the formula on a note * * @param note note * @return formula computation result */ public List<Object> evaluate(NotesNote note) { return evaluateExt(note).getValue(); } /** * Evaluates the formula on a note. Provides extended information. * * @param note note to be used as additional variables available to the formula or null * @return formula computation result with flags */ public FormulaExecutionResult evaluateExt(NotesNote note) { checkHandle(); if (note!=null) { if (note.isRecycled()) { throw new NotesError(0, "Note is already recycled"); } } if (PlatformUtils.is64Bit()) { LongByReference rethResult = new LongByReference(); IntByReference retResultLength = new IntByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); //NSFComputeEvaluateExt supports more than the usual 64K of formula result data final int retDWordResultLength = 1; short result = NotesNativeAPI64.get().NSFComputeEvaluateExt(m_hCompute64, note==null ? 0 : note.getHandle64(), rethResult, retResultLength, retDWordResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified ); NotesErrorUtils.checkResult(result); int valueLength = retResultLength.getValue(); List<Object> formulaResult = null; long hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem64.OSLockObject(hResult); try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem64.OSUnlockObject(hResult); result = Mem64.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } else { IntByReference rethResult = new IntByReference(); IntByReference retResultLength = new IntByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); //NSFComputeEvaluateExt supports more than the usual 64K of formula result data final int retDWordResultLength = 1; short result = NotesNativeAPI32.get().NSFComputeEvaluateExt(m_hCompute32, note==null ? 0 : note.getHandle32(), rethResult, retResultLength, retDWordResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified ); NotesErrorUtils.checkResult(result); List<Object> formulaResult = null; int hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem32.OSLockObject(hResult); int valueLength = retResultLength.getValue(); try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem32.OSUnlockObject(hResult); result = Mem32.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } } /** * Formula computation result * * @author Karsten Lehmann */ public static class FormulaExecutionResult { private List<Object> m_result; private boolean m_matchesFormula; private boolean m_shouldBeDeleted; private boolean m_noteModified; public FormulaExecutionResult(List<Object> result, boolean matchesFormula, boolean shouldBeDeleted, boolean noteModified) { m_result = result; m_matchesFormula = matchesFormula; m_shouldBeDeleted = shouldBeDeleted; m_noteModified = noteModified; } public List<Object> getValue() { return m_result; } public boolean matchesFormula() { return m_matchesFormula; } public boolean shouldBeDeleted() { return m_shouldBeDeleted; } public boolean isNoteModified() { return m_noteModified; } } @Override public void recycle() { if (isRecycled()) return; if (PlatformUtils.is64Bit()) { if (m_hCompute64!=0) { short result = NotesNativeAPI64.get().NSFComputeStop(m_hCompute64); NotesErrorUtils.checkResult(result); m_hCompute64=0; } if (m_hFormula64!=0) { Mem64.OSUnlockObject(m_hFormula64); short result = Mem64.OSMemFree(m_hFormula64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula64 = 0; m_ptrCompiledFormula=null; } } else { if (m_hCompute32!=0) { short result = NotesNativeAPI32.get().NSFComputeStop(m_hCompute32); NotesErrorUtils.checkResult(result); m_hCompute32=0; } if (m_hFormula32!=0) { Mem32.OSUnlockObject(m_hFormula32); short result = Mem32.OSMemFree(m_hFormula32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula32 = 0; m_ptrCompiledFormula=null; } } } @Override public boolean isRecycled() { if (PlatformUtils.is64Bit()) { if (m_hFormula64==0) { return true; } } else { if (m_hFormula32==0) { return true; } } return false; } @Override public boolean isNoRecycle() { return false; } @Override public int getHandle32() { return m_hFormula32; } @Override public long getHandle64() { return m_hFormula64; } public DHANDLE getHandle() { if (PlatformUtils.is64Bit()) { return DHANDLE64.newInstance(m_hFormula64); } else { return DHANDLE32.newInstance(m_hFormula32); } } /** * Returns a list of all registered (public) formula functions. Use {@link #getFunctionParameters(String)} * to get a list of function parameters. * * @return functions, e.g. "@Left(" */ public static List<String> getAllFunctions() { List<String> retNames = new ArrayList<>(); NSFFORMFUNCPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMFUNCPROCWin32() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMFUNCPROC() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaFunctions(callback); NotesErrorUtils.checkResult(result); return retNames; } /** * Returns a list of all registered (public) formula commands. Use {@link #getFunctionParameters(String)} * to get a list of command parameters. * * @return commands, e.g. "MailSend" */ public static List<String> getAllCommands() { List<String> retNames = new ArrayList<>(); NSFFORMCMDSPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMCMDSPROCWin32() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMCMDSPROC() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaCommands(callback); NotesErrorUtils.checkResult(result); return retNames; } public static class FormulaAnalyzeResult { private EnumSet<FormulaAttributes> attributes; private FormulaAnalyzeResult(EnumSet<FormulaAttributes> attributes) { this.attributes = attributes; } public Set<FormulaAttributes> getAttributes() { return Collections.unmodifiableSet(this.attributes); } @Override public String toString() { return "FormulaAnalyzeResult [attributes=" + attributes + "]"; } } /** * Scan through the function table (ftable) or keyword table (ktable) * to find parameters of an @ function or an @ command. * * @param formulaName name returned by {@link FormulaExecution#getAllFunctions()}, e.g. "@Left(" * @return function parameters, e.g. "stringToSearch; numberOfChars)stringToSearch; subString)" for the function "@Left(" */ public static List<String> getFunctionParameters(String formulaName) { Memory formulaMem = NotesStringUtils.toLMBCS(formulaName, true); Pointer ptr = NotesNativeAPI.get().NSFFindFormulaParameters(formulaMem); if (ptr==null) { return Collections.emptyList(); } else { //example format for @Middle(: //string; offset; numberchars)string; offset; endstring)string; startString; endstring)string; startString; numberchars) List<String> params = new ArrayList<>(); String paramsConc = NotesStringUtils.fromLMBCS(ptr, -1); StringBuilder sb = new StringBuilder(); for (int i=0; i<paramsConc.length(); i++) { char c = paramsConc.charAt(i); sb.append(c); if (c==')') { params.add(sb.toString()); sb.setLength(0); } } return params; } } /** * Analyzes the @-function * * @return result with flags, e.g. whether the function returns a constant value or is time based */ public FormulaAnalyzeResult analyze() { checkHandle(); DHANDLE hFormula = getHandle(); IntByReference retAttributes = new IntByReference(); ShortByReference retSummaryNamesOffset = new ShortByReference(); short result = NotesNativeAPI.get().NSFFormulaAnalyze(hFormula.getByValue(), retAttributes, retSummaryNamesOffset); NotesErrorUtils.checkResult(result); EnumSet<FormulaAttributes> attributes = FormulaAttributes.toFormulaAttributes(retAttributes.getValue()); return new FormulaAnalyzeResult(attributes); } }
API to apply security to formula execution
domino-jna/src/main/java/com/mindoo/domino/jna/formula/FormulaExecution.java
API to apply security to formula execution
Java
apache-2.0
351aeb957c2c46d0c8c1580f28c79057bcdc5bba
0
adgear/secor,adgear/secor
package com.pinterest.secor.io.impl; import com.pinterest.secor.common.SecorConfig; import com.pinterest.secor.io.AdgearReader; import com.pinterest.secor.io.KeyValue; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; // Converts gateway JSON to Beh TSV public class AdgearGatewayJsonReader implements AdgearReader { private final String timestampFieldname; private final boolean logGeo; private final String logGeoInclude; public AdgearGatewayJsonReader(SecorConfig secorConfig) { timestampFieldname = secorConfig.getMessageTimestampName(); logGeo = secorConfig.getSecorAdgearLogFieldsGeo(); logGeoInclude = secorConfig.getSecorAdgearLogFieldsGeoInclude(); } public String convert(KeyValue kv) { JSONObject jsonObject = null; Object value = JSONValue.parse(kv.getValue()); if (value instanceof JSONObject) { jsonObject = (JSONObject) value; } else { return null; } Double timestamp = (Double) jsonObject.get(timestampFieldname); String cookieId = (String) getAtPath(jsonObject, "bid_request.user.buyeruid"); String urlDomain = (String) getAtPath(jsonObject,"bid_request.site.domain"); // Extra fields, logged if present String country = null, region = null; if (logGeo) { String c = (String) getAtPath(jsonObject, "bid_request.device.geo.country"); // Apply whitelist if set if (logGeoInclude == null || logGeoInclude.equals(c)) { country = c; region = (String) getAtPath(jsonObject, "bid_request.device.geo.region"); } } if (timestamp == null || cookieId == null || urlDomain == null) { return null; } StringBuffer output = new StringBuffer(); output .append(cookieId).append('\t') .append(Math.round(timestamp)).append('\t') .append("urld:").append(urlDomain); // FIXME: Duplicated code (see sibling class) // FIXME: Add validation? if (logGeo) { if (country != null) { output.append(",country:").append(country); } if (region != null) { output.append(",region:").append(region); } } output.append("\n"); return output.toString(); } // 1. Horrible // 2. Why isn't this part of json-smart? private static Object getAtPath(JSONObject json, String path) { String[] components = path.split("\\."); Object object = json; for (String component : components) { if (!(object instanceof JSONObject)) return null; // That's really an error. object = ((JSONObject) object).get(component); if (object == null) return null; } return object; } }
src/main/java/com/pinterest/secor/io/impl/AdgearGatewayJsonReader.java
package com.pinterest.secor.io.impl; import com.pinterest.secor.common.SecorConfig; import com.pinterest.secor.io.AdgearReader; import com.pinterest.secor.io.KeyValue; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; // Converts gateway JSON to Beh TSV public class AdgearGatewayJsonReader implements AdgearReader { private final String timestampFieldname; private final boolean logGeo; private final String logGeoInclude; public AdgearGatewayJsonReader(SecorConfig secorConfig) { timestampFieldname = secorConfig.getMessageTimestampName(); logGeo = secorConfig.getSecorAdgearLogFieldsGeo(); logGeoInclude = secorConfig.getSecorAdgearLogFieldsGeoInclude(); } public String convert(KeyValue kv) { JSONObject jsonObject = null; Object value = JSONValue.parse(kv.getValue()); if (value instanceof JSONObject) { jsonObject = (JSONObject) value; } else { return null; } Double timestamp = (Double) jsonObject.get(timestampFieldname); String cookieId = (String) getAtPath(jsonObject, "bid_request.user.buyeruid"); String urlDomain = (String) getAtPath(jsonObject,"bid_request.site.domain"); // Extra fields, logged if present String country = null, region = null; if (logGeo) { String c = (String) getAtPath(jsonObject, "bid_request.device.geo.country"); // Apply whitelist if set if (logGeoInclude == null || c == logGeoInclude) { country = c; region = (String) getAtPath(jsonObject, "bid_request.device.geo.region"); } } if (timestamp == null || cookieId == null || urlDomain == null) { return null; } StringBuffer output = new StringBuffer(); output .append(cookieId).append('\t') .append(Math.round(timestamp)).append('\t') .append("urld:").append(urlDomain); // FIXME: Duplicated code (see sibling class) // FIXME: Add validation? if (logGeo) { if (country != null) { output.append(",country:").append(country); } if (region != null) { output.append(",region:").append(region); } } output.append("\n"); return output.toString(); } // 1. Horrible // 2. Why isn't this part of json-smart? private static Object getAtPath(JSONObject json, String path) { String[] components = path.split("\\."); Object object = json; for (String component : components) { if (!(object instanceof JSONObject)) return null; // That's really an error. object = ((JSONObject) object).get(component); if (object == null) return null; } return object; } }
Fix string comparison.
src/main/java/com/pinterest/secor/io/impl/AdgearGatewayJsonReader.java
Fix string comparison.
Java
bsd-3-clause
8a857e21525b88839da99ba236eb42485f800ed4
0
aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi-java
package com.aldebaran.qimessaging; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Map; /** * Tool class providing QiMessaging<->Java type system loading and * dynamic library loader designed to load libraries included in jar package. * @author proullon * */ public class EmbeddedTools { private File tmpDir = null; public static boolean LOADED_EMBEDDED_LIBRARY = false; private static native void initTypeSystem(java.lang.Object str, java.lang.Object i, java.lang.Object f, java.lang.Object d, java.lang.Object l, java.lang.Object m, java.lang.Object al, java.lang.Object t, java.lang.Object o, java.lang.Object b); private static native void initTupleInTypeSystem(java.lang.Object t1, java.lang.Object t2, java.lang.Object t3, java.lang.Object t4, java.lang.Object t5, java.lang.Object t6, java.lang.Object t7, java.lang.Object t8); public static String getSuitableLibraryExtention() { String[] ext = new String[] {".so", ".dylib", ".dll"}; String osName = System.getProperty("os.name"); if (osName == "Windows") return ext[2]; if (osName == "Mac") return ext[1]; return ext[0]; } /** * To work correctly, QiMessaging<->java type system needs to compare type class template. * Unfortunately, call template cannot be retrieve on native android thread. * The only available way to do is to store instance of wanted object * and get fresh class template from it right before using it. */ private boolean initTypeSystem() { String str = new String(); Integer i = new Integer(0); Float f = new Float(0); Double d = new Double(0); Long l = new Long(0); Tuple t = new Tuple1<java.lang.Object>(); Boolean b = new Boolean(true); GenericObjectBuilder ob = new GenericObjectBuilder(); Object obj = ob.object(); Map<java.lang.Object, java.lang.Object> m = new Hashtable<java.lang.Object, java.lang.Object>(); ArrayList<java.lang.Object> al = new ArrayList<java.lang.Object>(); // Initialize generic type system EmbeddedTools.initTypeSystem(str, i, f, d, l, m, al, t, obj, b); Tuple t1 = Tuple.makeTuple(0); Tuple t2 = Tuple.makeTuple(0, 0); Tuple t3 = Tuple.makeTuple(0, 0, 0); Tuple t4 = Tuple.makeTuple(0, 0, 0, 0); Tuple t5 = Tuple.makeTuple(0, 0, 0, 0, 0); Tuple t6 = Tuple.makeTuple(0, 0, 0, 0, 0, 0); Tuple t7 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0); Tuple t8 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0); // Initialize tuple EmbeddedTools.initTupleInTypeSystem(t1, t2, t3, t4, t5, t6, t7, t8); return true; } /** * Override directory where native libraries are extracted. */ public void overrideTempDirectory(File newValue) { tmpDir = newValue; } /** * Override directory where native libraries are extracted. */ public void overrideTempDirectory(File newValue) { tmpDir = newValue; } /** * Native C++ librairies are package with java sources. * This way, we are able to load them anywhere, anytime. */ public boolean loadEmbeddedLibraries() { if (LOADED_EMBEDDED_LIBRARY == true) { System.out.print("Native libraries already loaded"); return true; } /* * Since we use multiple shared libraries, * we need to use libstlport_shared to avoid multiple STL declarations */ loadEmbeddedLibrary("libgnustl_shared"); if (loadEmbeddedLibrary("libqi") == false || loadEmbeddedLibrary("libqitype") == false || loadEmbeddedLibrary("libqimessaging") == false || loadEmbeddedLibrary("libqimessagingjni") == false) { LOADED_EMBEDDED_LIBRARY = false; return false; } System.out.printf("Libraries loaded. Initializing type system...\n"); LOADED_EMBEDDED_LIBRARY = true; if (initTypeSystem() == false) { System.out.printf("Cannot initialize type system\n"); LOADED_EMBEDDED_LIBRARY = false; return false; } return true; } public boolean loadEmbeddedLibrary(String libname) { boolean usingEmbedded = false; // Locate native library within qimessaging.jar StringBuilder path = new StringBuilder(); path.append("/" + libname+getSuitableLibraryExtention()); // Search native library for host system URL nativeLibrary = null; if ((nativeLibrary = EmbeddedTools.class.getResource(path.toString())) == null) { try { System.loadLibrary(libname); } catch (UnsatisfiedLinkError e) { if (libname != "libgnustl_shared") // Disable warning to avoid false positive. System.out.printf("[WARN ] Unsatified link error : %s\n", e.getMessage()); return false; } return true; } // Delete if already exists File toDelete = new File(tmpDir.getAbsolutePath() + path.toString()); if (toDelete.exists()) { System.out.printf("Deleting %s\n", toDelete.getAbsolutePath()); toDelete.delete(); } // Extract and load native library try { final File libfile = File.createTempFile(libname, getSuitableLibraryExtention(), tmpDir); libfile.deleteOnExit(); final InputStream in = nativeLibrary.openStream(); final OutputStream out = new BufferedOutputStream(new FileOutputStream(libfile)); int len = 0; byte[] buffer = new byte[10000]; while ((len = in.read(buffer)) > -1) { out.write(buffer, 0, len); } out.close(); in.close(); int actualPathLength = libfile.getAbsolutePath().length(); int actualNameLength = libfile.getName().length(); int endIndex = actualPathLength - actualNameLength; // Rename tmp file to actual library name String pathToTmp = libfile.getAbsolutePath().substring(0, endIndex); File so = new File(pathToTmp + "/" + libname + getSuitableLibraryExtention()); System.out.printf("Extracting %s in %s...\n", libname + getSuitableLibraryExtention(), pathToTmp); libfile.renameTo(so); System.load(so.getAbsolutePath()); usingEmbedded = true; } catch (IOException x) { System.out.printf("Cannot extract native library %s: %s\n", libname, x); return false; } catch (UnsatisfiedLinkError e) { System.out.printf("Cannot load native library %s: %s\n", libname, e); return false; } return usingEmbedded; } }
java/qimessaging/src/main/java/com/aldebaran/qimessaging/EmbeddedTools.java
package com.aldebaran.qimessaging; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Map; /** * Tool class providing QiMessaging<->Java type system loading and * dynamic library loader designed to load libraries included in jar package. * @author proullon * */ public class EmbeddedTools { private File tmpDir = null; public static boolean LOADED_EMBEDDED_LIBRARY = false; private static native void initTypeSystem(java.lang.Object str, java.lang.Object i, java.lang.Object f, java.lang.Object d, java.lang.Object l, java.lang.Object m, java.lang.Object al, java.lang.Object t, java.lang.Object o, java.lang.Object b); private static native void initTupleInTypeSystem(java.lang.Object t1, java.lang.Object t2, java.lang.Object t3, java.lang.Object t4, java.lang.Object t5, java.lang.Object t6, java.lang.Object t7, java.lang.Object t8); public static String getSuitableLibraryExtention() { String[] ext = new String[] {".so", ".dylib", ".dll"}; String osName = System.getProperty("os.name"); if (osName == "Windows") return ext[2]; if (osName == "Mac") return ext[1]; return ext[0]; } /** * To work correctly, QiMessaging<->java type system needs to compare type class template. * Unfortunately, call template cannot be retrieve on native android thread. * The only available way to do is to store instance of wanted object * and get fresh class template from it right before using it. */ private boolean initTypeSystem() { String str = new String(); Integer i = new Integer(0); Float f = new Float(0); Double d = new Double(0); Long l = new Long(0); Tuple t = new Tuple1<java.lang.Object>(); Boolean b = new Boolean(true); GenericObjectBuilder ob = new GenericObjectBuilder(); Object obj = ob.object(); Map<java.lang.Object, java.lang.Object> m = new Hashtable<java.lang.Object, java.lang.Object>(); ArrayList<java.lang.Object> al = new ArrayList<java.lang.Object>(); // Initialize generic type system EmbeddedTools.initTypeSystem(str, i, f, d, l, m, al, t, obj, b); Tuple t1 = Tuple.makeTuple(0); Tuple t2 = Tuple.makeTuple(0, 0); Tuple t3 = Tuple.makeTuple(0, 0, 0); Tuple t4 = Tuple.makeTuple(0, 0, 0, 0); Tuple t5 = Tuple.makeTuple(0, 0, 0, 0, 0); Tuple t6 = Tuple.makeTuple(0, 0, 0, 0, 0, 0); Tuple t7 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0); Tuple t8 = Tuple.makeTuple(0, 0, 0, 0, 0, 0, 0, 0); // Initialize tuple EmbeddedTools.initTupleInTypeSystem(t1, t2, t3, t4, t5, t6, t7, t8); return true; } /** * Override directory where native libraries are extracted. */ public void overrideTempDirectory(File newValue) { tmpDir = newValue; } /** * Native C++ librairies are package with java sources. * This way, we are able to load them anywhere, anytime. */ public boolean loadEmbeddedLibraries() { if (LOADED_EMBEDDED_LIBRARY == true) { System.out.print("Native libraries already loaded"); return true; } /* * Since we use multiple shared libraries, * we need to use libstlport_shared to avoid multiple STL declarations */ loadEmbeddedLibrary("libgnustl_shared"); if (loadEmbeddedLibrary("libqi") == false || loadEmbeddedLibrary("libqitype") == false || loadEmbeddedLibrary("libqimessaging") == false || loadEmbeddedLibrary("libqimessagingjni") == false) { LOADED_EMBEDDED_LIBRARY = false; return false; } LOADED_EMBEDDED_LIBRARY = true; if (initTypeSystem() == false) { LOADED_EMBEDDED_LIBRARY = false; return false; } return true; } public boolean loadEmbeddedLibrary(String libname) { boolean usingEmbedded = false; // Locate native library within qimessaging.jar StringBuilder path = new StringBuilder(); path.append("/" + libname+getSuitableLibraryExtention()); // Search native library for host system URL nativeLibrary = null; if ((nativeLibrary = EmbeddedTools.class.getResource(path.toString())) == null) { try { System.loadLibrary(libname); } catch (UnsatisfiedLinkError e) { if (libname != "libgnustl_shared") // Disable warning to avoid false positive. System.out.printf("[WARN ] Unsatified link error : %s\n", e.getMessage()); return false; } return true; } // Extract and load native library try { final File libfile = File.createTempFile(libname, getSuitableLibraryExtention(), tmpDir); libfile.deleteOnExit(); final InputStream in = nativeLibrary.openStream(); final OutputStream out = new BufferedOutputStream(new FileOutputStream(libfile)); int len = 0; byte[] buffer = new byte[10000]; while ((len = in.read(buffer)) > -1) { out.write(buffer, 0, len); } out.close(); in.close(); int actualPathLength = libfile.getAbsolutePath().length(); int actualNameLength = libfile.getName().length(); int endIndex = actualPathLength - actualNameLength; // Rename tmp file to actual library name String pathToTmp = libfile.getAbsolutePath().substring(0, endIndex); File so = new File(pathToTmp + "/" + libname + getSuitableLibraryExtention()); System.out.printf("Extracting %s in %s...\n", libname + getSuitableLibraryExtention(), pathToTmp); libfile.renameTo(so); System.load(so.getAbsolutePath()); usingEmbedded = true; } catch (IOException x) { usingEmbedded = false; } return usingEmbedded; } }
Java: Add method to override directory where native libraries are extracted Change-Id: I4390f87dd00fb60db13b1b1dc08e6eeaeb315c52 Reviewed-on: http://gerrit.aldebaran.lan/20228 Reviewed-by: proullon <[email protected]> Tested-by: proullon <[email protected]>
java/qimessaging/src/main/java/com/aldebaran/qimessaging/EmbeddedTools.java
Java: Add method to override directory where native libraries are extracted
Java
bsd-3-clause
d296c18880aaf986f04fa326f2c101cc5908f8e7
0
salesforce/storm-dynamic-spout,salesforce/storm-dynamic-spout
package com.salesforce.storm.spout.sideline; import com.salesforce.storm.spout.sideline.kafka.DelegateSidelineSpout; import com.salesforce.storm.spout.sideline.metrics.MetricsRecorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Clock; import java.util.Map; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Spout Coordinator. * * Manages X number of spouts and coordinates their nextTuple(), ack() and fail() calls across threads */ public class SpoutCoordinator { private static final Logger logger = LoggerFactory.getLogger(SpoutCoordinator.class); /** * How long our monitor thread will sit around and sleep between monitoring * if new VirtualSpouts need to be started up, in Milliseconds. */ public static final int MONITOR_THREAD_SLEEP_MS = 2000; /** * How long we'll wait for all VirtualSpout's to cleanly shut down, before we stop * them with force, in Milliseconds. */ public static final int MAX_SPOUT_STOP_TIME_MS = 10000; /** * How often we'll make sure each VirtualSpout persists its state, in Milliseconds. */ public static final long FLUSH_INTERVAL_MS = 30000; /** * The size of the thread pool for running virtual spouts for sideline requests. */ public static final int SPOUT_RUNNER_THREAD_POOL_SIZE = 10; /** * Which Clock instance to get reference to the system time. * We use this to allow injecting a fake System clock in tests. * * ThreadSafety - Lucky for us, Clock is all thread safe :) */ private Clock clock = Clock.systemUTC(); /** * Queue of spouts that need to be passed to the monitor and spun up. */ private final Queue<DelegateSidelineSpout> newSpoutQueue = new ConcurrentLinkedQueue<>(); /** * Buffer by spout consumer id of messages that have been acked. */ private final Map<String,Queue<TupleMessageId>> ackedTuplesInputQueue = new ConcurrentHashMap<>(); /** * Buffer by spout consumer id of messages that have been failed. */ private final Map<String,Queue<TupleMessageId>> failedTuplesInputQueue = new ConcurrentHashMap<>(); /** * Thread Pool Executor. */ private final ExecutorService executor; /** * For capturing metrics. */ private final MetricsRecorder metricsRecorder; /** * The spout monitor runnable, which handles spinning up threads for sideline spouts. */ private SpoutMonitor spoutMonitor; /** * Flag that gets set to false on shutdown, to signal to close up shop. * This probably should be renamed at some point. */ private boolean isOpen = false; /** * Create a new coordinator, supplying the 'fire hose' or the starting spouts. * @param spout Fire hose spout */ public SpoutCoordinator(final DelegateSidelineSpout spout, final MetricsRecorder metricsRecorder) { this.executor = Executors.newFixedThreadPool(SPOUT_RUNNER_THREAD_POOL_SIZE); this.metricsRecorder = metricsRecorder; addSidelineSpout(spout); } /** * Add a new spout to the coordinator, this will get picked up by the coordinator's monitor, opened and * managed with teh other currently running spouts. * @param spout New delegate spout */ public void addSidelineSpout(final DelegateSidelineSpout spout) { newSpoutQueue.add(spout); } /** * Open the coordinator and begin spinning up virtual spout threads. * @param tupleOutputQueue The queue to put messages onto */ public void open(final BlockingQueue tupleOutputQueue) { isOpen = true; final CountDownLatch latch = new CountDownLatch(newSpoutQueue.size()); spoutMonitor = new SpoutMonitor( executor, newSpoutQueue, tupleOutputQueue, ackedTuplesInputQueue, failedTuplesInputQueue, latch, clock ); executor.submit(spoutMonitor); try { latch.await(); } catch (InterruptedException ex) { logger.error("Exception while waiting for the coordinator to open it's spouts {}", ex); } } /** * Acks a tuple on the spout that it belongs to. * @param id Tuple message id to ack */ public void ack(final TupleMessageId id) { if (!ackedTuplesInputQueue.containsKey(id.getSrcConsumerId())) { logger.warn("Acking tuple for unknown consumer"); return; } ackedTuplesInputQueue.get(id.getSrcConsumerId()).add(id); } /** * Fails a tuple on the spout that it belongs to. * @param id Tuple message id to fail */ public void fail(final TupleMessageId id) { if (!failedTuplesInputQueue.containsKey(id.getSrcConsumerId())) { logger.warn("Failing tuple for unknown consumer"); return; } failedTuplesInputQueue.get(id.getSrcConsumerId()).add(id); } /** * Stop coordinating spouts, calling this should shut down and finish the coordinator's spouts. */ public void close() { spoutMonitor.close(); try { executor.awaitTermination(MAX_SPOUT_STOP_TIME_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.error("Caught Exception while stopping: {}", ex); } executor.shutdownNow(); // Will trigger the monitor thread to stop running, which should be the end of it isOpen = false; } /** * For testing, returns the total number of running spouts. * @return The total number of spouts the coordinator is running */ int getTotalSpouts() { return spoutMonitor.getTotalSpouts(); } /** * Monitors the lifecycle of spinning up virtual spouts. */ private static class SpoutMonitor implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SpoutMonitor.class); private final ExecutorService executor; private final Queue<DelegateSidelineSpout> newSpoutQueue; private final BlockingQueue tupleOutputQueue; private final Map<String,Queue<TupleMessageId>> ackedTuplesInputQueue; private final Map<String,Queue<TupleMessageId>> failedTuplesInputQueue; private final CountDownLatch latch; private final Clock clock; private final Map<String,SpoutRunner> spoutRunners = new ConcurrentHashMap<>(); private final Map<String,Future> spoutThreads = new ConcurrentHashMap<>(); private boolean isOpen = true; SpoutMonitor( final ExecutorService executor, final Queue<DelegateSidelineSpout> newSpoutQueue, final BlockingQueue tupleOutputQueue, final Map<String,Queue<TupleMessageId>> ackedTuplesInputQueue, final Map<String,Queue<TupleMessageId>> failedTuplesInputQueue, final CountDownLatch latch, final Clock clock ) { this.executor = executor; this.newSpoutQueue = newSpoutQueue; this.tupleOutputQueue = tupleOutputQueue; this.ackedTuplesInputQueue = ackedTuplesInputQueue; this.failedTuplesInputQueue = failedTuplesInputQueue; this.latch = latch; this.clock = clock; } @Override public void run() { try { // Rename our thread. Thread.currentThread().setName("SidelineSpout-NewSpoutMonitor"); // Start monitoring loop. while (isOpen) { logger.info("Still here.. my input queue is {}", newSpoutQueue.size()); for (DelegateSidelineSpout spout; (spout = newSpoutQueue.poll()) != null;) { logger.info("Preparing thread for spout {}", spout.getConsumerId()); final SpoutRunner spoutRunner = new SpoutRunner( spout, tupleOutputQueue, ackedTuplesInputQueue, failedTuplesInputQueue, latch, clock ); spoutRunners.put(spout.getConsumerId(), spoutRunner); final Future spoutInstance = executor.submit(spoutRunner); spoutThreads.put(spout.getConsumerId(), spoutInstance); } // Pause for a period before checking for more spouts try { Thread.sleep(MONITOR_THREAD_SLEEP_MS); } catch (InterruptedException ex) { logger.warn("!!!!!! Thread interrupted, shutting down..."); return; } } logger.warn("!!!!!! Spout coordinator is ceasing to run..."); } catch (Exception ex) { // TODO: Should we restart the monitor? logger.error("SpoutMonitor threw an exception {}", ex); } } public void close() { isOpen = false; for (SpoutRunner spoutRunner : spoutRunners.values()) { spoutRunner.requestStop(); } spoutRunners.clear(); spoutThreads.clear(); } public int getTotalSpouts() { return spoutRunners.size(); } } private static class SpoutRunner implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SpoutRunner.class); private final DelegateSidelineSpout spout; private final BlockingQueue tupleOutputQueue; private final Map<String,Queue<TupleMessageId>> ackedTupleInputQueue; private final Map<String,Queue<TupleMessageId>> failedTupleInputQueue; private final CountDownLatch latch; private final Clock clock; SpoutRunner( final DelegateSidelineSpout spout, final BlockingQueue tupleOutputQueue, final Map<String,Queue<TupleMessageId>> ackedTupleInputQueue, final Map<String,Queue<TupleMessageId>> failedTupleInputQueue, final CountDownLatch latch, final Clock clock ) { this.spout = spout; this.tupleOutputQueue = tupleOutputQueue; this.ackedTupleInputQueue = ackedTupleInputQueue; this.failedTupleInputQueue = failedTupleInputQueue; this.latch = latch; this.clock = clock; } @Override public void run() { try { logger.info("Opening {} spout", spout.getConsumerId()); // Rename thread to use the spout's consumer id Thread.currentThread().setName(spout.getConsumerId()); spout.open(); ackedTupleInputQueue.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>()); failedTupleInputQueue.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>()); latch.countDown(); long lastFlush = clock.millis(); // Loop forever until someone requests the spout to stop while (!spout.isStopRequested()) { // First look for any new tuples to be emitted. logger.debug("Requesting next tuple for spout {}", spout.getConsumerId()); final KafkaMessage message = spout.nextTuple(); if (message != null) { try { tupleOutputQueue.put(message); } catch (InterruptedException ex) { // TODO: Revisit this logger.error("{}", ex); } } // Lemon's note: Should we ack and then remove from the queue? What happens in the event // of a failure in ack(), the tuple will be removed from the queue despite a failed ack // Ack anything that needs to be acked while (!ackedTupleInputQueue.get(spout.getConsumerId()).isEmpty()) { TupleMessageId id = ackedTupleInputQueue.get(spout.getConsumerId()).poll(); spout.ack(id); } // Fail anything that needs to be failed while (!failedTupleInputQueue.get(spout.getConsumerId()).isEmpty()) { TupleMessageId id = failedTupleInputQueue.get(spout.getConsumerId()).poll(); spout.fail(id); } // Periodically we flush the state of the spout to capture progress if (lastFlush + FLUSH_INTERVAL_MS < clock.millis()) { logger.info("Flushing state for spout {}", spout.getConsumerId()); spout.flushState(); lastFlush = clock.millis(); } } // Looks like someone requested that we stop this instance. // So we call close on it. logger.info("Finishing {} spout", spout.getConsumerId()); spout.close(); // Remove our entries from the acked and failed queue. ackedTupleInputQueue.remove(spout.getConsumerId()); failedTupleInputQueue.remove(spout.getConsumerId()); } catch (Exception ex) { // TODO: Should we restart the SpoutRunner? logger.error("SpoutRunner for {} threw an exception {}", spout.getConsumerId(), ex); } } public void requestStop() { this.spout.requestStop(); } } }
src/main/java/com/salesforce/storm/spout/sideline/SpoutCoordinator.java
package com.salesforce.storm.spout.sideline; import com.salesforce.storm.spout.sideline.kafka.DelegateSidelineSpout; import com.salesforce.storm.spout.sideline.metrics.MetricsRecorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Clock; import java.util.Map; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Spout Coordinator. * * Manages X number of spouts and coordinates their nextTuple(), ack() and fail() calls across threads */ public class SpoutCoordinator { private static final Logger logger = LoggerFactory.getLogger(SpoutCoordinator.class); /** * How long our monitor thread will sit around and sleep between monitoring * if new VirtualSpouts need to be started up, in Milliseconds. */ public static final int MONITOR_THREAD_SLEEP_MS = 2000; /** * How long we'll wait for all VirtualSpout's to cleanly shut down, before we stop * them with force, in Milliseconds. */ public static final int MAX_SPOUT_STOP_TIME_MS = 10000; /** * How often we'll make sure each VirtualSpout persists its state, in Milliseconds. */ public static final long FLUSH_INTERVAL_MS = 30000; /** * The size of the thread pool for running virtual spouts for sideline requests. */ public static final int SPOUT_RUNNER_THREAD_POOL_SIZE = 10; /** * Which Clock instance to get reference to the system time. * We use this to allow injecting a fake System clock in tests. * * ThreadSafety - Lucky for us, Clock is all thread safe :) */ private Clock clock = Clock.systemUTC(); /** * Queue of spouts that need to be passed to the monitor and spun up. */ private final Queue<DelegateSidelineSpout> newSpoutQueue = new ConcurrentLinkedQueue<>(); /** * Buffer by spout consumer id of messages that have been acked. */ private final Map<String,Queue<TupleMessageId>> ackedTuplesInputQueue = new ConcurrentHashMap<>(); /** * Buffer by spout consumer id of messages that have been failed. */ private final Map<String,Queue<TupleMessageId>> failedTuplesInputQueue = new ConcurrentHashMap<>(); /** * Thread Pool Executor. */ private final ExecutorService executor; /** * For capturing metrics. */ private final MetricsRecorder metricsRecorder; /** * The spout monitor runnable, which handles spinning up threads for sideline spouts. */ private SpoutMonitor spoutMonitor; /** * Flag that gets set to false on shutdown, to signal to close up shop. * This probably should be renamed at some point. */ private boolean isOpen = false; /** * Create a new coordinator, supplying the 'fire hose' or the starting spouts. * @param spout Fire hose spout */ public SpoutCoordinator(final DelegateSidelineSpout spout, final MetricsRecorder metricsRecorder) { this.executor = Executors.newFixedThreadPool(SPOUT_RUNNER_THREAD_POOL_SIZE); this.metricsRecorder = metricsRecorder; addSidelineSpout(spout); } /** * Add a new spout to the coordinator, this will get picked up by the coordinator's monitor, opened and * managed with teh other currently running spouts. * @param spout New delegate spout */ public void addSidelineSpout(final DelegateSidelineSpout spout) { newSpoutQueue.add(spout); } /** * Open the coordinator and begin spinning up virtual spout threads. * @param queue The queue to put messages onto */ public void open(final BlockingQueue queue) { isOpen = true; final CountDownLatch latch = new CountDownLatch(newSpoutQueue.size()); spoutMonitor = new SpoutMonitor( executor, newSpoutQueue, queue, ackedTuplesInputQueue, failedTuplesInputQueue, latch, clock ); executor.submit(spoutMonitor); try { latch.await(); } catch (InterruptedException ex) { logger.error("Exception while waiting for the coordinator to open it's spouts {}", ex); } } /** * Acks a tuple on the spout that it belongs to. * @param id Tuple message id to ack */ public void ack(final TupleMessageId id) { if (!ackedTuplesInputQueue.containsKey(id.getSrcConsumerId())) { logger.warn("Acking tuple for unknown consumer"); return; } ackedTuplesInputQueue.get(id.getSrcConsumerId()).add(id); } /** * Fails a tuple on the spout that it belongs to. * @param id Tuple message id to fail */ public void fail(final TupleMessageId id) { if (!failedTuplesInputQueue.containsKey(id.getSrcConsumerId())) { logger.warn("Failing tuple for unknown consumer"); return; } failedTuplesInputQueue.get(id.getSrcConsumerId()).add(id); } /** * Stop coordinating spouts, calling this should shut down and finish the coordinator's spouts. */ public void close() { spoutMonitor.close(); try { executor.awaitTermination(MAX_SPOUT_STOP_TIME_MS, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.error("Caught Exception while stopping: {}", ex); } executor.shutdownNow(); // Will trigger the monitor thread to stop running, which should be the end of it isOpen = false; } /** * For testing, returns the total number of running spouts. * @return The total number of spouts the coordinator is running */ int getTotalSpouts() { return spoutMonitor.getTotalSpouts(); } /** * Monitors the lifecycle of spinning up virtual spouts. */ private static class SpoutMonitor implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SpoutMonitor.class); private final ExecutorService executor; private final Queue<DelegateSidelineSpout> spouts; private final BlockingQueue queue; private final Map<String,Queue<TupleMessageId>> acked; private final Map<String,Queue<TupleMessageId>> failed; private final CountDownLatch latch; private final Clock clock; private final Map<String,SpoutRunner> spoutRunners = new ConcurrentHashMap<>(); private final Map<String,Future> spoutThreads = new ConcurrentHashMap<>(); private boolean isOpen = true; SpoutMonitor( final ExecutorService executor, final Queue<DelegateSidelineSpout> spouts, final BlockingQueue queue, final Map<String,Queue<TupleMessageId>> acked, final Map<String,Queue<TupleMessageId>> failed, final CountDownLatch latch, final Clock clock ) { this.executor = executor; this.spouts = spouts; this.queue = queue; this.acked = acked; this.failed = failed; this.latch = latch; this.clock = clock; } @Override public void run() { try { // Rename our thread. Thread.currentThread().setName("SidelineSpout-NewSpoutMonitor"); // Start monitoring loop. while (isOpen) { logger.info("Still here.. my input queue is {}", spouts.size()); for (DelegateSidelineSpout spout; (spout = spouts.poll()) != null;) { logger.info("Preparing thread for spout {}", spout.getConsumerId()); final SpoutRunner spoutRunner = new SpoutRunner( spout, queue, acked, failed, latch, clock ); spoutRunners.put(spout.getConsumerId(), spoutRunner); final Future spoutInstance = executor.submit(spoutRunner); spoutThreads.put(spout.getConsumerId(), spoutInstance); } // Pause for a period before checking for more spouts try { Thread.sleep(MONITOR_THREAD_SLEEP_MS); } catch (InterruptedException ex) { logger.warn("!!!!!! Thread interrupted, shutting down..."); return; } } logger.warn("!!!!!! Spout coordinator is ceasing to run..."); } catch (Exception ex) { // TODO: Should we restart the monitor? logger.error("SpoutMonitor threw an exception {}", ex); } } public void close() { isOpen = false; for (SpoutRunner spoutRunner : spoutRunners.values()) { spoutRunner.requestStop(); } spoutRunners.clear(); spoutThreads.clear(); } public int getTotalSpouts() { return spoutRunners.size(); } } private static class SpoutRunner implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SpoutRunner.class); private final DelegateSidelineSpout spout; private final BlockingQueue queue; private final Map<String,Queue<TupleMessageId>> acked; private final Map<String,Queue<TupleMessageId>> failed; private final CountDownLatch latch; private final Clock clock; SpoutRunner( final DelegateSidelineSpout spout, final BlockingQueue queue, final Map<String,Queue<TupleMessageId>> acked, final Map<String,Queue<TupleMessageId>> failed, final CountDownLatch latch, final Clock clock ) { this.spout = spout; this.queue = queue; this.acked = acked; this.failed = failed; this.latch = latch; this.clock = clock; } @Override public void run() { try { logger.info("Opening {} spout", spout.getConsumerId()); // Rename thread to use the spout's consumer id Thread.currentThread().setName(spout.getConsumerId()); spout.open(); acked.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>()); failed.put(spout.getConsumerId(), new ConcurrentLinkedQueue<>()); latch.countDown(); long lastFlush = clock.millis(); // Loop forever until someone requests the spout to stop while (!spout.isStopRequested()) { // First look for any new tuples to be emitted. logger.debug("Requesting next tuple for spout {}", spout.getConsumerId()); final KafkaMessage message = spout.nextTuple(); if (message != null) { try { queue.put(message); } catch (InterruptedException ex) { // TODO: Revisit this logger.error("{}", ex); } } // Lemon's note: Should we ack and then remove from the queue? What happens in the event // of a failure in ack(), the tuple will be removed from the queue despite a failed ack // Ack anything that needs to be acked while (!acked.get(spout.getConsumerId()).isEmpty()) { TupleMessageId id = acked.get(spout.getConsumerId()).poll(); spout.ack(id); } // Fail anything that needs to be failed while (!failed.get(spout.getConsumerId()).isEmpty()) { TupleMessageId id = failed.get(spout.getConsumerId()).poll(); spout.fail(id); } // Periodically we flush the state of the spout to capture progress if (lastFlush + FLUSH_INTERVAL_MS < clock.millis()) { logger.info("Flushing state for spout {}", spout.getConsumerId()); spout.flushState(); lastFlush = clock.millis(); } } // Looks like someone requested that we stop this instance. // So we call close on it. logger.info("Finishing {} spout", spout.getConsumerId()); spout.close(); // Remove our entries from the acked and failed queue. acked.remove(spout.getConsumerId()); failed.remove(spout.getConsumerId()); } catch (Exception ex) { // TODO: Should we restart the SpoutRunner? logger.error("SpoutRunner for {} threw an exception {}", spout.getConsumerId(), ex); } } public void requestStop() { this.spout.requestStop(); } } }
Rename some properties
src/main/java/com/salesforce/storm/spout/sideline/SpoutCoordinator.java
Rename some properties
Java
mit
965bde15e839382fa7841cfecd231ca43593fa2f
0
maillouxc/git-rekt
package com.gitrekt.resort.controller; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; /** * FXML Controller class for the staff home screen. */ public class StaffHomeScreenController implements Initializable { @FXML private Button viewReportsButton; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } public void onViewReportsButtonClicked() throws IOException { Stage mainStage = (Stage) viewReportsButton.getScene().getWindow(); Parent viewReportsScreenRoot = FXMLLoader.load( getClass().getResource("/fxml/ViewReportsScreenController.fxml") ); Scene viewReportsScreen = new Scene(viewReportsScreenRoot); mainStage.setScene(viewReportsScreen); } }
src/main/java/com/gitrekt/resort/controller/StaffHomeScreenController.java
package com.gitrekt.resort.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.Initializable; /** * FXML Controller class for the staff home screen. */ public class StaffHomeScreenController implements Initializable { /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
Display view reports screen on button click
src/main/java/com/gitrekt/resort/controller/StaffHomeScreenController.java
Display view reports screen on button click
Java
mit
0698bc769d3389bd99ebb3afd46f539eddbc1620
0
berryma4/diirt,richardfearn/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,berryma4/diirt,diirt/diirt,diirt/diirt,berryma4/diirt,diirt/diirt,ControlSystemStudio/diirt,richardfearn/diirt,richardfearn/diirt,ControlSystemStudio/diirt
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.pvmanager.formula; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import org.epics.util.array.ArrayDouble; import org.epics.util.text.NumberFormats; import org.epics.util.time.Timestamp; import org.epics.vtype.Alarm; import org.epics.vtype.AlarmSeverity; import org.epics.vtype.Display; import org.epics.vtype.Time; import org.epics.vtype.VBoolean; import org.epics.vtype.VDouble; import org.epics.vtype.VNumber; import org.epics.vtype.VNumberArray; import org.epics.vtype.VString; import org.epics.vtype.VStringArray; import org.epics.vtype.VType; import org.epics.vtype.VTypeToString; import org.epics.vtype.VTypeValueEquals; import org.epics.vtype.ValueFactory; import static org.epics.vtype.ValueFactory.*; import org.epics.vtype.ValueUtil; import org.epics.vtype.table.Column; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.*; import org.junit.Assert; import static org.junit.Assert.assertThat; /** * * @author carcassi */ public class FunctionTester { private final FormulaFunction function; private boolean convertTypes = true; private FunctionTester(FormulaFunction function) { this.function = function; } public static FunctionTester findByName(FormulaFunctionSet set, String name) { Collection<FormulaFunction> functions = set.findFunctions(name); assertThat("Function '" + name + "' not found.", functions.isEmpty(), equalTo(false)); assertThat("Multiple matches for function '" + name + "'.", functions.size(), equalTo(1)); return new FunctionTester(functions.iterator().next()); } public static FunctionTester findBySignature(FormulaFunctionSet set, String name, Class<?>... argTypes) { Collection<FormulaFunction> functions = set.findFunctions(name); assertThat("Function '" + name + "' not found.", functions.isEmpty(), equalTo(false)); functions = FormulaFunctions.findArgTypeMatch(Arrays.asList(argTypes), functions); assertThat("No matches found for function '" + name + "'.", functions.isEmpty(), equalTo(false)); assertThat("Multiple matches for function '" + name + "'.", functions.size(), equalTo(1)); return new FunctionTester(functions.iterator().next()); } public FunctionTester convertTypes(boolean convertTypes) { this.convertTypes = convertTypes; return this; } public FunctionTester matchReturnValue(Matcher<Object> matcher, Object... args) { if (convertTypes) { args = convertTypes(args); } Object result = function.calculate(Arrays.asList(args)); Assert.assertThat(result, matcher); return this; } public FunctionTester compareReturnValue(Object expected, Object... args) { if (convertTypes) { expected = convertType(expected); args = convertTypes(args); } Object result = function.calculate(Arrays.asList(args)); if (result instanceof VDouble && expected instanceof VDouble) { assertThat("Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'.", ((VDouble) result).getValue().doubleValue(), closeTo(((VDouble) expected).getValue().doubleValue(), 0.0001)); } else { assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + result + ") expected (" + expected + ")", compareValues(result, expected), equalTo(true)); } return this; } public static boolean compareValues(Object obj1, Object obj2) { if (Objects.equals(obj1, obj2)) { return true; } if (obj1 instanceof VType && obj2 instanceof VType) { return VTypeValueEquals.valueEquals(obj1, obj2); } else if (obj1 instanceof Column && obj2 instanceof Column) { Column column1 = (Column) obj1; Column column2 = (Column) obj2; return column1.getName().equals(column2.getName()) && column1.isGenerated() == column2.isGenerated() && column1.getType().equals(column2.getType()) && column1.getData(column1.isGenerated() ? 10 : -1).equals(column2.getData(column2.isGenerated() ? 10 : -1)); } return false; } private Object convertType(Object obj) { if (obj instanceof VType) { return obj; } Object converted = ValueFactory.toVType(obj); if (converted != null) { return converted; } return obj; } private Object[] convertTypes(Object... obj) { Object[] result = new Object[obj.length]; for (int i = 0; i < result.length; i++) { result[i] = convertType(obj[i]); } return result; } public FunctionTester compareReturnAlarm(Alarm expected, Object... args) { if (convertTypes) { args = convertTypes(args); } Alarm result = ValueUtil.alarmOf(function.calculate(Arrays.asList(args))); assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + VTypeToString.alarmToString(result) + ") expected (" + VTypeToString.alarmToString(expected) + ")", VTypeValueEquals.alarmEquals(result, expected), equalTo(true)); return this; } public FunctionTester compareReturnTime(Time expected, Object... args) { if (convertTypes) { args = convertTypes(args); } Time result = ValueUtil.timeOf(function.calculate(Arrays.asList(args))); assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + VTypeToString.timeToString(result) + ") expected (" + VTypeToString.timeToString(expected) + ")", VTypeValueEquals.timeEquals(result, expected), equalTo(true)); return this; } public FunctionTester highestAlarmReturned() { if (function.isVarArgs() || function.getArgumentTypes().size() > 1) { highestAlarmReturnedMultipleArgs(function); } else { highestAlarmReturnedSingleArg(function); } return this; } private Object createValue(Class<?> clazz, Alarm alarm, Time time, Display display) { if (clazz.equals(VNumber.class)) { return newVNumber(1.0, alarm, time, display); } else if (clazz.equals(VNumberArray.class)) { return newVNumberArray(new ArrayDouble(1.0), alarm, time, display); } else if (clazz.equals(VString.class)) { return newVString("A", alarm, time); } else if (clazz.equals(VStringArray.class)) { return newVStringArray(Arrays.asList("A"), alarm, time); } else if (clazz.equals(VBoolean.class)) { return newVBoolean(true, alarm, time); } else { throw new IllegalArgumentException("Can't create sample argument for class " + clazz); } } private void highestAlarmReturnedSingleArg(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Alarm none = alarmNone(); Alarm minor = newAlarm(AlarmSeverity.MINOR, "HIGH"); Alarm major = newAlarm(AlarmSeverity.MAJOR, "LOLO"); compareReturnAlarm(none, createValue(function.getArgumentTypes().get(0), none, timeNow(), display)); compareReturnAlarm(minor, createValue(function.getArgumentTypes().get(0), minor, timeNow(), display)); compareReturnAlarm(major, createValue(function.getArgumentTypes().get(0), major, timeNow(), display)); } private void highestAlarmReturnedMultipleArgs(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; if (function.isVarArgs()) { args = new Object[function.getArgumentTypes().size() + 1]; } else { args = new Object[function.getArgumentTypes().size()]; } Alarm none = alarmNone(); Alarm minor = newAlarm(AlarmSeverity.MINOR, "HIGH"); Alarm major = newAlarm(AlarmSeverity.MAJOR, "LOLO"); // Prepare arguments with no alarm for (int i = 0; i < function.getArgumentTypes().size(); i++) { args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display); } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display); } compareReturnAlarm(none, args); // Prepare arguments with one minor and everything else none for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display); } else { args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display); } compareReturnAlarm(minor, args); // Prepare arguments with one minor and everything else major for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), major, timeNow(), display); } else { args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), major, timeNow(), display); } compareReturnAlarm(major, args); } public FunctionTester latestTimeReturned() { if (function.isVarArgs() || function.getArgumentTypes().size() > 1) { latestTimeReturnedMultipleArgs(function); } else { latestTimeReturnedSingleArg(function); } return this; } private void latestTimeReturnedSingleArg(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; Time time1 = newTime(Timestamp.of(12340000, 0)); Time time2 = newTime(Timestamp.of(12350000, 0)); compareReturnTime(time1, createValue(function.getArgumentTypes().get(0), alarmNone(), time1, display)); compareReturnTime(time2, createValue(function.getArgumentTypes().get(0), alarmNone(), time2, display)); } private void latestTimeReturnedMultipleArgs(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; if (function.isVarArgs()) { args = new Object[function.getArgumentTypes().size() + 1]; } else { args = new Object[function.getArgumentTypes().size()]; } Time time1 = newTime(Timestamp.of(12340000, 0)); Time time2 = newTime(Timestamp.of(12350000, 0)); // Prepare arguments with all time1 for (int i = 0; i < function.getArgumentTypes().size(); i++) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display); } compareReturnTime(time1, args); // Prepare arguments with one time2 and everything else time1 for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } else { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display); } compareReturnTime(time2, args); // Prepare arguments with one minor and everything else major for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display); } else { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time2, display); } compareReturnTime(time2, args); } }
pvmanager-extra/src/test/java/org/epics/pvmanager/formula/FunctionTester.java
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.pvmanager.formula; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import org.epics.util.array.ArrayDouble; import org.epics.util.text.NumberFormats; import org.epics.util.time.Timestamp; import org.epics.vtype.Alarm; import org.epics.vtype.AlarmSeverity; import org.epics.vtype.Display; import org.epics.vtype.Time; import org.epics.vtype.VBoolean; import org.epics.vtype.VDouble; import org.epics.vtype.VNumber; import org.epics.vtype.VNumberArray; import org.epics.vtype.VString; import org.epics.vtype.VStringArray; import org.epics.vtype.VType; import org.epics.vtype.VTypeToString; import org.epics.vtype.VTypeValueEquals; import org.epics.vtype.ValueFactory; import static org.epics.vtype.ValueFactory.*; import org.epics.vtype.ValueUtil; import org.epics.vtype.table.Column; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.*; import org.junit.Assert; import static org.junit.Assert.assertThat; /** * * @author carcassi */ public class FunctionTester { private final FormulaFunction function; private boolean convertTypes = true; private FunctionTester(FormulaFunction function) { this.function = function; } public static FunctionTester findByName(FormulaFunctionSet set, String name) { Collection<FormulaFunction> functions = set.findFunctions(name); assertThat("Function '" + name + "' not found.", functions.isEmpty(), equalTo(false)); assertThat("Multiple matches for function '" + name + "'.", functions.size(), equalTo(1)); return new FunctionTester(functions.iterator().next()); } public static FunctionTester findBySignature(FormulaFunctionSet set, String name, Class<?>... argTypes) { Collection<FormulaFunction> functions = set.findFunctions(name); assertThat("Function '" + name + "' not found.", functions.isEmpty(), equalTo(false)); functions = FormulaFunctions.findArgTypeMatch(Arrays.asList(argTypes), functions); assertThat("No matches found for function '" + name + "'.", functions.isEmpty(), equalTo(false)); assertThat("Multiple matches for function '" + name + "'.", functions.size(), equalTo(1)); return new FunctionTester(functions.iterator().next()); } public FunctionTester convertTypes(boolean convertTypes) { this.convertTypes = convertTypes; return this; } public FunctionTester matchReturnValue(Matcher<Object> matcher, Object... args) { if (convertTypes) { args = convertTypes(args); } Object result = function.calculate(Arrays.asList(args)); Assert.assertThat(result, matcher); return this; } public FunctionTester compareReturnValue(Object expected, Object... args) { if (convertTypes) { expected = convertType(expected); args = convertTypes(args); } Object result = function.calculate(Arrays.asList(args)); if (result instanceof VDouble && expected instanceof VDouble) { assertThat("Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'.", ((VDouble) result).getValue().doubleValue(), closeTo(((VDouble) expected).getValue().doubleValue(), 0.0001)); } else { assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + result + ") expected (" + expected + ")", compareValues(result, expected), equalTo(true)); } return this; } public static boolean compareValues(Object obj1, Object obj2) { if (Objects.equals(obj1, obj2)) { return true; } if (obj1 instanceof VType && obj2 instanceof VType) { return VTypeValueEquals.valueEquals(obj1, obj2); } else if (obj1 instanceof Column && obj2 instanceof Column) { Column column1 = (Column) obj1; Column column2 = (Column) obj2; return column1.getName().equals(column2.getName()) && column1.isGenerated() == column2.isGenerated() && column1.getType().equals(column2.getType()) && column1.getData(10).equals(column2.getData(10)); } return false; } private Object convertType(Object obj) { if (obj instanceof VType) { return obj; } Object converted = ValueFactory.toVType(obj); if (converted != null) { return converted; } return obj; } private Object[] convertTypes(Object... obj) { Object[] result = new Object[obj.length]; for (int i = 0; i < result.length; i++) { result[i] = convertType(obj[i]); } return result; } public FunctionTester compareReturnAlarm(Alarm expected, Object... args) { if (convertTypes) { args = convertTypes(args); } Alarm result = ValueUtil.alarmOf(function.calculate(Arrays.asList(args))); assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + VTypeToString.alarmToString(result) + ") expected (" + VTypeToString.alarmToString(expected) + ")", VTypeValueEquals.alarmEquals(result, expected), equalTo(true)); return this; } public FunctionTester compareReturnTime(Time expected, Object... args) { if (convertTypes) { args = convertTypes(args); } Time result = ValueUtil.timeOf(function.calculate(Arrays.asList(args))); assertThat( "Wrong result for function '" + function.getName() + "(" + Arrays.toString(args) + ")'. Was (" + VTypeToString.timeToString(result) + ") expected (" + VTypeToString.timeToString(expected) + ")", VTypeValueEquals.timeEquals(result, expected), equalTo(true)); return this; } public FunctionTester highestAlarmReturned() { if (function.isVarArgs() || function.getArgumentTypes().size() > 1) { highestAlarmReturnedMultipleArgs(function); } else { highestAlarmReturnedSingleArg(function); } return this; } private Object createValue(Class<?> clazz, Alarm alarm, Time time, Display display) { if (clazz.equals(VNumber.class)) { return newVNumber(1.0, alarm, time, display); } else if (clazz.equals(VNumberArray.class)) { return newVNumberArray(new ArrayDouble(1.0), alarm, time, display); } else if (clazz.equals(VString.class)) { return newVString("A", alarm, time); } else if (clazz.equals(VStringArray.class)) { return newVStringArray(Arrays.asList("A"), alarm, time); } else if (clazz.equals(VBoolean.class)) { return newVBoolean(true, alarm, time); } else { throw new IllegalArgumentException("Can't create sample argument for class " + clazz); } } private void highestAlarmReturnedSingleArg(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Alarm none = alarmNone(); Alarm minor = newAlarm(AlarmSeverity.MINOR, "HIGH"); Alarm major = newAlarm(AlarmSeverity.MAJOR, "LOLO"); compareReturnAlarm(none, createValue(function.getArgumentTypes().get(0), none, timeNow(), display)); compareReturnAlarm(minor, createValue(function.getArgumentTypes().get(0), minor, timeNow(), display)); compareReturnAlarm(major, createValue(function.getArgumentTypes().get(0), major, timeNow(), display)); } private void highestAlarmReturnedMultipleArgs(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; if (function.isVarArgs()) { args = new Object[function.getArgumentTypes().size() + 1]; } else { args = new Object[function.getArgumentTypes().size()]; } Alarm none = alarmNone(); Alarm minor = newAlarm(AlarmSeverity.MINOR, "HIGH"); Alarm major = newAlarm(AlarmSeverity.MAJOR, "LOLO"); // Prepare arguments with no alarm for (int i = 0; i < function.getArgumentTypes().size(); i++) { args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display); } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display); } compareReturnAlarm(none, args); // Prepare arguments with one minor and everything else none for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), none, timeNow(), display); } else { args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), none, timeNow(), display); } compareReturnAlarm(minor, args); // Prepare arguments with one minor and everything else major for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), major, timeNow(), display); } else { args[i] = createValue(function.getArgumentTypes().get(i), minor, timeNow(), display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), major, timeNow(), display); } compareReturnAlarm(major, args); } public FunctionTester latestTimeReturned() { if (function.isVarArgs() || function.getArgumentTypes().size() > 1) { latestTimeReturnedMultipleArgs(function); } else { latestTimeReturnedSingleArg(function); } return this; } private void latestTimeReturnedSingleArg(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; Time time1 = newTime(Timestamp.of(12340000, 0)); Time time2 = newTime(Timestamp.of(12350000, 0)); compareReturnTime(time1, createValue(function.getArgumentTypes().get(0), alarmNone(), time1, display)); compareReturnTime(time2, createValue(function.getArgumentTypes().get(0), alarmNone(), time2, display)); } private void latestTimeReturnedMultipleArgs(FormulaFunction function) { Display display = newDisplay(-5.0, -4.0, -3.0, "m", NumberFormats.toStringFormat(), 3.0, 4.0, 5.0, -5.0, 5.0); Object[] args; if (function.isVarArgs()) { args = new Object[function.getArgumentTypes().size() + 1]; } else { args = new Object[function.getArgumentTypes().size()]; } Time time1 = newTime(Timestamp.of(12340000, 0)); Time time2 = newTime(Timestamp.of(12350000, 0)); // Prepare arguments with all time1 for (int i = 0; i < function.getArgumentTypes().size(); i++) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display); } compareReturnTime(time1, args); // Prepare arguments with one time2 and everything else time1 for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } else { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time1, display); } compareReturnTime(time2, args); // Prepare arguments with one minor and everything else major for (int i = 0; i < function.getArgumentTypes().size(); i++) { if (i == args.length - 1) { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time2, display); } else { args[i] = createValue(function.getArgumentTypes().get(i), alarmNone(), time1, display); } } if (function.isVarArgs()) { args[args.length - 1] = createValue(function.getArgumentTypes().get(args.length - 2), alarmNone(), time2, display); } compareReturnTime(time2, args); } }
formula: fixing compareValue for columns
pvmanager-extra/src/test/java/org/epics/pvmanager/formula/FunctionTester.java
formula: fixing compareValue for columns
Java
mit
73cb70c2c651189121cb0754a6118c8aec37a78e
0
eaglerainbow/docker-plugin,jenkinsci/docker-plugin,jenkinsci/docker-plugin,jenkinsci/docker-plugin,eaglerainbow/docker-plugin,eaglerainbow/docker-plugin
package com.nirima.jenkins.plugins.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.PushImageCmd; import com.github.dockerjava.api.exception.DockerException; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.Identifier; import com.github.dockerjava.api.model.PushResponseItem; import com.github.dockerjava.core.NameParser; import com.github.dockerjava.core.command.PushImageResultCallback; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.nirima.jenkins.plugins.docker.action.DockerBuildAction; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.Descriptor; import hudson.model.Queue; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.queue.CauseOfBlockage; import hudson.slaves.AbstractCloudSlave; import hudson.slaves.Cloud; import hudson.slaves.ComputerLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.RetentionStrategy; import jenkins.model.Jenkins; import org.jenkinsci.plugins.tokenmacro.TokenMacro; import javax.annotation.CheckForNull; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.nirima.jenkins.plugins.docker.utils.JenkinsUtils.getAuthConfigFor; import static com.nirima.jenkins.plugins.docker.utils.LogUtils.printResponseItemToListener; import static org.apache.commons.lang.StringUtils.isEmpty; public class DockerSlave extends AbstractCloudSlave { private static final Logger LOGGER = Logger.getLogger(DockerSlave.class.getName()); public DockerTemplate dockerTemplate; // remember container id @CheckForNull private String containerId; // remember cloud name @CheckForNull private String cloudId; private transient Run theRun; public DockerSlave(DockerTemplate dockerTemplate, String containerId, String name, String nodeDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws Descriptor.FormException, IOException { super(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, nodeProperties); Preconditions.checkNotNull(dockerTemplate); Preconditions.checkNotNull(containerId); setDockerTemplate(dockerTemplate); this.containerId = containerId; } public DockerSlave(String slaveName, String nodeDescription, ComputerLauncher launcher, String containerId, DockerTemplate dockerTemplate, String cloudId) throws IOException, Descriptor.FormException { super(slaveName, nodeDescription, //description dockerTemplate.getRemoteFs(), dockerTemplate.getNumExecutors(), dockerTemplate.getMode(), dockerTemplate.getLabelString(), launcher, dockerTemplate.getRetentionStrategyCopy(), dockerTemplate.getNodeProperties() ); setContainerId(containerId); setDockerTemplate(dockerTemplate); setCloudId(cloudId); } public DockerSlave(DockerCloud cloud, DockerTemplate template, ComputerLauncher launcher) throws IOException, Descriptor.FormException { super( cloud.getDisplayName() + '-' + Long.toHexString(System.nanoTime()), "Docker Node [" + template.getDockerTemplateBase().getImage() + " on "+ cloud.getDisplayName() + "]", template.getRemoteFs(), template.getNumExecutors(), template.getMode(), template.getLabelString(), launcher, template.getRetentionStrategyCopy(), Collections.<NodeProperty<?>>emptyList() ); this.cloudId = cloud.getDisplayName(); this.dockerTemplate = template; } public String getContainerId() { return containerId; } public void setContainerId(String containerId) { this.containerId = containerId; } public String getCloudId() { return cloudId; } public void setCloudId(String cloudId) { this.cloudId = cloudId; } public DockerTemplate getDockerTemplate() { return dockerTemplate; } public void setDockerTemplate(DockerTemplate dockerTemplate) { this.dockerTemplate = dockerTemplate; } public DockerCloud getCloud() { final Cloud cloud = Jenkins.getInstance().getCloud(getCloudId()); if (cloud == null) { throw new RuntimeException("Docker template " + dockerTemplate + " has no assigned Cloud."); } if (cloud.getClass() != DockerCloud.class) { throw new RuntimeException("Assigned cloud is not DockerCloud"); } return (DockerCloud) cloud; } @Override public DockerComputer getComputer() { return (DockerComputer) super.getComputer(); } @Override public String getDisplayName() { return name; } public void setRun(Run run) { this.theRun = run; } @Override public DockerComputer createComputer() { return new DockerComputer(this); } @Override public CauseOfBlockage canTake(Queue.BuildableItem item) { if (item.task instanceof Queue.FlyweightTask) { return new CauseOfBlockage() { public String getShortDescription() { return "Don't run FlyweightTask on Docker node"; } }; } return super.canTake(item); } public boolean containerExistsInCloud() { try { DockerClient client = getClient(); client.inspectContainerCmd(containerId).exec(); return true; } catch (Exception ex) { return false; } } @Override protected void _terminate(TaskListener listener) throws IOException, InterruptedException { try { toComputer().disconnect(new DockerOfflineCause()); LOGGER.log(Level.INFO, "Disconnected computer"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Can't disconnect", e); } if (containerId != null) { try { DockerClient client = getClient(); client.stopContainerCmd(getContainerId()).exec(); LOGGER.log(Level.INFO, "Stopped container {0}", getContainerId()); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Failed to stop instance " + getContainerId() + " for slave " + name + " due to exception", ex.getMessage()); LOGGER.log(Level.SEVERE, "Causing exception for failure on stopping the instance was", ex); } // If the run was OK, then do any tagging here if (theRun != null) { try { slaveShutdown(listener); LOGGER.log(Level.INFO, "Shutdowned slave for {0}", getContainerId()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failure to slaveShutdown instance " + getContainerId() + " for slave " + name, e); LOGGER.log(Level.SEVERE, "Causing exception for failure on slaveShutdown was", e); } } try { DockerClient client = getClient(); client.removeContainerCmd(containerId) .withRemoveVolumes(getDockerTemplate().isRemoveVolumes()) .exec(); LOGGER.log(Level.INFO, "Removed container {0}", getContainerId()); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Failed to remove instance " + getContainerId() + " for slave " + name + " due to exception: " + ex.getMessage()); LOGGER.log(Level.SEVERE, "Causing exception for failre on removing instance was", ex); } } else { LOGGER.log(Level.SEVERE, "ContainerId is absent, no way to remove/stop container"); } } private void slaveShutdown(final TaskListener listener) throws DockerException, IOException { // The slave has stopped. Should we commit / tag / push ? if (!getJobProperty().tagOnCompletion) { addJenkinsAction(null); return; } DockerClient client = getClient(); // Commit String tag_image = client.commitCmd(containerId) .withRepository(theRun.getParent().getDisplayName()) .withTag(theRun.getDisplayName().replace("#", "b")) // allowed only ([a-zA-Z_][a-zA-Z0-9_]*) .withAuthor("Jenkins") .exec(); // Tag it with the jenkins name addJenkinsAction(tag_image); // SHould we add additional tags? try { String tagToken = getAdditionalTag(listener); if (!Strings.isNullOrEmpty(tagToken)) { final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(tagToken); final String commitTag = isEmpty(reposTag.tag) ? "latest" : reposTag.tag; getClient().tagImageCmd(tag_image, reposTag.repos, commitTag).withForce().exec(); addJenkinsAction(tagToken); if (getJobProperty().pushOnSuccess) { Identifier identifier = Identifier.fromCompoundString(tagToken); PushImageResultCallback resultCallback = new PushImageResultCallback() { public void onNext(PushResponseItem item) { printResponseItemToListener(listener, item); super.onNext(item); } }; try { PushImageCmd cmd = getClient().pushImageCmd(identifier); AuthConfig authConfig = getAuthConfigFor(tagToken); if( authConfig != null ) { cmd.withAuthConfig(authConfig); } cmd.exec(resultCallback).awaitSuccess(); } catch(DockerException ex) { LOGGER.log(Level.SEVERE, "Exception pushing docker image. Check that the destination registry is running.", ex); throw ex; } } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Could not add additional tags", ex); } if (getJobProperty().cleanImages) { client.removeImageCmd(tag_image) .withForce(true) .exec(); } } private String getAdditionalTag(TaskListener listener) { // Do a macro expansion on the addJenkinsAction token // Job property String tagToken = getJobProperty().additionalTag; // Do any macro expansions try { if (!Strings.isNullOrEmpty(tagToken)) tagToken = TokenMacro.expandAll((AbstractBuild) theRun, listener, tagToken); } catch (Exception e) { LOGGER.log(Level.WARNING, "can't expand macroses", e); } return tagToken; } /** * Add a built on docker action. */ private void addJenkinsAction(String tag_image) throws IOException { theRun.addAction(new DockerBuildAction(getCloud().getServerUrl(), containerId, tag_image, dockerTemplate.remoteFsMapping)); theRun.save(); } public DockerClient getClient() { return getCloud().getClient(); } private DockerJobProperty getJobProperty() { try { DockerJobProperty p = (DockerJobProperty) ((AbstractBuild) theRun).getProject().getProperty(DockerJobProperty.class); if (p != null) return p; } catch (Exception ex) { // Don't care. } // Safe default return new DockerJobProperty(false, null, false, true, null); } @Override public String toString() { return Objects.toStringHelper(this) .add("name", name) .add("containerId", containerId) .add("template", dockerTemplate) .toString(); } @Extension public static final class DescriptorImpl extends SlaveDescriptor { @Override public String getDisplayName() { return "Docker Slave"; } @Override public boolean isInstantiable() { return false; } } }
docker-plugin/src/main/java/com/nirima/jenkins/plugins/docker/DockerSlave.java
package com.nirima.jenkins.plugins.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.PushImageCmd; import com.github.dockerjava.api.exception.DockerException; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.api.model.Identifier; import com.github.dockerjava.api.model.PushResponseItem; import com.github.dockerjava.core.NameParser; import com.github.dockerjava.core.command.PushImageResultCallback; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.nirima.jenkins.plugins.docker.action.DockerBuildAction; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.Descriptor; import hudson.model.Queue; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.queue.CauseOfBlockage; import hudson.slaves.AbstractCloudSlave; import hudson.slaves.Cloud; import hudson.slaves.ComputerLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.RetentionStrategy; import jenkins.model.Jenkins; import org.jenkinsci.plugins.tokenmacro.TokenMacro; import javax.annotation.CheckForNull; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static com.nirima.jenkins.plugins.docker.utils.JenkinsUtils.getAuthConfigFor; import static com.nirima.jenkins.plugins.docker.utils.LogUtils.printResponseItemToListener; import static org.apache.commons.lang.StringUtils.isEmpty; public class DockerSlave extends AbstractCloudSlave { private static final Logger LOGGER = Logger.getLogger(DockerSlave.class.getName()); public DockerTemplate dockerTemplate; // remember container id @CheckForNull private String containerId; // remember cloud name @CheckForNull private String cloudId; private transient Run theRun; public DockerSlave(DockerTemplate dockerTemplate, String containerId, String name, String nodeDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy retentionStrategy, List<? extends NodeProperty<?>> nodeProperties) throws Descriptor.FormException, IOException { super(name, nodeDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, nodeProperties); Preconditions.checkNotNull(dockerTemplate); Preconditions.checkNotNull(containerId); setDockerTemplate(dockerTemplate); this.containerId = containerId; } public DockerSlave(String slaveName, String nodeDescription, ComputerLauncher launcher, String containerId, DockerTemplate dockerTemplate, String cloudId) throws IOException, Descriptor.FormException { super(slaveName, nodeDescription, //description dockerTemplate.getRemoteFs(), dockerTemplate.getNumExecutors(), dockerTemplate.getMode(), dockerTemplate.getLabelString(), launcher, dockerTemplate.getRetentionStrategyCopy(), dockerTemplate.getNodeProperties() ); setContainerId(containerId); setDockerTemplate(dockerTemplate); setCloudId(cloudId); } public DockerSlave(DockerCloud cloud, DockerTemplate template, ComputerLauncher launcher) throws IOException, Descriptor.FormException { super( cloud.getDisplayName() + '-' + Long.toHexString(System.nanoTime()), "Docker Node [" + template.getDockerTemplateBase().getImage() + " on "+ cloud.getDisplayName() + "]", template.getRemoteFs(), template.getNumExecutors(), template.getMode(), template.getLabelString(), launcher, template.getRetentionStrategyCopy(), Collections.<NodeProperty<?>>emptyList() ); this.cloudId = cloud.getDisplayName(); this.dockerTemplate = template; } public String getContainerId() { return containerId; } public void setContainerId(String containerId) { this.containerId = containerId; } public String getCloudId() { return cloudId; } public void setCloudId(String cloudId) { this.cloudId = cloudId; } public DockerTemplate getDockerTemplate() { return dockerTemplate; } public void setDockerTemplate(DockerTemplate dockerTemplate) { this.dockerTemplate = dockerTemplate; } public DockerCloud getCloud() { final Cloud cloud = Jenkins.getInstance().getCloud(getCloudId()); if (cloud == null) { throw new RuntimeException("Docker template " + dockerTemplate + " has no assigned Cloud."); } if (cloud.getClass() != DockerCloud.class) { throw new RuntimeException("Assigned cloud is not DockerCloud"); } return (DockerCloud) cloud; } @Override public DockerComputer getComputer() { return (DockerComputer) super.getComputer(); } @Override public String getDisplayName() { return name; } public void setRun(Run run) { this.theRun = run; } @Override public DockerComputer createComputer() { return new DockerComputer(this); } @Override public CauseOfBlockage canTake(Queue.BuildableItem item) { if (item.task instanceof Queue.FlyweightTask) { return new CauseOfBlockage() { public String getShortDescription() { return "Don't run FlyweightTask on Docker node"; } }; } return super.canTake(item); } public boolean containerExistsInCloud() { try { DockerClient client = getClient(); client.inspectContainerCmd(containerId).exec(); return true; } catch (Exception ex) { return false; } } @Override protected void _terminate(TaskListener listener) throws IOException, InterruptedException { try { toComputer().disconnect(new DockerOfflineCause()); LOGGER.log(Level.INFO, "Disconnected computer"); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Can't disconnect", e); } if (containerId != null) { try { DockerClient client = getClient(); client.stopContainerCmd(getContainerId()).exec(); LOGGER.log(Level.INFO, "Stopped container {0}", getContainerId()); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Failed to stop instance " + getContainerId() + " for slave " + name + " due to exception", ex.getMessage()); LOGGER.log(Level.SEVERE, "Causing exception for failure on stopping the instance was", ex); } // If the run was OK, then do any tagging here if (theRun != null) { try { slaveShutdown(listener); LOGGER.log(Level.INFO, "Shutdowned slave for {0}", getContainerId()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Failure to slaveShutdown instance " + getContainerId() + " for slave " + name, e); LOGGER.log(Level.SEVERE, "Causing exception for failure on slaveShutdown was", e); } } try { DockerClient client = getClient(); client.removeContainerCmd(containerId) .withRemoveVolumes(getDockerTemplate().isRemoveVolumes()) .exec(); LOGGER.log(Level.INFO, "Removed container {0}", getContainerId()); } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Failed to remove instance " + getContainerId() + " for slave " + name + " due to exception: " + ex.getMessage()); LOGGER.log(Level.SEVERE, "Causing exception for failre on removing instance was", ex); } } else { LOGGER.log(Level.SEVERE, "ContainerId is absent, no way to remove/stop container"); } } private void slaveShutdown(final TaskListener listener) throws DockerException, IOException { // The slave has stopped. Should we commit / tag / push ? if (!getJobProperty().tagOnCompletion) { addJenkinsAction(null); return; } DockerClient client = getClient(); // Commit String tag_image = client.commitCmd(containerId) .withRepository(theRun.getParent().getDisplayName()) .withTag(theRun.getDisplayName().replace("#", "b")) // allowed only ([a-zA-Z_][a-zA-Z0-9_]*) .withAuthor("Jenkins") .exec(); // Tag it with the jenkins name addJenkinsAction(tag_image); // SHould we add additional tags? try { String tagToken = getAdditionalTag(listener); if (!Strings.isNullOrEmpty(tagToken)) { final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(tagToken); final String commitTag = isEmpty(reposTag.tag) ? "latest" : reposTag.tag; getClient().tagImageCmd(tag_image, reposTag.repos, commitTag).withForce().exec(); addJenkinsAction(tagToken); if (getJobProperty().pushOnSuccess) { Identifier identifier = Identifier.fromCompoundString(tagToken); PushImageResultCallback resultCallback = new PushImageResultCallback() { public void onNext(PushResponseItem item) { printResponseItemToListener(listener, item); super.onNext(item); } }; try { PushImageCmd cmd = getClient().pushImageCmd(identifier); AuthConfig authConfig = getAuthConfigFor(tagToken); if( authConfig != null ) { cmd.withAuthConfig(authConfig); } cmd.exec(resultCallback).awaitSuccess(); } catch(DockerException ex) { LOGGER.log(Level.SEVERE, "Exception pushing docker image. Check that the destination registry is running.", ex); throw ex; } } } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Could not add additional tags", ex); } if (getJobProperty().cleanImages) { client.removeImageCmd(tag_image) .withForce(true) .exec(); } } private String getAdditionalTag(TaskListener listener) { // Do a macro expansion on the addJenkinsAction token // Job property String tagToken = getJobProperty().additionalTag; // Do any macro expansions try { if (!Strings.isNullOrEmpty(tagToken)) tagToken = TokenMacro.expandAll((AbstractBuild) theRun, listener, tagToken); } catch (Exception e) { LOGGER.log(Level.WARNING, "can't expand macroses", e); } return tagToken; } /** * Add a built on docker action. */ private void addJenkinsAction(String tag_image) throws IOException { theRun.addAction(new DockerBuildAction(getCloud().getServerUrl(), containerId, tag_image, dockerTemplate.remoteFsMapping)); theRun.save(); } public DockerClient getClient() { return getCloud().getClient(); } private DockerJobProperty getJobProperty() { try { DockerJobProperty p = (DockerJobProperty) ((AbstractBuild) theRun).getProject().getProperty(DockerJobProperty.class); if (p != null) return p; } catch (Exception ex) { // Don't care. } // Safe default return new DockerJobProperty(false, null, false, true, null); } @Override public String toString() { return Objects.toStringHelper(this) .add("name", name) .add("containerId", containerId) .add("template", dockerTemplate) .toString(); } @Extension public static final class DescriptorImpl extends SlaveDescriptor { @Override public String getDisplayName() { return "Docker Slave"; } @Override public boolean isInstantiable() { return false; } } }
missing import
docker-plugin/src/main/java/com/nirima/jenkins/plugins/docker/DockerSlave.java
missing import
Java
mit
163b37ed377f90f929c78cf17ad1b94ce405cb49
0
vgt-tomek/image-draw
package pl.vgtworld.imagedraw.processing; import java.awt.Image; import java.awt.image.BufferedImage; import pl.vgtworld.imagedraw.ImageDrawEntity; class ImageResizeActions { public void resize(ImageDrawEntity image, Integer newWidth, Integer newHeight) { dimensionValidation(newWidth, newHeight); if (newWidth == null) { newWidth = calculateNewWidth(image, newHeight); } if (newHeight == null) { newHeight = calculateNewHeight(image, newWidth); } BufferedImage currentImageData = image.getImage(); Image scaledInstance = currentImageData.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); BufferedImage resizedImageData = new BufferedImage(newWidth, newHeight, image.getImage().getType()); resizedImageData.getGraphics().drawImage(scaledInstance, 0, 0, null); image.setImage(resizedImageData); } private int calculateNewWidth(ImageDrawEntity image, int newHeight) { return calculateNewEdgeLength(image.getImage().getWidth(), image.getImage().getHeight(), newHeight); } private int calculateNewHeight(ImageDrawEntity image, int newWidth) { return calculateNewEdgeLength(image.getImage().getHeight(), image.getImage().getWidth(), newWidth); } private int calculateNewEdgeLength(int currentEdgeLength, int currentOtherEdgeLength, int newOtherEdgeLength) { float resizeRatio = newOtherEdgeLength / (float)currentOtherEdgeLength; float calculatedLength = currentEdgeLength * resizeRatio; int roundedLength = Math.round(calculatedLength); return roundedLength == 0 ? 1 : roundedLength; } private void dimensionValidation(Integer newWidth, Integer newHeight) { if (newWidth == null && newHeight == null) { throw new IllegalStateException("At least one dimension must not be null"); } if ((newWidth != null && newWidth <= 0) || (newHeight != null && newHeight <= 0)) { throw new IllegalArgumentException("Dimension cannot be negative"); } } }
image-draw/src/main/java/pl/vgtworld/imagedraw/processing/ImageResizeActions.java
package pl.vgtworld.imagedraw.processing; import java.awt.image.BufferedImage; import pl.vgtworld.imagedraw.ImageDrawEntity; class ImageResizeActions { public void resize(ImageDrawEntity image, Integer newWidth, Integer newHeight) { dimensionValidation(newWidth, newHeight); if (newWidth == null) { newWidth = calculateNewWidth(image, newHeight); } if (newHeight == null) { newHeight = calculateNewHeight(image, newWidth); } BufferedImage currentImageData = image.getImage(); java.awt.Image scaledInstance = currentImageData.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH); BufferedImage resizedImageData = new BufferedImage(newWidth, newHeight, image.getImage().getType()); resizedImageData.getGraphics().drawImage(scaledInstance, 0, 0, null); image.setImage(resizedImageData); } private int calculateNewWidth(ImageDrawEntity image, int newHeight) { return calculateNewEdgeLength(image.getImage().getWidth(), image.getImage().getHeight(), newHeight); } private int calculateNewHeight(ImageDrawEntity image, int newWidth) { return calculateNewEdgeLength(image.getImage().getHeight(), image.getImage().getWidth(), newWidth); } private int calculateNewEdgeLength(int currentEdgeLength, int currentOtherEdgeLength, int newOtherEdgeLength) { float resizeRatio = newOtherEdgeLength / (float)currentOtherEdgeLength; float calculatedLength = currentEdgeLength * resizeRatio; int roundedLength = Math.round(calculatedLength); return roundedLength == 0 ? 1 : roundedLength; } private void dimensionValidation(Integer newWidth, Integer newHeight) { if (newWidth == null && newHeight == null) { throw new IllegalStateException("At least one dimension must not be null"); } if ((newWidth != null && newWidth <= 0) || (newHeight != null && newHeight <= 0)) { throw new IllegalArgumentException("Dimension cannot be negative"); } } }
Import java.awt.Image instead of using full name.
image-draw/src/main/java/pl/vgtworld/imagedraw/processing/ImageResizeActions.java
Import java.awt.Image instead of using full name.
Java
mit
d54a39183e348223a42a94c238d584cf4387be51
0
sstrickx/yahoofinance-api,chris-ch/yahoofinance-api
package yahoofinance; import java.io.IOException; import java.lang.reflect.Field; import java.util.Calendar; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import yahoofinance.histquotes.HistQuotesRequest; import yahoofinance.histquotes.HistoricalQuote; import yahoofinance.histquotes.Interval; import yahoofinance.quotes.stock.StockDividend; import yahoofinance.quotes.stock.StockQuote; import yahoofinance.quotes.stock.StockQuotesData; import yahoofinance.quotes.stock.StockQuotesRequest; import yahoofinance.quotes.stock.StockStats; /** * * @author Stijn Strickx */ public class Stock { private final String symbol; private String name; private String currency; private String stockExchange; private StockQuote quote; private StockStats stats; private StockDividend dividend; private List<HistoricalQuote> history; public Stock(String symbol) { this.symbol = symbol; } private void update() throws IOException { StockQuotesRequest request = new StockQuotesRequest(this.symbol); StockQuotesData data = request.getSingleResult(); if(data != null) { this.setQuote(data.getQuote()); this.setStats(data.getStats()); this.setDividend(data.getDividend()); YahooFinance.logger.log(Level.INFO, "Updated Stock with symbol: {0}", this.symbol); } else { YahooFinance.logger.log(Level.SEVERE, "Failed to update Stock with symbol: {0}", this.symbol); } } /** * Checks if the returned name is null. This probably means that the symbol was not recognized by Yahoo Finance. * @return whether this stock's symbol is known by Yahoo Finance (true) or not (false) */ public boolean isValid() { return this.name != null; } /** * Returns the basic quotes data available for this stock. * * @return basic quotes data available for this stock * @see #getQuote(boolean) */ public StockQuote getQuote() { return this.quote; } /** * Returns the basic quotes data available for this stock. * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the quote data gets refreshed, it will automatically also refresh * the statistics and dividend data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return basic quotes data available for this stock * @throws java.io.IOException when there's a connection problem */ public StockQuote getQuote(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.quote; } public void setQuote(StockQuote quote) { this.quote = quote; } /** * Returns the statistics available for this stock. * * @return statistics available for this stock * @see #getStats(boolean) */ public StockStats getStats() { return this.stats; } /** * Returns the statistics available for this stock. * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the statistics get refreshed, it will automatically also refresh * the quote and dividend data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return statistics available for this stock * @throws java.io.IOException when there's a connection problem */ public StockStats getStats(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.stats; } public void setStats(StockStats stats) { this.stats = stats; } /** * Returns the dividend data available for this stock. * * @return dividend data available for this stock * @see #getDividend(boolean) */ public StockDividend getDividend() { return this.dividend; } /** * Returns the dividend data available for this stock. * * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the dividend data get refreshed, it will automatically also refresh * the quote and statistics data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return dividend data available for this stock * @throws java.io.IOException when there's a connection problem */ public StockDividend getDividend(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.dividend; } public void setDividend(StockDividend dividend) { this.dividend = dividend; } /** * This method will return historical quotes from this stock. * If the historical quotes are not available yet, they will * be requested first from Yahoo Finance. * <p> * If the historical quotes are not available yet, the * following characteristics will be used for the request: * <ul> * <li> from: 1 year ago (default) * <li> to: today (default) * <li> interval: MONTHLY (default) * </ul> * <p> * There are several more methods available that allow you * to define some characteristics of the historical data. * Calling one of those methods will result in a new request * being sent to Yahoo Finance. * * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory(yahoofinance.histquotes.Interval) * @see #getHistory(java.util.Calendar) * @see #getHistory(java.util.Calendar, java.util.Calendar) * @see #getHistory(java.util.Calendar, yahoofinance.histquotes.Interval) * @see #getHistory(java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval) */ public List<HistoricalQuote> getHistory() throws IOException { if(this.history != null) { return this.history; } return this.getHistory(HistQuotesRequest.DEFAULT_FROM); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: 1 year ago (default) * <li> to: today (default) * <li> interval: specified value * </ul> * * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Interval interval) throws IOException { return this.getHistory(HistQuotesRequest.DEFAULT_FROM, interval); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: today (default) * <li> interval: MONTHLY (default) * </ul> * * @param from start date of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from) throws IOException { return this.getHistory(from, HistQuotesRequest.DEFAULT_TO); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: today (default) * <li> interval: specified value * </ul> * * @param from start date of the historical data * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Interval interval) throws IOException { return this.getHistory(from, HistQuotesRequest.DEFAULT_TO, interval); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: specified value * <li> interval: MONTHLY (default) * </ul> * * @param from start date of the historical data * @param to end date of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Calendar to) throws IOException { return this.getHistory(from, to, Interval.MONTHLY); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: specified value * <li> interval: specified value * </ul> * * @param from start date of the historical data * @param to end date of the historical data * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Calendar to, Interval interval) throws IOException { HistQuotesRequest hist = new HistQuotesRequest(this.symbol, from, to, interval); this.setHistory(hist.getResult()); return this.history; } public void setHistory(List<HistoricalQuote> history) { this.history = history; } public String getSymbol() { return symbol; } /** * Get the full name of the stock * * @return the name or null if the data is not available */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Get the currency of the stock * * @return the currency or null if the data is not available */ public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } /** * Get the exchange on which the stock is traded * * @return the exchange or null if the data is not available */ public String getStockExchange() { return stockExchange; } public void setStockExchange(String stockExchange) { this.stockExchange = stockExchange; } @Override public String toString() { return this.symbol + ": " + this.quote.getPrice(); } public void print() { System.out.println(this.symbol); System.out.println("--------------------------------"); for (Field f : this.getClass().getDeclaredFields()) { try { System.out.println(f.getName() + ": " + f.get(this)); } catch (IllegalArgumentException ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("--------------------------------"); } }
src/main/java/yahoofinance/Stock.java
package yahoofinance; import java.io.IOException; import java.lang.reflect.Field; import java.util.Calendar; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import yahoofinance.histquotes.HistQuotesRequest; import yahoofinance.histquotes.HistoricalQuote; import yahoofinance.histquotes.Interval; import yahoofinance.quotes.stock.StockDividend; import yahoofinance.quotes.stock.StockQuote; import yahoofinance.quotes.stock.StockQuotesData; import yahoofinance.quotes.stock.StockQuotesRequest; import yahoofinance.quotes.stock.StockStats; /** * * @author Stijn Strickx */ public class Stock { private final String symbol; private String name; private String currency; private String stockExchange; private StockQuote quote; private StockStats stats; private StockDividend dividend; private List<HistoricalQuote> history; public Stock(String symbol) { this.symbol = symbol; } private void update() throws IOException { StockQuotesRequest request = new StockQuotesRequest(this.symbol); StockQuotesData data = request.getSingleResult(); if(data != null) { this.setQuote(data.getQuote()); this.setStats(data.getStats()); this.setDividend(data.getDividend()); YahooFinance.logger.log(Level.INFO, "Updated Stock with symbol: {0}", this.symbol); } else { YahooFinance.logger.log(Level.SEVERE, "Failed to update Stock with symbol: {0}", this.symbol); } } /** * Returns the basic quotes data available for this stock. * * @return basic quotes data available for this stock * @see #getQuote(boolean) */ public StockQuote getQuote() { return this.quote; } /** * Returns the basic quotes data available for this stock. * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the quote data gets refreshed, it will automatically also refresh * the statistics and dividend data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return basic quotes data available for this stock * @throws java.io.IOException when there's a connection problem */ public StockQuote getQuote(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.quote; } public void setQuote(StockQuote quote) { this.quote = quote; } /** * Returns the statistics available for this stock. * * @return statistics available for this stock * @see #getStats(boolean) */ public StockStats getStats() { return this.stats; } /** * Returns the statistics available for this stock. * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the statistics get refreshed, it will automatically also refresh * the quote and dividend data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return statistics available for this stock * @throws java.io.IOException when there's a connection problem */ public StockStats getStats(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.stats; } public void setStats(StockStats stats) { this.stats = stats; } /** * Returns the dividend data available for this stock. * * @return dividend data available for this stock * @see #getDividend(boolean) */ public StockDividend getDividend() { return this.dividend; } /** * Returns the dividend data available for this stock. * * This method will return null in the following situations: * <ul> * <li> the data hasn't been loaded yet * in a previous request and refresh is set to false. * <li> refresh is true and the data cannot be retrieved from Yahoo Finance * for whatever reason (symbol not recognized, no network connection, ...) * </ul> * <p> * When the dividend data get refreshed, it will automatically also refresh * the quote and statistics data of the stock from Yahoo Finance * in the same request. * * @param refresh indicates whether the data should be requested again to Yahoo Finance * @return dividend data available for this stock * @throws java.io.IOException when there's a connection problem */ public StockDividend getDividend(boolean refresh) throws IOException { if(refresh) { this.update(); } return this.dividend; } public void setDividend(StockDividend dividend) { this.dividend = dividend; } /** * This method will return historical quotes from this stock. * If the historical quotes are not available yet, they will * be requested first from Yahoo Finance. * <p> * If the historical quotes are not available yet, the * following characteristics will be used for the request: * <ul> * <li> from: 1 year ago (default) * <li> to: today (default) * <li> interval: MONTHLY (default) * </ul> * <p> * There are several more methods available that allow you * to define some characteristics of the historical data. * Calling one of those methods will result in a new request * being sent to Yahoo Finance. * * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory(yahoofinance.histquotes.Interval) * @see #getHistory(java.util.Calendar) * @see #getHistory(java.util.Calendar, java.util.Calendar) * @see #getHistory(java.util.Calendar, yahoofinance.histquotes.Interval) * @see #getHistory(java.util.Calendar, java.util.Calendar, yahoofinance.histquotes.Interval) */ public List<HistoricalQuote> getHistory() throws IOException { if(this.history != null) { return this.history; } return this.getHistory(HistQuotesRequest.DEFAULT_FROM); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: 1 year ago (default) * <li> to: today (default) * <li> interval: specified value * </ul> * * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Interval interval) throws IOException { return this.getHistory(HistQuotesRequest.DEFAULT_FROM, interval); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: today (default) * <li> interval: MONTHLY (default) * </ul> * * @param from start date of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from) throws IOException { return this.getHistory(from, HistQuotesRequest.DEFAULT_TO); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: today (default) * <li> interval: specified value * </ul> * * @param from start date of the historical data * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Interval interval) throws IOException { return this.getHistory(from, HistQuotesRequest.DEFAULT_TO, interval); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: specified value * <li> interval: MONTHLY (default) * </ul> * * @param from start date of the historical data * @param to end date of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Calendar to) throws IOException { return this.getHistory(from, to, Interval.MONTHLY); } /** * Requests the historical quotes for this stock with the following characteristics. * <ul> * <li> from: specified value * <li> to: specified value * <li> interval: specified value * </ul> * * @param from start date of the historical data * @param to end date of the historical data * @param interval the interval of the historical data * @return a list of historical quotes from this stock * @throws java.io.IOException when there's a connection problem * @see #getHistory() */ public List<HistoricalQuote> getHistory(Calendar from, Calendar to, Interval interval) throws IOException { HistQuotesRequest hist = new HistQuotesRequest(this.symbol, from, to, interval); this.setHistory(hist.getResult()); return this.history; } public void setHistory(List<HistoricalQuote> history) { this.history = history; } public String getSymbol() { return symbol; } /** * Get the full name of the stock * * @return the name or null if the data is not available */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * Get the currency of the stock * * @return the currency or null if the data is not available */ public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } /** * Get the exchange on which the stock is traded * * @return the exchange or null if the data is not available */ public String getStockExchange() { return stockExchange; } public void setStockExchange(String stockExchange) { this.stockExchange = stockExchange; } @Override public String toString() { return this.symbol + ": " + this.quote.getPrice(); } public void print() { System.out.println(this.symbol); System.out.println("--------------------------------"); for (Field f : this.getClass().getDeclaredFields()) { try { System.out.println(f.getName() + ": " + f.get(this)); } catch (IllegalArgumentException ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("--------------------------------"); } }
Provide a check to see if the returned Stock is valid #64
src/main/java/yahoofinance/Stock.java
Provide a check to see if the returned Stock is valid #64
Java
mit
5f06582136881696df1c6f53a2c49389c0530e2b
0
braintree/braintree_android,braintree/braintree_android,braintree/braintree_android,braintree/braintree_android
package com.braintreepayments.api.dropin; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.widget.ImageView; import com.braintreepayments.api.BraintreeApi; import com.braintreepayments.api.dropin.Customization.CustomizationBuilder; import com.braintreepayments.api.exceptions.BraintreeException; import com.braintreepayments.api.exceptions.ErrorWithResponse; import com.braintreepayments.api.models.CardBuilder; import com.braintreepayments.testutils.TestClientTokenBuilder; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.braintreepayments.api.utils.PaymentFormHelpers.waitForAddPaymentFormHeader; import static com.braintreepayments.api.utils.PaymentFormHelpers.waitForPaymentMethodList; import static com.braintreepayments.testutils.CardNumber.VISA; import static com.braintreepayments.testutils.ui.Assertions.assertBitmapsEqual; import static com.braintreepayments.testutils.ui.Matchers.withId; import static com.braintreepayments.testutils.ui.ViewHelper.waitForView; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.startsWith; public class CustomizationTest extends BraintreePaymentActivityTestCase { public void testDescriptionIsNotNecessary() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_primary_description)).check(matches(not(isDisplayed()))); } public void testSubmitButtonUsesDefaultTextIfNoCustomizationProvided() { Intent intent = createIntent(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(R.string.bt_default_submit_button_text))); } public void testSubmitButtonUsesCustomizationForCardFormIfIncludedAsAnExtra() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .submitButtonText("Subscribe") .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText("$19 - Subscribe"))); } public void testSubmitButtonUsesCustomizationForSelectPaymentMethodIfIncludedAsAnExtra() throws ErrorWithResponse, BraintreeException { String clientToken = new TestClientTokenBuilder().build(); BraintreeApi api = new BraintreeApi(mContext, clientToken); api.create(new CardBuilder() .cardNumber(VISA) .expirationDate("0819")); Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .submitButtonText("Subscribe") .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForPaymentMethodList(); onView(withId(R.id.bt_select_payment_method_submit_button)).check(matches(withText("$19 - Subscribe"))); } public void testDescriptionsAreDisplayedIfIncludedAsAnExtra() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); Customization customization = new CustomizationBuilder() .primaryDescription("Hello, World!") .secondaryDescription("Some stuffz") .amount("$1,000,000,000.00") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForView(withId(R.id.bt_primary_description)).check(matches(withText("Hello, World!"))); onView(withId(R.id.bt_secondary_description)).check(matches(withText("Some stuffz"))); onView(withId(R.id.bt_description_amount)).check(matches(withText("$1,000,000,000.00"))); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText( startsWith("$1,000,000,000.00")))); } public void testDefaultButtonTextIsUsedWhenCustomizationIsPresentWithoutSpecifyingButtonText() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); Customization customization = new CustomizationBuilder() .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText("$19 - Purchase"))); } @TargetApi(VERSION_CODES.HONEYCOMB) public void testActionBarTitleAndLogoAreUsedIfIncludedAsAnExtra() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .actionBarTitle("This is a title") .actionBarLogo(android.R.drawable.ic_delete) .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); Activity activity = getActivity(); assertEquals("This is a title", activity.getActionBar().getTitle()); if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) { ImageView actual = (ImageView) activity.findViewById(android.R.id.home); assertBitmapsEqual(actual.getDrawable(), mContext.getResources().getDrawable(android.R.drawable.ic_delete) ); } } @TargetApi(VERSION_CODES.HONEYCOMB) public void testDefaultActionBarTitleAndLogoAreUsedWhenCustomizationIsPresentWithoutSpecifyingTitleAndLogo() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .primaryDescription("Description") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); Activity activity = getActivity(); assertEquals("Purchase", activity.getActionBar().getTitle()); if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP) { ImageView actual = (ImageView) activity.findViewById(android.R.id.home); ColorDrawable expected = new ColorDrawable(mContext.getResources().getColor( android.R.color.transparent)); assertEquals(actual.getDrawable().getOpacity(), expected.getOpacity()); } } private Intent createIntent() { return new Intent(mContext, BraintreePaymentActivity.class); } }
Drop-In/src/androidTest/java/com/braintreepayments/api/dropin/CustomizationTest.java
package com.braintreepayments.api.dropin; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build.VERSION_CODES; import android.widget.ImageView; import com.braintreepayments.api.BraintreeApi; import com.braintreepayments.api.dropin.Customization.CustomizationBuilder; import com.braintreepayments.api.exceptions.BraintreeException; import com.braintreepayments.api.exceptions.ErrorWithResponse; import com.braintreepayments.api.models.CardBuilder; import com.braintreepayments.testutils.TestClientTokenBuilder; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.braintreepayments.api.utils.PaymentFormHelpers.waitForAddPaymentFormHeader; import static com.braintreepayments.api.utils.PaymentFormHelpers.waitForPaymentMethodList; import static com.braintreepayments.testutils.CardNumber.VISA; import static com.braintreepayments.testutils.ui.Assertions.assertBitmapsEqual; import static com.braintreepayments.testutils.ui.Matchers.withId; import static com.braintreepayments.testutils.ui.ViewHelper.waitForView; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.startsWith; public class CustomizationTest extends BraintreePaymentActivityTestCase { public void testDescriptionIsNotNecessary() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_primary_description)).check(matches(not(isDisplayed()))); } public void testSubmitButtonUsesDefaultTextIfNoCustomizationProvided() { Intent intent = createIntent(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText(R.string.bt_default_submit_button_text))); } public void testSubmitButtonUsesCustomizationForCardFormIfIncludedAsAnExtra() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .submitButtonText("Subscribe") .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText("$19 - Subscribe"))); } public void testSubmitButtonUsesCustomizationForSelectPaymentMethodIfIncludedAsAnExtra() throws ErrorWithResponse, BraintreeException { String clientToken = new TestClientTokenBuilder().build(); BraintreeApi api = new BraintreeApi(mContext, clientToken); api.create(new CardBuilder() .cardNumber(VISA) .expirationDate("0819")); Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .submitButtonText("Subscribe") .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForPaymentMethodList(); onView(withId(R.id.bt_select_payment_method_submit_button)).check(matches(withText("$19 - Subscribe"))); } public void testDescriptionsAreDisplayedIfIncludedAsAnExtra() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); Customization customization = new CustomizationBuilder() .primaryDescription("Hello, World!") .secondaryDescription("Some stuffz") .amount("$1,000,000,000.00") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForView(withId(R.id.bt_primary_description)).check(matches(withText("Hello, World!"))); onView(withId(R.id.bt_secondary_description)).check(matches(withText("Some stuffz"))); onView(withId(R.id.bt_description_amount)).check(matches(withText("$1,000,000,000.00"))); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText( startsWith("$1,000,000,000.00")))); } public void testDefaultButtonTextIsUsedWhenCustomizationIsPresentWithoutSpecifyingButtonText() { Intent intent = createIntent(); String clientToken = new TestClientTokenBuilder().build(); Customization customization = new CustomizationBuilder() .amount("$19") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); getActivity(); waitForAddPaymentFormHeader(); onView(withId(R.id.bt_card_form_submit_button)).check(matches(withText("$19 - Purchase"))); } @TargetApi(VERSION_CODES.HONEYCOMB) public void testActionBarTitleAndLogoAreUsedIfIncludedAsAnExtra() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .actionBarTitle("This is a title") .actionBarLogo(android.R.drawable.ic_delete) .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); Activity activity = getActivity(); assertEquals("This is a title", activity.getActionBar().getTitle()); ImageView actual = (ImageView) activity.findViewById(android.R.id.home); assertBitmapsEqual(actual.getDrawable(), mContext.getResources().getDrawable(android.R.drawable.ic_delete) ); } @TargetApi(VERSION_CODES.HONEYCOMB) public void testDefaultActionBarTitleAndLogoAreUsedWhenCustomizationIsPresentWithoutSpecifyingTitleAndLogo() { Intent intent = createIntent(); Customization customization = new CustomizationBuilder() .primaryDescription("Description") .build(); intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, new TestClientTokenBuilder().build()); intent.putExtra(BraintreePaymentActivity.EXTRA_CUSTOMIZATION, customization); setActivityIntent(intent); Activity activity = getActivity(); assertEquals("Purchase", activity.getActionBar().getTitle()); ImageView actual = (ImageView) activity.findViewById(android.R.id.home); ColorDrawable expected = new ColorDrawable(mContext.getResources().getColor( android.R.color.transparent)); assertEquals(actual.getDrawable().getOpacity(), expected.getOpacity()); } private Intent createIntent() { return new Intent(mContext, BraintreePaymentActivity.class); } }
More Android 5.0 UI test fixes
Drop-In/src/androidTest/java/com/braintreepayments/api/dropin/CustomizationTest.java
More Android 5.0 UI test fixes
Java
mit
24df834f73f4b2c5c50046364c1a8525eda68f91
0
bonczj/vertx-messaging-sample
package bonczj.vertx.message; import bonczj.vertx.models.Result; import bonczj.vertx.models.Status; import io.vertx.core.AbstractVerticle; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import java.util.Random; import java.util.logging.Logger; public class MessageHandlerVerticle extends AbstractVerticle { private static final Logger logger = Logger.getLogger(MessageHandlerVerticle.class.getSimpleName()); @Override public void start() throws Exception { super.start(); getVertx().eventBus().consumer("message.handle", objectMessage -> { JsonObject object = (JsonObject) objectMessage.body(); Result result = Json.decodeValue(object.encode(), Result.class); logger.info(String.format("Processing message %s", result.getId().toString())); Random random = new Random(); int seconds = random.nextInt(9) + 1; // Thread.sleep is blocking, so allow vertx to handle it cleaner than normal. getVertx().executeBlocking(objectFuture -> { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { objectFuture.fail(e); } objectFuture.complete(); }, objectAsyncResult -> { if (objectAsyncResult.succeeded()) { result.setStatus(Status.COMPLETED); result.setResult(String.format("Message complete in %d seconds!", seconds)); logger.info(String.format("Message %s complete in %d seconds", result.getId(), seconds)); JsonObject json = new JsonObject(Json.encode(result)); getVertx().eventBus().send("result.message.handle", json); logger.info(String.format("Response sent to result.message.handle for result %s", result.getId())); } else { result.setStatus(Status.FAILED); result.setResult(String.format("Failed to sleep %d seconds for result %s", seconds, result.getId())); JsonObject json = new JsonObject(Json.encode(result)); getVertx().eventBus().send("result.message.handle", json); logger.severe(result.getResult()); } }); }); } }
message-handler-verticle/src/main/java/bonczj/vertx/message/MessageHandlerVerticle.java
package bonczj.vertx.message; import bonczj.vertx.models.Result; import bonczj.vertx.models.Status; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import java.util.Random; import java.util.logging.Logger; public class MessageHandlerVerticle extends AbstractVerticle { private static final Logger logger = Logger.getLogger(MessageHandlerVerticle.class.getSimpleName()); @Override public void start() throws Exception { super.start(); getVertx().eventBus().consumer("message.handle", objectMessage -> { JsonObject object = (JsonObject) objectMessage.body(); Result result = Json.decodeValue(object.encode(), Result.class); logger.info(String.format("Processing message %s", result.getId().toString())); Random random = new Random(); int seconds = random.nextInt(9) + 1; for (int i = 0; i < seconds; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } } result.setStatus(Status.COMPLETED); result.setResult(String.format("Message complete in %f seconds!", seconds / 100.0f)); logger.info(String.format("Message %s complete in %f seconds", result.getId(), seconds / 100.0f)); object = new JsonObject(Json.encode(result)); getVertx().eventBus().send("result.message.handle", object); logger.info(String.format("Response sent to result.message.handle for result %s", result.getId())); }); } }
Moved the blocking call to a blocking execution block so that is follows the correct pattern for vert.
message-handler-verticle/src/main/java/bonczj/vertx/message/MessageHandlerVerticle.java
Moved the blocking call to a blocking execution block so that is follows the correct pattern for vert.
Java
mit
f4e2df9cc4565f34592997bcf958e608e43eb074
0
lew/mitzi
package mitzi; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class NaiveBoard implements IBoard { protected static int[][] initial_board = { { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 12, 13, 14, 15, 16, 14, 13, 12, 00, 00 }, { 00, 00, 11, 11, 11, 11, 11, 11, 11, 11, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 01, 01, 01, 01, 01, 01, 01, 01, 00, 00 }, { 00, 00, 02, 03, 04, 05, 06, 04, 03, 02, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } }; private int[][] board = new int[12][12]; private int full_move_clock; private int half_move_clock; // squares c1, g1, c8 and g8 in ICCF numeric notation // do not change the squares' order or bad things will happen! // set to -1 if castling not allowed private int[] castling = { -1, -1, -1, -1 }; private int en_passant_target = -1; private int active_color; // The following class members are used to prevent multiple computations private Set<IMove> possible_moves; // Set of all possible moves private Boolean is_check; // using the class Boolean, which can be null! private Boolean is_mate; private Boolean is_stale_mate; // the following maps takes and Integer, representing the color, type or // PieceValue and returns the set of squares or the number of squares! private Map<Integer, Set<Integer>> occupied_squares_by_color_and_type = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Set<Integer>> occupied_squares_by_color = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Set<Integer>> occupied_squares_by_type = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Integer> num_occupied_squares_by_color_and_type = new HashMap<Integer, Integer>(); private Map<Integer, Integer> num_occupied_squares_by_color = new HashMap<Integer, Integer>(); private Map<Integer, Integer> num_occupied_squares_by_type = new HashMap<Integer, Integer>(); // -------------------------------------------------------- private NaiveBoard returnCopy() { NaiveBoard newBoard = new NaiveBoard(); newBoard.active_color = active_color; newBoard.en_passant_target = en_passant_target; newBoard.full_move_clock = full_move_clock; newBoard.half_move_clock = half_move_clock; System.arraycopy(castling, 0, newBoard.castling, 0, 4); // from row and column 1,2,11,12 are 0.. for (int i = 2; i < 11; i++) System.arraycopy(board[i], 2, newBoard.board[i], 2, 8); return newBoard; } private int getFromBoard(int square) { int row = SquareHelper.getRow(square); int column = SquareHelper.getColumn(square); return board[10 - row][1 + column]; } private void setOnBoard(int square, int piece_value) { int row = SquareHelper.getRow(square); int column = SquareHelper.getColumn(square); board[10 - row][1 + column] = piece_value; } public int getOpponentsColor() { if (active_color == PieceHelper.BLACK) return PieceHelper.WHITE; else return PieceHelper.BLACK; } @Override public void setToInitial() { board = initial_board; full_move_clock = 1; half_move_clock = 0; castling[0] = 31; castling[1] = 71; castling[2] = 38; castling[3] = 78; en_passant_target = -1; active_color = PieceHelper.WHITE; } @Override public void setToFEN(String fen) { board = new int[12][12]; castling[0] = -1; castling[1] = -1; castling[2] = -1; castling[3] = -1; en_passant_target = -1; String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 1; row <= 8; row++) { int offset = 0; for (int column = 1; column + offset <= 8; column++) { pieces = fen_rows[8 - row].toCharArray(); int square = (column + offset) * 10 + row; switch (pieces[column - 1]) { case 'P': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN, PieceHelper.WHITE)); break; case 'R': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK, PieceHelper.WHITE)); break; case 'N': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.KNIGHT, PieceHelper.WHITE)); break; case 'B': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.BISHOP, PieceHelper.WHITE)); break; case 'Q': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.QUEEN, PieceHelper.WHITE)); break; case 'K': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING, PieceHelper.WHITE)); break; case 'p': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN, PieceHelper.BLACK)); break; case 'r': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK, PieceHelper.BLACK)); break; case 'n': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.KNIGHT, PieceHelper.BLACK)); break; case 'b': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.BISHOP, PieceHelper.BLACK)); break; case 'q': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.QUEEN, PieceHelper.BLACK)); break; case 'k': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING, PieceHelper.BLACK)); break; default: offset += Character.getNumericValue(pieces[column - 1]) - 1; break; } } } // set active color switch (fen_parts[1]) { case "b": active_color = PieceHelper.BLACK; break; case "w": active_color = PieceHelper.WHITE; break; } // set possible castling moves if (!fen_parts[2].equals("-")) { char[] castlings = fen_parts[2].toCharArray(); for (int i = 0; i < castlings.length; i++) { switch (castlings[i]) { case 'K': castling[1] = 71; break; case 'Q': castling[0] = 31; break; case 'k': castling[3] = 78; break; case 'q': castling[2] = 38; break; } } } // set en passant square if (!fen_parts[3].equals("-")) { en_passant_target = SquareHelper.fromString(fen_parts[3]); } // set half move clock half_move_clock = Integer.parseInt(fen_parts[4]); // set full move clock full_move_clock = Integer.parseInt(fen_parts[5]); } @Override public NaiveBoard doMove(IMove move) { NaiveBoard newBoard = this.returnCopy(); int src = move.getFromSquare(); int dest = move.getToSquare(); int piece = getFromBoard(src); // reducing calls of getFormBoard // if promotion if (move.getPromotion() != 0) { newBoard.setOnBoard(src, 0); newBoard.setOnBoard(dest, PieceHelper.pieceValue(move.getPromotion(), active_color)); newBoard.half_move_clock = 0; } // If rochade else if (PieceHelper.pieceType(piece) == PieceHelper.KING && Math.abs((src - dest)) == 20) { newBoard.setOnBoard(dest, PieceHelper.pieceValue(PieceHelper.KING, active_color)); newBoard.setOnBoard(src, 0); newBoard.setOnBoard((src + dest) / 2, PieceHelper.pieceValue(PieceHelper.ROOK, active_color)); if (SquareHelper.getColumn(dest) == 3) newBoard.setOnBoard(src - 40, 0); else newBoard.setOnBoard(src + 30, 0); newBoard.half_move_clock++; } // If en passant else if (PieceHelper.pieceType(piece) == PieceHelper.PAWN && dest == this.getEnPassant()) { newBoard.setOnBoard(dest, PieceHelper.pieceValue(PieceHelper.PAWN, active_color)); newBoard.setOnBoard(src, 0); if (active_color == PieceHelper.WHITE) newBoard.setOnBoard(dest - 1, 0); else newBoard.setOnBoard(dest + 1, 0); newBoard.half_move_clock = 0; } // Usual move else { newBoard.setOnBoard(dest, piece); newBoard.setOnBoard(src, 0); if (this.getFromBoard(dest) != 0 || PieceHelper.pieceType(piece) == PieceHelper.PAWN) newBoard.half_move_clock = 0; else newBoard.half_move_clock++; } // Change active_color after move newBoard.active_color = PieceHelper.pieceOppositeColor(piece); if (active_color == PieceHelper.BLACK) newBoard.full_move_clock++; // Update en_passant if (PieceHelper.pieceType(piece) == PieceHelper.PAWN && Math.abs(dest - src) == 2) newBoard.en_passant_target = (dest + src) / 2; else newBoard.en_passant_target = -1; // Update castling if (PieceHelper.pieceType(piece) == PieceHelper.KING) { if (active_color == PieceHelper.WHITE && src == 51) { newBoard.castling[0] = -1; newBoard.castling[1] = -1; } else if (active_color == PieceHelper.BLACK && src == 58) { newBoard.castling[2] = -1; newBoard.castling[3] = -1; } } else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) { if (active_color == PieceHelper.WHITE) { if (src == 81) newBoard.castling[1] = -1; else if (src == 11) newBoard.castling[0] = -1; } else { if (src == 88) newBoard.castling[3] = -1; else if (src == 18) newBoard.castling[2] = -1; } } return newBoard; } @Override public int getEnPassant() { return en_passant_target; } @Override public boolean canCastle(int king_to) { if ((king_to == 31 && castling[0] != -1) || (king_to == 71 && castling[1] != -1) || (king_to == 38 && castling[2] != -1) || (king_to == 78 && castling[3] != -1)) { return true; } else { return false; } } @Override public Set<Integer> getOccupiedSquaresByColor(int color) { if (occupied_squares_by_color.containsKey(color) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper .pieceColor(this.getFromBoard(square)) == color) set.add(square); } occupied_squares_by_color.put(color, set); return set; } return occupied_squares_by_color.get(color); } @Override public Set<Integer> getOccupiedSquaresByType(int type) { if (occupied_squares_by_type.containsKey(type) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceType(this.getFromBoard(square)) == type) set.add(square); } occupied_squares_by_type.put(type, set); return set; } return occupied_squares_by_type.get(type); } @Override public Set<Integer> getOccupiedSquaresByColorAndType(int color, int type) { int value = PieceHelper.pieceValue(type, color); if (occupied_squares_by_color_and_type.containsKey(value) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (value == this.getFromBoard(square)) set.add(square); } occupied_squares_by_color_and_type.put(value, set); return set; } return occupied_squares_by_color_and_type.get(value); } @Override public int getNumberOfPiecesByColor(int color) { if (num_occupied_squares_by_color.containsKey(color) == false) { if (occupied_squares_by_color.containsKey(color) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceColor(this .getFromBoard(square)) == color) num++; } num_occupied_squares_by_color.put(color, num); return num; } num_occupied_squares_by_color.put(color, occupied_squares_by_color .get(color).size()); } return num_occupied_squares_by_color.get(color); } @Override public int getNumberOfPiecesByType(int type) { if (num_occupied_squares_by_type.containsKey(type) == false) { if (occupied_squares_by_type.containsKey(type) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceType(this .getFromBoard(square)) == type) num++; } num_occupied_squares_by_type.put(type, num); return num; } num_occupied_squares_by_type.put(type, occupied_squares_by_type .get(type).size()); } return num_occupied_squares_by_type.get(type); } @Override public int getNumberOfPiecesByColorAndType(int color, int type) { int value = PieceHelper.pieceValue(type, color); if (num_occupied_squares_by_color_and_type.containsKey(value) == false) { if (occupied_squares_by_color_and_type.containsKey(value) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (value == this.getFromBoard(square)) num++; } num_occupied_squares_by_color_and_type.put(value, num); return num; } num_occupied_squares_by_color_and_type.put(value, occupied_squares_by_color_and_type.get(value).size()); } return num_occupied_squares_by_color_and_type.get(value); } @Override public Set<IMove> getPossibleMoves() { if (possible_moves == null) { Set<IMove> total_set = new HashSet<IMove>(); Set<IMove> temp_set; // all the active squares Set<Integer> squares = getOccupiedSquaresByColor(active_color); // loop over all squares for (int square : squares) { temp_set = getPossibleMovesFrom(square); total_set.addAll(temp_set); } possible_moves = total_set; } return possible_moves; } @Override public Set<IMove> getPossibleMovesFrom(int square) { // The case, that the destination is the opponents king cannot happen. int type = PieceHelper.pieceType(getFromBoard(square)); int opp_color = getOpponentsColor(); List<Integer> squares; Set<IMove> moves = new HashSet<IMove>(); Move move; // Types BISHOP, QUEEN, ROOK if (type == PieceHelper.BISHOP || type == PieceHelper.QUEEN || type == PieceHelper.ROOK) { // Loop over all directions and skip not appropriate ones for (Direction direction : Direction.values()) { // Skip N,W,E,W with BISHOP and skip NE,NW,SE,SW with ROOK if (((direction == Direction.NORTH || direction == Direction.EAST || direction == Direction.SOUTH || direction == Direction.WEST) && type == PieceHelper.BISHOP) || ((direction == Direction.NORTHWEST || direction == Direction.NORTHEAST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && type == PieceHelper.ROOK)) { continue; } else { // do stuff squares = SquareHelper.getAllSquaresInDirection(square, direction); for (Integer new_square : squares) { int piece = getFromBoard(new_square); if (piece == 0 || PieceHelper.pieceColor(piece) == opp_color) { move = new Move(square, new_square); moves.add(move); if (piece != 0 && PieceHelper.pieceColor(piece) == opp_color) break; } else break; } } } } if (type == PieceHelper.PAWN) { // If Pawn has not moved yet (steps possible) if ((SquareHelper.getRow(square) == 2 && active_color == PieceHelper.WHITE) || (SquareHelper.getRow(square) == 7 && active_color == PieceHelper.BLACK)) { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); if (getFromBoard(square + 2 * Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + 2 * Direction.pawnDirection(active_color).offset); moves.add(move); } } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getFromBoard(square + direction.offset) != 0 && PieceHelper.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) { move = new Move(square, square + direction.offset); moves.add(move); } } } // if Promotion will happen else if ((SquareHelper.getRow(square) == 7 && active_color == PieceHelper.WHITE) || (SquareHelper.getRow(square) == 2 && active_color == PieceHelper.BLACK)) { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.QUEEN); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.KNIGHT); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.ROOK); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.BISHOP); moves.add(move); } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getFromBoard(square + direction.offset) != 0 && PieceHelper.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) { move = new Move(square, square + direction.offset, PieceHelper.QUEEN); moves.add(move); move = new Move(square, square + direction.offset, PieceHelper.KNIGHT); moves.add(move); } } } // Usual turn and en passente is possible, no promotion else { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if ((getFromBoard(square + direction.offset) != 0 && PieceHelper .pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) || square + direction.offset == getEnPassant()) { move = new Move(square, square + direction.offset); moves.add(move); } } } } if (type == PieceHelper.KING) { for (Direction direction : Direction.values()) { Integer new_square = square + direction.offset; move = new Move(square, new_square); if (SquareHelper.isValidSquare(new_square)) { // if the new square is empty or occupied by the opponent if (getFromBoard(new_square) == 0 || PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) moves.add(move); } } // Castle Moves // If the King is not check now, try castle moves if (!isCheckPosition()) { int off = 0; if (active_color == PieceHelper.BLACK) off = 2; for (int i = 0; i < 2; i++) { int castle_flag = 0; Integer new_square = castling[i + off]; // castling must still be possible to this side if (new_square != -1) { Direction dir; if (i == 0) dir = Direction.WEST; else dir = Direction.EAST; List<Integer> line = SquareHelper .getAllSquaresInDirection(square, dir); // Check each square if it is empty for (Integer squ : line) { if (getFromBoard(squ) != 0) { castle_flag = 1; break; } if (squ == new_square) break; } if (castle_flag == 1) continue; // Check each square if the king on it would be check for (Integer squ : line) { move = new Move(square, squ); NaiveBoard board = doMove(move); board.active_color = active_color; // TODO: ugly // solution ! ;) if (board.isCheckPosition()) break; if (squ == new_square) { // if EVERYTHING is right, // then add the move moves.add(move); break; } } } } } } if (type == PieceHelper.KNIGHT) { squares = SquareHelper.getAllSquaresByKnightStep(square); for (Integer new_square : squares) { if (getFromBoard(new_square) == 0 || PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) { move = new Move(square, new_square); moves.add(move); } } } // remove invalid positions // TODO do this in a more efficient way Iterator<IMove> iter = moves.iterator(); while (iter.hasNext()) { IMove m = iter.next(); NaiveBoard temp_board = this.doMove(m); temp_board.active_color = active_color; // ugly solution… if (temp_board.isCheckPosition()) { iter.remove(); } } return moves; } @Override public Set<IMove> getPossibleMovesTo(int square) { // TODO Auto-generated method stub return null; } @Override public boolean isCheckPosition() { if (is_check == null) { is_check = true; Set<Integer> temp_king_pos = getOccupiedSquaresByColorAndType( active_color, PieceHelper.KING); int king_pos = temp_king_pos.iterator().next(); // go in each direction for (Direction direction : Direction.values()) { List<Integer> line = SquareHelper.getAllSquaresInDirection( king_pos, direction); // go until… int iter = 0; for (int square : line) { iter++; // …some piece is found int piece = getFromBoard(square); if (piece != 0) { if (PieceHelper.pieceColor(piece) == active_color) { break; } else { if (PieceHelper.pieceType(piece) == PieceHelper.PAWN && iter == 1) { if (((direction == Direction.NORTHEAST || direction == Direction.NORTHWEST) && active_color == PieceHelper.WHITE) || ((direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && active_color == PieceHelper.BLACK)) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) { if (direction == Direction.EAST || direction == Direction.WEST || direction == Direction.NORTH || direction == Direction.SOUTH) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.BISHOP) { if (direction == Direction.NORTHEAST || direction == Direction.NORTHWEST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.QUEEN) { return true; } else if (PieceHelper.pieceType(piece) == PieceHelper.KING && iter == 1) { return true; } break; } } } } // check for knight attacks List<Integer> knight_squares = SquareHelper .getAllSquaresByKnightStep(king_pos); for (int square : knight_squares) { int piece = getFromBoard(square); if (piece != 0) { if (PieceHelper.pieceColor(piece) != active_color && PieceHelper.pieceType(piece) == PieceHelper.KNIGHT) { return true; } } } is_check = false; } return is_check.booleanValue(); } @Override public boolean isMatePosition() { if (is_mate == null) { is_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty() && isCheckPosition()) return true; is_mate = false; } return is_mate.booleanValue(); } @Override public boolean isStaleMatePosition() { if (is_stale_mate == null) { is_stale_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty()) return true; is_stale_mate = false; } return is_stale_mate.booleanValue(); } @Override public boolean isPossibleMove(IMove move) { // TODO Auto-generated method stub return false; } public String toString() { return toFEN(); } @Override public String toFEN() { StringBuilder fen = new StringBuilder(); // piece placement for (int row = 2; row < 10; row++) { int counter = 0; for (int column = 2; column < 10; column++) { if (board[row][column] == 0) { counter++; } else { if (counter != 0) { fen.append(counter); counter = 0; } fen.append(PieceHelper.toString(board[row][column])); } if (column == 9 && counter != 0) { fen.append(counter); } } if (row != 9) { fen.append("/"); } } fen.append(" "); // active color if (active_color == PieceHelper.WHITE) { fen.append("w"); } else { fen.append("b"); } fen.append(" "); // castling availability boolean castle_flag = false; if (castling[1] != -1) { fen.append("K"); castle_flag = true; } if (castling[0] != -1) { fen.append("Q"); castle_flag = true; } if (castling[3] != -1) { fen.append("k"); castle_flag = true; } if (castling[2] != -1) { fen.append("q"); castle_flag = true; } if (!castle_flag) { fen.append("-"); } fen.append(" "); // en passant target square if (en_passant_target == -1) { fen.append("-"); } else { fen.append(SquareHelper.toString(en_passant_target)); } fen.append(" "); // halfmove clock fen.append(half_move_clock); fen.append(" "); // fullmove clock fen.append(full_move_clock); return fen.toString(); } @Override public int getActiveColor() { return active_color; } @Override public int getHalfMoveClock() { return half_move_clock; } @Override public int getFullMoveClock() { return full_move_clock; } }
src/mitzi/NaiveBoard.java
package mitzi; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class NaiveBoard implements IBoard { protected static int[][] initial_board = { { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 12, 13, 14, 15, 16, 14, 13, 12, 00, 00 }, { 00, 00, 11, 11, 11, 11, 11, 11, 11, 11, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 01, 01, 01, 01, 01, 01, 01, 01, 00, 00 }, { 00, 00, 02, 03, 04, 05, 06, 04, 03, 02, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 }, { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 } }; private int[][] board = new int[12][12]; private int full_move_clock; private int half_move_clock; // squares c1, g1, c8 and g8 in ICCF numeric notation // do not change the squares' order or bad things will happen! // set to -1 if castling not allowed private int[] castling = { -1, -1, -1, -1 }; private int en_passant_target = -1; private int active_color; // The following class members are used to prevent multiple computations private Set<IMove> possible_moves; private Boolean is_check; // using the class Boolean, which can be null! private Boolean is_mate; private Boolean is_stale_mate; // the following maps takes and Integer, representing the color, type or // PieceValue and returns the set of squares or the number of squares! private Map<Integer, Set<Integer>> occupied_squares_by_color_and_type = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Set<Integer>> occupied_squares_by_color = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Set<Integer>> occupied_squares_by_type = new HashMap<Integer, Set<Integer>>(); private Map<Integer, Integer> num_occupied_squares_by_color_and_type = new HashMap<Integer, Integer>(); private Map<Integer, Integer> num_occupied_squares_by_color = new HashMap<Integer, Integer>(); private Map<Integer, Integer> num_occupied_squares_by_type = new HashMap<Integer, Integer>(); // -------------------------------------------------------- private NaiveBoard returnCopy() { NaiveBoard newBoard = new NaiveBoard(); newBoard.active_color = active_color; newBoard.en_passant_target = en_passant_target; newBoard.full_move_clock = full_move_clock; newBoard.half_move_clock = half_move_clock; System.arraycopy(castling, 0, newBoard.castling, 0, 4); // from row and column 1,2,11,12 are 0.. for (int i = 2; i < 11; i++) System.arraycopy(board[i], 2, newBoard.board[i], 2, 8); return newBoard; } private int getFromBoard(int square) { int row = SquareHelper.getRow(square); int column = SquareHelper.getColumn(square); return board[10 - row][1 + column]; } private void setOnBoard(int square, int piece_value) { int row = SquareHelper.getRow(square); int column = SquareHelper.getColumn(square); board[10 - row][1 + column] = piece_value; } public int getOpponentsColor() { if (active_color == PieceHelper.BLACK) return PieceHelper.WHITE; else return PieceHelper.BLACK; } @Override public void setToInitial() { board = initial_board; full_move_clock = 1; half_move_clock = 0; castling[0] = 31; castling[1] = 71; castling[2] = 38; castling[3] = 78; en_passant_target = -1; active_color = PieceHelper.WHITE; } @Override public void setToFEN(String fen) { board = new int[12][12]; castling[0] = -1; castling[1] = -1; castling[2] = -1; castling[3] = -1; en_passant_target = -1; String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 1; row <= 8; row++) { int offset = 0; for (int column = 1; column + offset <= 8; column++) { pieces = fen_rows[8 - row].toCharArray(); int square = (column + offset) * 10 + row; switch (pieces[column - 1]) { case 'P': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN, PieceHelper.WHITE)); break; case 'R': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK, PieceHelper.WHITE)); break; case 'N': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.KNIGHT, PieceHelper.WHITE)); break; case 'B': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.BISHOP, PieceHelper.WHITE)); break; case 'Q': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.QUEEN, PieceHelper.WHITE)); break; case 'K': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING, PieceHelper.WHITE)); break; case 'p': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.PAWN, PieceHelper.BLACK)); break; case 'r': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.ROOK, PieceHelper.BLACK)); break; case 'n': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.KNIGHT, PieceHelper.BLACK)); break; case 'b': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.BISHOP, PieceHelper.BLACK)); break; case 'q': setOnBoard(square, PieceHelper.pieceValue( PieceHelper.QUEEN, PieceHelper.BLACK)); break; case 'k': setOnBoard(square, PieceHelper.pieceValue(PieceHelper.KING, PieceHelper.BLACK)); break; default: offset += Character.getNumericValue(pieces[column - 1]) - 1; break; } } } // set active color switch (fen_parts[1]) { case "b": active_color = PieceHelper.BLACK; break; case "w": active_color = PieceHelper.WHITE; break; } // set possible castling moves if (!fen_parts[2].equals("-")) { char[] castlings = fen_parts[2].toCharArray(); for (int i = 0; i < castlings.length; i++) { switch (castlings[i]) { case 'K': castling[1] = 71; break; case 'Q': castling[0] = 31; break; case 'k': castling[3] = 78; break; case 'q': castling[2] = 38; break; } } } // set en passant square if (!fen_parts[3].equals("-")) { en_passant_target = SquareHelper.fromString(fen_parts[3]); } // set half move clock half_move_clock = Integer.parseInt(fen_parts[4]); // set full move clock full_move_clock = Integer.parseInt(fen_parts[5]); } @Override public NaiveBoard doMove(IMove move) { NaiveBoard newBoard = this.returnCopy(); int src = move.getFromSquare(); int dest = move.getToSquare(); // if promotion if (move.getPromotion() != 0) { newBoard.setOnBoard(src, 0); newBoard.setOnBoard(dest, PieceHelper.pieceValue(move.getPromotion(), active_color)); newBoard.half_move_clock = 0; } // If rochade else if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.KING && Math.abs((src - dest)) == 20) { newBoard.setOnBoard(dest, PieceHelper.pieceValue(PieceHelper.KING, active_color)); newBoard.setOnBoard(src, 0); newBoard.setOnBoard((src + dest) / 2, PieceHelper.pieceValue(PieceHelper.ROOK, active_color)); if (SquareHelper.getColumn(dest) == 3) newBoard.setOnBoard(src - 40, 0); else newBoard.setOnBoard(src + 30, 0); newBoard.half_move_clock++; } // If en passant else if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN && dest == this.getEnPassant()) { newBoard.setOnBoard(dest, PieceHelper.pieceValue(PieceHelper.PAWN, active_color)); newBoard.setOnBoard(src, 0); if (active_color == PieceHelper.WHITE) newBoard.setOnBoard(dest - 1, 0); else newBoard.setOnBoard(dest + 1, 0); newBoard.half_move_clock = 0; } // Usual move else { newBoard.setOnBoard(dest, this.getFromBoard(src)); newBoard.setOnBoard(src, 0); if (this.getFromBoard(dest) != 0 || PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN) newBoard.half_move_clock = 0; else newBoard.half_move_clock++; } // Change active_color after move newBoard.active_color = PieceHelper.pieceOppositeColor(this .getFromBoard(src)); if (active_color == PieceHelper.BLACK) newBoard.full_move_clock++; // Update en_passant if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.PAWN && Math.abs(dest - src) == 2) newBoard.en_passant_target = (dest + src) / 2; else newBoard.en_passant_target = -1; // Update castling if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.KING) { if (active_color == PieceHelper.WHITE && src == 51) { newBoard.castling[0] = -1; newBoard.castling[1] = -1; } else if (active_color == PieceHelper.BLACK && src == 58) { newBoard.castling[2] = -1; newBoard.castling[3] = -1; } } else if (PieceHelper.pieceType(this.getFromBoard(src)) == PieceHelper.ROOK) { if (active_color == PieceHelper.WHITE) { if (src == 81) newBoard.castling[1] = -1; else if (src == 11) newBoard.castling[0] = -1; } else { if (src == 88) newBoard.castling[3] = -1; else if (src == 18) newBoard.castling[2] = -1; } } return newBoard; } @Override public int getEnPassant() { return en_passant_target; } @Override public boolean canCastle(int king_to) { if ((king_to == 31 && castling[0] != -1) || (king_to == 71 && castling[1] != -1) || (king_to == 38 && castling[2] != -1) || (king_to == 78 && castling[3] != -1)) { return true; } else { return false; } } @Override public Set<Integer> getOccupiedSquaresByColor(int color) { if (occupied_squares_by_color.containsKey(color) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper .pieceColor(this.getFromBoard(square)) == color) set.add(square); } occupied_squares_by_color.put(color, set); return set; } return occupied_squares_by_color.get(color); } @Override public Set<Integer> getOccupiedSquaresByType(int type) { if (occupied_squares_by_type.containsKey(type) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceType(this.getFromBoard(square)) == type) set.add(square); } occupied_squares_by_type.put(type, set); return set; } return occupied_squares_by_type.get(type); } @Override public Set<Integer> getOccupiedSquaresByColorAndType(int color, int type) { if (occupied_squares_by_color_and_type.containsKey(PieceHelper .pieceValue(type, color)) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceValue(type, color) == this .getFromBoard(square)) set.add(square); } occupied_squares_by_color_and_type.put( PieceHelper.pieceValue(type, color), set); return set; } return occupied_squares_by_color_and_type.get(PieceHelper.pieceValue( type, color)); } @Override public int getNumberOfPiecesByColor(int color) { if (num_occupied_squares_by_color.containsKey(color) == false) { if (occupied_squares_by_color.containsKey(color) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceColor(this .getFromBoard(square)) == color) num++; } num_occupied_squares_by_color.put(color, num); return num; } num_occupied_squares_by_color.put(color, occupied_squares_by_color .get(color).size()); } return num_occupied_squares_by_color.get(color); } @Override public int getNumberOfPiecesByType(int type) { if (num_occupied_squares_by_type.containsKey(type) == false) { if (occupied_squares_by_type.containsKey(type) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && PieceHelper.pieceType(this .getFromBoard(square)) == type) num++; } num_occupied_squares_by_type.put(type, num); return num; } num_occupied_squares_by_type.put(type, occupied_squares_by_type .get(type).size()); } return num_occupied_squares_by_type.get(type); } @Override public int getNumberOfPiecesByColorAndType(int color, int type) { int value = PieceHelper.pieceValue(type, color); if (num_occupied_squares_by_color_and_type.containsKey(value) == false) { if (occupied_squares_by_color_and_type.containsKey(value) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (this.getFromBoard(square) > 0 && value == this.getFromBoard(square)) num++; } num_occupied_squares_by_color_and_type.put(value, num); return num; } num_occupied_squares_by_color_and_type.put(value, occupied_squares_by_color_and_type.get(value).size()); } return num_occupied_squares_by_color_and_type.get(value); } @Override public Set<IMove> getPossibleMoves() { if (possible_moves == null) { Set<IMove> total_set = new HashSet<IMove>(); Set<IMove> temp_set; // all the active squares Set<Integer> squares = getOccupiedSquaresByColor(active_color); // loop over all squares for (int square : squares) { temp_set = getPossibleMovesFrom(square); total_set.addAll(temp_set); } possible_moves = total_set; } return possible_moves; } @Override public Set<IMove> getPossibleMovesFrom(int square) { // The case, that the destination is the opponents king cannot happen. int type = PieceHelper.pieceType(getFromBoard(square)); int opp_color = getOpponentsColor(); List<Integer> squares; Set<IMove> moves = new HashSet<IMove>(); Move move; // Types BISHOP, QUEEN, ROOK if (type == PieceHelper.BISHOP || type == PieceHelper.QUEEN || type == PieceHelper.ROOK) { // Loop over all directions and skip not appropriate ones for (Direction direction : Direction.values()) { // Skip N,W,E,W with BISHOP and skip NE,NW,SE,SW with ROOK if (((direction == Direction.NORTH || direction == Direction.EAST || direction == Direction.SOUTH || direction == Direction.WEST) && type == PieceHelper.BISHOP) || ((direction == Direction.NORTHWEST || direction == Direction.NORTHEAST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && type == PieceHelper.ROOK)) { continue; } else { // do stuff squares = SquareHelper.getAllSquaresInDirection(square, direction); for (Integer new_square : squares) { if (getFromBoard(new_square) == 0 || PieceHelper .pieceColor(getFromBoard(new_square)) == opp_color) { move = new Move(square, new_square); moves.add(move); if (getFromBoard(new_square) != 0 && PieceHelper .pieceColor(getFromBoard(new_square)) == opp_color) break; } else break; } } } } if (type == PieceHelper.PAWN) { // If Pawn has not moved yet (steps possible) if ((SquareHelper.getRow(square) == 2 && active_color == PieceHelper.WHITE) || (SquareHelper.getRow(square) == 7 && active_color == PieceHelper.BLACK)) { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); if (getFromBoard(square + 2 * Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + 2 * Direction.pawnDirection(active_color).offset); moves.add(move); } } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getFromBoard(square + direction.offset) != 0 && PieceHelper.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) { move = new Move(square, square + direction.offset); moves.add(move); } } } // if Promotion will happen else if ((SquareHelper.getRow(square) == 7 && active_color == PieceHelper.WHITE) || (SquareHelper.getRow(square) == 2 && active_color == PieceHelper.BLACK)) { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.QUEEN); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.KNIGHT); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.ROOK); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, PieceHelper.BISHOP); moves.add(move); } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getFromBoard(square + direction.offset) != 0 && PieceHelper.pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) { move = new Move(square, square + direction.offset, PieceHelper.QUEEN); moves.add(move); move = new Move(square, square + direction.offset, PieceHelper.KNIGHT); moves.add(move); } } } // Usual turn and en passente is possible, no promotion else { if (getFromBoard(square + Direction.pawnDirection(active_color).offset) == 0) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if ((getFromBoard(square + direction.offset) != 0 && PieceHelper .pieceColor(getFromBoard(square + direction.offset)) == getOpponentsColor()) || square + direction.offset == getEnPassant()) { move = new Move(square, square + direction.offset); moves.add(move); } } } } if (type == PieceHelper.KING) { for (Direction direction : Direction.values()) { Integer new_square = square + direction.offset; move = new Move(square, new_square); if (SquareHelper.isValidSquare(new_square)) { // if the new square is empty or occupied by the opponent if (getFromBoard(new_square) == 0 || PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) moves.add(move); } } // Castle Moves // If the King is not check now, try castle moves if (!isCheckPosition()) { int off = 0; if (active_color == PieceHelper.BLACK) off = 2; for (int i = 0; i < 2; i++) { int castle_flag = 0; Integer new_square = castling[i + off]; // castling must still be possible to this side if (new_square != -1) { Direction dir; if (i == 0) dir = Direction.WEST; else dir = Direction.EAST; List<Integer> line = SquareHelper .getAllSquaresInDirection(square, dir); // Check each square if it is empty for (Integer squ : line) { if (getFromBoard(squ) != 0) { castle_flag = 1; break; } if (squ == new_square) break; } if (castle_flag == 1) continue; // Check each square if the king on it would be check for (Integer squ : line) { move = new Move(square, squ); NaiveBoard board = doMove(move); board.active_color = active_color; // TODO: ugly // solution ! ;) if (board.isCheckPosition()) break; if (squ == new_square) { // if EVERYTHING is right, // then add the move moves.add(move); break; } } } } } } if (type == PieceHelper.KNIGHT) { squares = SquareHelper.getAllSquaresByKnightStep(square); for (Integer new_square : squares) { if (getFromBoard(new_square) == 0 || PieceHelper.pieceColor(getFromBoard(new_square)) != active_color) { move = new Move(square, new_square); moves.add(move); } } } // remove invalid positions // TODO do this in a more efficient way Iterator<IMove> iter = moves.iterator(); while (iter.hasNext()) { NaiveBoard temp_board = this.doMove(iter.next()); temp_board.active_color = active_color; // ugly solution… if (temp_board.isCheckPosition()) { iter.remove(); } } return moves; } @Override public Set<IMove> getPossibleMovesTo(int square) { // TODO Auto-generated method stub return null; } @Override public boolean isCheckPosition() { if (is_check == null) { is_check = true; Set<Integer> temp_king_pos = getOccupiedSquaresByColorAndType( active_color, PieceHelper.KING); int king_pos = temp_king_pos.iterator().next(); // go in each direction for (Direction direction : Direction.values()) { List<Integer> line = SquareHelper.getAllSquaresInDirection( king_pos, direction); // go until… int iter = 0; for (int square : line) { iter++; // …some piece is found int piece = getFromBoard(square); if (piece != 0) { if (PieceHelper.pieceColor(piece) == active_color) { break; } else { if (PieceHelper.pieceType(piece) == PieceHelper.PAWN && iter == 1) { if (((direction == Direction.NORTHEAST || direction == Direction.NORTHWEST) && active_color == PieceHelper.WHITE) || ((direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && active_color == PieceHelper.BLACK)) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.ROOK) { if (direction == Direction.EAST || direction == Direction.WEST || direction == Direction.NORTH || direction == Direction.SOUTH) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.BISHOP) { if (direction == Direction.NORTHEAST || direction == Direction.NORTHWEST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) { return true; } } else if (PieceHelper.pieceType(piece) == PieceHelper.QUEEN) { return true; } else if (PieceHelper.pieceType(piece) == PieceHelper.KING && iter == 1) { return true; } break; } } } } // check for knight attacks List<Integer> knight_squares = SquareHelper .getAllSquaresByKnightStep(king_pos); for (int square : knight_squares) { int piece = getFromBoard(square); if (piece != 0) { if (PieceHelper.pieceColor(piece) != active_color && PieceHelper.pieceType(piece) == PieceHelper.KNIGHT) { return true; } } } is_check = false; } return is_check.booleanValue(); } @Override public boolean isMatePosition() { if (is_mate == null) { is_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty() && isCheckPosition()) return true; is_mate = false; } return is_mate.booleanValue(); } @Override public boolean isStaleMatePosition() { if (is_stale_mate == null) { is_stale_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty()) return true; is_stale_mate = false; } return is_stale_mate.booleanValue(); } @Override public boolean isPossibleMove(IMove move) { // TODO Auto-generated method stub return false; } public String toString() { return toFEN(); } @Override public String toFEN() { StringBuilder fen = new StringBuilder(); // piece placement for (int row = 2; row < 10; row++) { int counter = 0; for (int column = 2; column < 10; column++) { if (board[row][column] == 0) { counter++; } else { if (counter != 0) { fen.append(counter); counter = 0; } fen.append(PieceHelper.toString(board[row][column])); } if (column == 9 && counter != 0) { fen.append(counter); } } if (row != 9) { fen.append("/"); } } fen.append(" "); // active color if (active_color == PieceHelper.WHITE) { fen.append("w"); } else { fen.append("b"); } fen.append(" "); // castling availability boolean castle_flag = false; if (castling[1] != -1) { fen.append("K"); castle_flag = true; } if (castling[0] != -1) { fen.append("Q"); castle_flag = true; } if (castling[3] != -1) { fen.append("k"); castle_flag = true; } if (castling[2] != -1) { fen.append("q"); castle_flag = true; } if (!castle_flag) { fen.append("-"); } fen.append(" "); // en passant target square if (en_passant_target == -1) { fen.append("-"); } else { fen.append(SquareHelper.toString(en_passant_target)); } fen.append(" "); // halfmove clock fen.append(half_move_clock); fen.append(" "); // fullmove clock fen.append(full_move_clock); return fen.toString(); } @Override public int getActiveColor() { return active_color; } @Override public int getHalfMoveClock() { return half_move_clock; } @Override public int getFullMoveClock() { return full_move_clock; } }
reduced the number of getFromBoard calls... Mitzi is again a bit faster :)
src/mitzi/NaiveBoard.java
reduced the number of getFromBoard calls... Mitzi is again a bit faster :)
Java
mit
667955f70b12e8c45fc591e00b59a9b231ca02ef
0
GluuFederation/oxCore,madumlao/oxCore
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.ldap.model; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.persistence.Transient; import org.gluu.site.ldap.persistence.annotation.LdapAttribute; import org.gluu.site.ldap.persistence.annotation.LdapDN; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapJsonObject; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; /** * @author Yuriy Zabrovarnyy * @author Javier Rojas Blum * @version December 15, 2015 */ @LdapEntry @LdapObjectClass(values = { "top", "oxAuthSessionId" }) public class SimpleSessionState implements Serializable { private static final long serialVersionUID = -237476411915686378L; @LdapDN private String dn; @LdapAttribute(name = "uniqueIdentifier") private String id; @LdapAttribute(name = "oxLastAccessTime") private Date lastUsedAt; @LdapAttribute(name = "oxAuthUserDN") private String userDn; @LdapAttribute(name = "oxAuthAuthenticationTime") private Date authenticationTime; @LdapAttribute(name = "oxAuthSessionState") private Boolean permissionGranted; @LdapAttribute(name = "oxAsJwt") private Boolean isJwt = false; @LdapAttribute(name = "oxJwt") private String jwt; @LdapJsonObject @LdapAttribute(name = "oxAuthSessionAttribute") private Map<String, String> sessionAttributes; @Transient private transient boolean persisted; public String getDn() { return dn; } public void setDn(String dn) { this.dn = dn; } public String getJwt() { return jwt; } public void setJwt(String jwt) { this.jwt = jwt; } public Boolean getIsJwt() { return isJwt; } public void setIsJwt(Boolean isJwt) { this.isJwt = isJwt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getLastUsedAt() { return lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null; } public void setLastUsedAt(Date lastUsedAt) { this.lastUsedAt = lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null; } public String getUserDn() { return userDn; } public void setUserDn(String userDn) { this.userDn = userDn != null ? userDn : ""; } public Date getAuthenticationTime() { return authenticationTime != null ? new Date(authenticationTime.getTime()) : null; } public void setAuthenticationTime(Date authenticationTime) { this.authenticationTime = authenticationTime != null ? new Date(authenticationTime.getTime()) : null; } public Boolean getPermissionGranted() { return permissionGranted; } public void setPermissionGranted(Boolean permissionGranted) { this.permissionGranted = permissionGranted; } public Map<String, String> getSessionAttributes() { if (sessionAttributes == null) { sessionAttributes = new HashMap<String, String>(); } return sessionAttributes; } public void setSessionAttributes(Map<String, String> sessionAttributes) { this.sessionAttributes = sessionAttributes; } public boolean isPersisted() { return persisted; } public void setPersisted(boolean persisted) { this.persisted = persisted; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleSessionState id1 = (SimpleSessionState) o; return !(id != null ? !id.equals(id1.id) : id1.id != null); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SessionState"); sb.append(", dn='").append(dn).append('\''); sb.append(", id='").append(id).append('\''); sb.append(", isJwt=").append(isJwt); sb.append(", lastUsedAt=").append(lastUsedAt); sb.append(", userDn='").append(userDn).append('\''); sb.append(", authenticationTime=").append(authenticationTime); sb.append(", permissionGranted=").append(permissionGranted); sb.append(", sessionAttributes=").append(sessionAttributes); sb.append(", persisted=").append(persisted); sb.append('}'); return sb.toString(); } }
oxLdapSample/src/main/java/org/gluu/ldap/model/SimpleSessionState.java
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.ldap.model; import java.io.Serializable; import java.util.Date; import java.util.Map; import javax.persistence.Transient; import org.apache.commons.collections.map.HashedMap; import org.gluu.site.ldap.persistence.annotation.LdapAttribute; import org.gluu.site.ldap.persistence.annotation.LdapDN; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapJsonObject; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; /** * @author Yuriy Zabrovarnyy * @author Javier Rojas Blum * @version December 15, 2015 */ @LdapEntry @LdapObjectClass(values = { "top", "oxAuthSessionId" }) public class SimpleSessionState implements Serializable { private static final long serialVersionUID = -237476411915686378L; @LdapDN private String dn; @LdapAttribute(name = "uniqueIdentifier") private String id; @LdapAttribute(name = "oxLastAccessTime") private Date lastUsedAt; @LdapAttribute(name = "oxAuthUserDN") private String userDn; @LdapAttribute(name = "oxAuthAuthenticationTime") private Date authenticationTime; @LdapAttribute(name = "oxAuthSessionState") private Boolean permissionGranted; @LdapAttribute(name = "oxAsJwt") private Boolean isJwt = false; @LdapAttribute(name = "oxJwt") private String jwt; @LdapJsonObject @LdapAttribute(name = "oxAuthSessionAttribute") private Map<String, String> sessionAttributes; @Transient private transient boolean persisted; public String getDn() { return dn; } public void setDn(String dn) { this.dn = dn; } public String getJwt() { return jwt; } public void setJwt(String jwt) { this.jwt = jwt; } public Boolean getIsJwt() { return isJwt; } public void setIsJwt(Boolean isJwt) { this.isJwt = isJwt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getLastUsedAt() { return lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null; } public void setLastUsedAt(Date lastUsedAt) { this.lastUsedAt = lastUsedAt != null ? new Date(lastUsedAt.getTime()) : null; } public String getUserDn() { return userDn; } public void setUserDn(String userDn) { this.userDn = userDn != null ? userDn : ""; } public Date getAuthenticationTime() { return authenticationTime != null ? new Date(authenticationTime.getTime()) : null; } public void setAuthenticationTime(Date authenticationTime) { this.authenticationTime = authenticationTime != null ? new Date(authenticationTime.getTime()) : null; } public Boolean getPermissionGranted() { return permissionGranted; } public void setPermissionGranted(Boolean permissionGranted) { this.permissionGranted = permissionGranted; } public Map<String, String> getSessionAttributes() { if (sessionAttributes == null) { sessionAttributes = new HashedMap(); } return sessionAttributes; } public void setSessionAttributes(Map<String, String> sessionAttributes) { this.sessionAttributes = sessionAttributes; } public boolean isPersisted() { return persisted; } public void setPersisted(boolean persisted) { this.persisted = persisted; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleSessionState id1 = (SimpleSessionState) o; return !(id != null ? !id.equals(id1.id) : id1.id != null); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SessionState"); sb.append(", dn='").append(dn).append('\''); sb.append(", id='").append(id).append('\''); sb.append(", isJwt=").append(isJwt); sb.append(", lastUsedAt=").append(lastUsedAt); sb.append(", userDn='").append(userDn).append('\''); sb.append(", authenticationTime=").append(authenticationTime); sb.append(", permissionGranted=").append(permissionGranted); sb.append(", sessionAttributes=").append(sessionAttributes); sb.append(", persisted=").append(persisted); sb.append('}'); return sb.toString(); } }
Fix Map type
oxLdapSample/src/main/java/org/gluu/ldap/model/SimpleSessionState.java
Fix Map type
Java
mit
df5744bcd336c2d6b99fccd3bd21142781fc0d0b
0
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
package org.broadinstitute.sting.gatk.walkers.indels; import org.broadinstitute.sting.gatk.refdata.*; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.utils.cmdLine.Argument; @WalkerName("SNPClusters") @Requires(value={DataSource.REFERENCE},referenceMetaData={@RMD(name="snps",type=AllelicVariant.class)}) public class SNPClusterWalker extends RefWalker<GenomeLoc, GenomeLoc> { @Argument(fullName="windowSize", shortName="window", doc="window size for calculating clusters", required=false) int windowSize = 10; public void initialize() { if ( windowSize < 1) throw new RuntimeException("Window Size must be a positive integer"); } public GenomeLoc map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { AllelicVariant snp = (AllelicVariant)tracker.lookup("snps", null); return (snp != null && snp.isSNP()) ? context.getLocation() : null; } public void onTraversalDone(GenomeLoc sum) { if ( sum != null && sum.getStart() != sum.getStop() ) out.println(sum); } public GenomeLoc reduceInit() { return null; } public GenomeLoc reduce(GenomeLoc value, GenomeLoc sum) { // ignore non-SNP variants if ( value == null ) return sum; // if we have no previous SNPs start with the new location if ( sum == null ) return value; // if we hit a new contig, emit and start with the new location if ( sum.getContigIndex() != value.getContigIndex() ) { if ( sum.getStart() != sum.getStop() ) out.println(sum); return value; } // if the last SNP location was within a window, merge them if ( value.getStart() - sum.getStop() <= windowSize ) { sum = GenomeLocParser.setStop(sum,value.getStart()); return sum; } // otherwise, emit and start with the new location if ( sum.getStart() != sum.getStop() ) out.println(sum); return value; } }
java/src/org/broadinstitute/sting/gatk/walkers/indels/SNPClusterWalker.java
package org.broadinstitute.sting.gatk.walkers.indels; import org.broadinstitute.sting.gatk.refdata.*; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.gatk.walkers.*; import org.broadinstitute.sting.utils.cmdLine.Argument; @WalkerName("SNPClusters") @By(DataSource.REFERENCE) @Requires(DataSource.REFERENCE) @Allows(DataSource.REFERENCE) public class SNPClusterWalker extends RefWalker<GenomeLoc, GenomeLoc> { @Argument(fullName="windowSize", shortName="window", doc="window size for calculating clusters", required=false) int windowSize = 10; public void initialize() { if ( windowSize < 1) throw new RuntimeException("Window Size must be a positive integer"); } public GenomeLoc map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { AllelicVariant eval = (AllelicVariant)tracker.lookup("eval", null); if ( eval instanceof SNPCallFromGenotypes ) return context.getLocation(); return null; } public void onTraversalDone(GenomeLoc sum) { if ( sum != null && sum.getStart() != sum.getStop() ) out.println(sum); } public GenomeLoc reduceInit() { return null; } public GenomeLoc reduce(GenomeLoc value, GenomeLoc sum) { // ignore non-SNP variants if ( value == null ) return sum; // if we have no previous SNPs start with the new location if ( sum == null ) return value; // if we hit a new contig, emit and start with the new location if ( sum.getContigIndex() != value.getContigIndex() ) { if ( sum.getStart() != sum.getStop() ) out.println(sum); return value; } // if the last SNP location was within a window, merge them if ( value.getStart() - sum.getStop() <= windowSize ) { sum = GenomeLocParser.setStop(sum,value.getStart()); return sum; } // otherwise, emit and start with the new location if ( sum.getStart() != sum.getStop() ) out.println(sum); return value; } }
update this walker so any variants can be passed in git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@1426 348d0f76-0448-11de-a6fe-93d51630548a
java/src/org/broadinstitute/sting/gatk/walkers/indels/SNPClusterWalker.java
update this walker so any variants can be passed in
Java
epl-1.0
8d6c5ddba550aa81914eeb63b2a2ca54b75c1a77
0
minecrafter/SuperbVote,minecrafter/SuperbVote
package io.minimum.minecraft.superbvote.signboard; import io.minimum.minecraft.superbvote.SuperbVote; import io.minimum.minecraft.superbvote.configuration.message.MessageContext; import io.minimum.minecraft.superbvote.configuration.message.PlainStringMessage; import io.minimum.minecraft.superbvote.util.PlayerVotes; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.block.Skull; import java.util.List; import java.util.Optional; import java.util.UUID; @RequiredArgsConstructor public class TopPlayerSignUpdater implements Runnable { private final List<TopPlayerSign> toUpdate; private final List<PlayerVotes> top; private static final UUID QUESTION_MARK_HEAD = UUID.fromString("606e2ff0-ed77-4842-9d6c-e1d3321c7838"); static final BlockFace[] FACES = {BlockFace.SELF, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; public static Optional<Block> findSkullBlock(Block origin) { Block at = origin.getRelative(BlockFace.UP); for (BlockFace face : FACES) { Block b = at.getRelative(face); if (b.getType() == Material.PLAYER_HEAD || b.getType() == Material.PLAYER_WALL_HEAD) return Optional.of(b); } return Optional.empty(); } @Override public void run() { for (TopPlayerSign sign : toUpdate) { Block block = sign.getSign().getBukkitLocation().getBlock(); if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN) { Sign worldSign = (Sign) block.getState(); // TODO: Formatting if (sign.getPosition() > top.size()) { for (int i = 0; i < 4; i++) { worldSign.setLine(i, "???"); } } else { int lines = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().size(); for (int i = 0; i < Math.min(4, lines); i++) { PlainStringMessage m = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().get(i); PlayerVotes pv = top.get(sign.getPosition() - 1); worldSign.setLine(i, m.getWithOfflinePlayer(null, new MessageContext(null, pv, null)).replace("%num%", Integer.toString(sign.getPosition()))); } for (int i = lines; i < 4; i++) { worldSign.setLine(i, ""); } } worldSign.update(); // If a head location is also present, set the location for that. Optional<Block> headBlock = findSkullBlock(sign.getSign().getBukkitLocation().getBlock()); if (headBlock.isPresent()) { Block head = headBlock.get(); Skull skull = (Skull) head.getState(); skull.setOwningPlayer(Bukkit.getOfflinePlayer(sign.getPosition() > top.size() ? QUESTION_MARK_HEAD : top.get(sign.getPosition() - 1).getUuid())); skull.update(); } } } } }
src/main/java/io/minimum/minecraft/superbvote/signboard/TopPlayerSignUpdater.java
package io.minimum.minecraft.superbvote.signboard; import io.minimum.minecraft.superbvote.SuperbVote; import io.minimum.minecraft.superbvote.configuration.message.MessageContext; import io.minimum.minecraft.superbvote.configuration.message.PlainStringMessage; import io.minimum.minecraft.superbvote.util.PlayerVotes; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.Sign; import org.bukkit.block.Skull; import java.util.List; import java.util.Optional; import java.util.UUID; @RequiredArgsConstructor public class TopPlayerSignUpdater implements Runnable { private final List<TopPlayerSign> toUpdate; private final List<PlayerVotes> top; private static final UUID QUESTION_MARK_HEAD = UUID.fromString("606e2ff0-ed77-4842-9d6c-e1d3321c7838"); static final BlockFace[] FACES = {BlockFace.SELF, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; public static Optional<Block> findSkullBlock(Block origin) { Block at = origin.getRelative(BlockFace.UP); for (BlockFace face : FACES) { Block b = at.getRelative(face); System.out.println("at " + face + " block is " + b.getType()); if (b.getType() == Material.PLAYER_HEAD || b.getType() == Material.PLAYER_WALL_HEAD) return Optional.of(b); } return Optional.empty(); } @Override public void run() { for (TopPlayerSign sign : toUpdate) { Block block = sign.getSign().getBukkitLocation().getBlock(); System.out.println(block.getType()); if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN) { Sign worldSign = (Sign) block.getState(); // TODO: Formatting if (sign.getPosition() > top.size()) { for (int i = 0; i < 4; i++) { worldSign.setLine(i, "???"); } } else { int lines = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().size(); for (int i = 0; i < Math.min(4, lines); i++) { PlainStringMessage m = SuperbVote.getPlugin().getConfiguration().getTopPlayerSignsConfiguration().getSignText().get(i); PlayerVotes pv = top.get(sign.getPosition() - 1); worldSign.setLine(i, m.getWithOfflinePlayer(null, new MessageContext(null, pv, null)).replace("%num%", Integer.toString(sign.getPosition()))); } for (int i = lines; i < 4; i++) { worldSign.setLine(i, ""); } } worldSign.update(); // If a head location is also present, set the location for that. Optional<Block> headBlock = findSkullBlock(sign.getSign().getBukkitLocation().getBlock()); if (headBlock.isPresent()) { Block head = headBlock.get(); Skull skull = (Skull) head.getState(); skull.setOwningPlayer(Bukkit.getOfflinePlayer(sign.getPosition() > top.size() ? QUESTION_MARK_HEAD : top.get(sign.getPosition() - 1).getUuid())); skull.update(); } } } } }
Remove debug artifacts.
src/main/java/io/minimum/minecraft/superbvote/signboard/TopPlayerSignUpdater.java
Remove debug artifacts.
Java
mpl-2.0
789981a9f35da05fa384c67aa56e300505ebaa7b
0
crankycoder/MozStumbler,cascheberg/MozStumbler,priyankvex/MozStumbler,cascheberg/MozStumbler,crankycoder/MozStumbler,petercpg/MozStumbler,priyankvex/MozStumbler,petercpg/MozStumbler,cascheberg/MozStumbler,petercpg/MozStumbler,MozillaCZ/MozStumbler,MozillaCZ/MozStumbler,priyankvex/MozStumbler,crankycoder/MozStumbler,MozillaCZ/MozStumbler
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.mozstumbler.client.navdrawer; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.TextView; import com.ocpsoft.pretty.time.PrettyTime; import org.mozilla.mozstumbler.R; import org.mozilla.mozstumbler.client.ClientPrefs; import org.mozilla.mozstumbler.client.DateTimeUtils; import org.mozilla.mozstumbler.service.AppGlobals; import org.mozilla.mozstumbler.service.Prefs; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageContract; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageManager; import org.mozilla.mozstumbler.service.uploadthread.AsyncUploadParam; import org.mozilla.mozstumbler.service.uploadthread.AsyncUploader; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.Date; import java.util.Locale; import java.util.Properties; public class MetricsView { public interface IMapLayerToggleListener { public void setShowMLS(boolean isOn); } private static final String LOG_TAG = AppGlobals.LOG_PREFIX + MetricsView.class.getSimpleName(); private final TextView mLastUpdateTimeView, mAllTimeObservationsSentView, mAllTimeCellsSentView, mAllTimeWifisSentView, mQueuedObservationsView, mQueuedCellsView, mQueuedWifisView, mThisSessionObservationsView; private final CheckBox mOnMapShowMLS; private WeakReference<IMapLayerToggleListener> mMapLayerToggleListener = new WeakReference<IMapLayerToggleListener>(null); private final Handler mHandler = new Handler(Looper.getMainLooper()); private final long FREQ_UPDATE_UPLOADTIME = 10 * 1000; private ImageButton mUploadButton; private final View mView; private long mTotalBytesUploadedThisSession_lastDisplayed = -1; private long mLastUploadTime = 0; private final String mObservationAndSize = "%1$d %2$s"; private boolean mHasQueuedObservations; private static int mThisSessionObservationsCount; public MetricsView(View view) { mView = view; mOnMapShowMLS = (CheckBox) mView.findViewById(R.id.checkBox_show_mls); mOnMapShowMLS.setVisibility(View.GONE); mOnMapShowMLS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ClientPrefs.getInstance().setOnMapShowMLS(mOnMapShowMLS.isChecked()); if (mMapLayerToggleListener.get() != null) { mMapLayerToggleListener.get().setShowMLS(mOnMapShowMLS.isChecked()); } } }); mLastUpdateTimeView = (TextView) mView.findViewById(R.id.last_upload_time_value); mAllTimeObservationsSentView = (TextView) mView.findViewById(R.id.observations_sent_value); mAllTimeCellsSentView = (TextView) mView.findViewById(R.id.cells_sent_value); mAllTimeWifisSentView = (TextView) mView.findViewById(R.id.wifis_sent_value); mQueuedObservationsView = (TextView) mView.findViewById(R.id.observations_queued_value); mQueuedCellsView = (TextView) mView.findViewById(R.id.cells_queued_value); mQueuedWifisView = (TextView) mView.findViewById(R.id.wifis_queued_value); mThisSessionObservationsView = (TextView) mView.findViewById(R.id.this_session_observations_value); mUploadButton = (ImageButton) mView.findViewById(R.id.upload_observations_button); mUploadButton.setEnabled(false); mUploadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mHasQueuedObservations) { return; } // @TODO: Emit a signal here to initiate an upload // and have it handled by MainApp AsyncUploader uploader = new AsyncUploader(); AsyncUploadParam param = new AsyncUploadParam(false /* useWifiOnly */, Prefs.getInstance().getNickname(), Prefs.getInstance().getEmail()); uploader.execute(param); setUploadButtonToSyncing(true); } }); mHandler.postDelayed(mUpdateLastUploadedLabel, FREQ_UPDATE_UPLOADTIME); } public void setMapLayerToggleListener(IMapLayerToggleListener listener) { mMapLayerToggleListener = new WeakReference<IMapLayerToggleListener>(listener); mOnMapShowMLS.setChecked(ClientPrefs.getInstance().getOnMapShowMLS()); } private boolean buttonIsSyncIcon; private void updateUploadButtonEnabled() { if (buttonIsSyncIcon) { mUploadButton.setEnabled(false); } else { mUploadButton.setEnabled(mHasQueuedObservations); } } private void setUploadButtonToSyncing(boolean isSyncing) { if (isSyncing) { mUploadButton.setImageResource(android.R.drawable.ic_popup_sync); } else { mUploadButton.setImageResource(R.drawable.ic_action_upload); } buttonIsSyncIcon = isSyncing; updateUploadButtonEnabled(); } public void setUploadState(boolean isUploadingObservations) { updateUiThread(); } private void updateUiThread() { mHandler.post(new Runnable() { @Override public void run() { update(); } }); } public void update() { DataStorageManager dm = DataStorageManager.getInstance(); if (dm == null) { return; } updateQueuedStats(dm); updateSentStats(dm); updateThisSessionStats(); setUploadButtonToSyncing(AsyncUploader.isUploading.get()); } public void onOpened() { if (ClientPrefs.getInstance().isOptionEnabledToShowMLSOnMap()) { mOnMapShowMLS.setVisibility(View.VISIBLE); } else { mOnMapShowMLS.setVisibility(View.GONE); } update(); } private void updateThisSessionStats() { if (mThisSessionObservationsCount < 1) { mThisSessionObservationsView.setText("0"); return; } long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get(); String val = String.format(mObservationAndSize, mThisSessionObservationsCount, formatKb(bytesUploadedThisSession)); mThisSessionObservationsView.setText(val); } String formatKb(long bytes) { float kb = bytes / 1000.0f; if (kb < 0.1) { return ""; // don't show 0.0 for size. } return "(" + (Math.round(kb * 10.0f) / 10.0f) + " KB)"; } private final Runnable mUpdateLastUploadedLabel = new Runnable() { @Override public void run() { updateLastUploadedLabel(); mHandler.postDelayed(mUpdateLastUploadedLabel, FREQ_UPDATE_UPLOADTIME); } }; private void updateLastUploadedLabel() { String value = (String) mView.getContext().getText(R.string.metrics_observations_last_upload_time_never); if (mLastUploadTime > 0) { if (Locale.getDefault().getLanguage().equals("en")) { value = new PrettyTime().format(new Date(mLastUploadTime)); } else { value = DateTimeUtils.formatTimeForLocale(mLastUploadTime); } } mLastUpdateTimeView.setText(value); } private void updateSentStats(DataStorageManager dataStorageManager) { final long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get(); if (mTotalBytesUploadedThisSession_lastDisplayed == bytesUploadedThisSession) { // no need to update return; } mTotalBytesUploadedThisSession_lastDisplayed = bytesUploadedThisSession; try { Properties props = dataStorageManager.readSyncStats(); String value; value = props.getProperty(DataStorageContract.Stats.KEY_CELLS_SENT, "0"); mAllTimeCellsSentView.setText(String.valueOf(value)); value = props.getProperty(DataStorageContract.Stats.KEY_WIFIS_SENT, "0"); mAllTimeWifisSentView.setText(String.valueOf(value)); value = props.getProperty(DataStorageContract.Stats.KEY_OBSERVATIONS_SENT, "0"); String bytes = props.getProperty(DataStorageContract.Stats.KEY_BYTES_SENT, "0"); value = String.format(mObservationAndSize, Integer.parseInt(value), formatKb(Long.parseLong(bytes))); mAllTimeObservationsSentView.setText(value); mLastUploadTime = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_LAST_UPLOAD_TIME, "0")); updateLastUploadedLabel(); } catch (IOException ex) { Log.e(LOG_TAG, "Exception in updateSentStats()", ex); } } private void updateQueuedStats(DataStorageManager dataStorageManager) { DataStorageManager.QueuedCounts q = dataStorageManager.getQueuedCounts(); mQueuedCellsView.setText(String.valueOf(q.mCellCount)); mQueuedWifisView.setText(String.valueOf(q.mWifiCount)); String val = String.format(mObservationAndSize, q.mReportCount, formatKb(q.mBytes)); mQueuedObservationsView.setText(val); mHasQueuedObservations = q.mReportCount > 0; updateUploadButtonEnabled(); } public void setObservationCount(int count) { mThisSessionObservationsCount = count; updateThisSessionStats(); } }
android/src/main/java/org/mozilla/mozstumbler/client/navdrawer/MetricsView.java
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.mozstumbler.client.navdrawer; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.TextView; import com.ocpsoft.pretty.time.PrettyTime; import org.mozilla.mozstumbler.R; import org.mozilla.mozstumbler.client.ClientPrefs; import org.mozilla.mozstumbler.client.DateTimeUtils; import org.mozilla.mozstumbler.service.AppGlobals; import org.mozilla.mozstumbler.service.Prefs; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageContract; import org.mozilla.mozstumbler.service.stumblerthread.datahandling.DataStorageManager; import org.mozilla.mozstumbler.service.uploadthread.AsyncUploadParam; import org.mozilla.mozstumbler.service.uploadthread.AsyncUploader; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.Date; import java.util.Locale; import java.util.Properties; public class MetricsView { public interface IMapLayerToggleListener { public void setShowMLS(boolean isOn); } private static final String LOG_TAG = AppGlobals.LOG_PREFIX + MetricsView.class.getSimpleName(); private final TextView mLastUpdateTimeView, mAllTimeObservationsSentView, mAllTimeCellsSentView, mAllTimeWifisSentView, mQueuedObservationsView, mQueuedCellsView, mQueuedWifisView, mThisSessionObservationsView; private final CheckBox mOnMapShowMLS; private WeakReference<IMapLayerToggleListener> mMapLayerToggleListener = new WeakReference<IMapLayerToggleListener>(null); private ImageButton mUploadButton; private final View mView; private long mTotalBytesUploaded_lastDisplayed = -1; private final String mObservationAndSize = "%1$d %2$s"; private boolean mHasQueuedObservations; private static int mThisSessionObservationsCount; public MetricsView(View view) { mView = view; mOnMapShowMLS = (CheckBox) mView.findViewById(R.id.checkBox_show_mls); mOnMapShowMLS.setVisibility(View.GONE); mOnMapShowMLS.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ClientPrefs.getInstance().setOnMapShowMLS(mOnMapShowMLS.isChecked()); if (mMapLayerToggleListener.get() != null) { mMapLayerToggleListener.get().setShowMLS(mOnMapShowMLS.isChecked()); } } }); mLastUpdateTimeView = (TextView) mView.findViewById(R.id.last_upload_time_value); mAllTimeObservationsSentView = (TextView) mView.findViewById(R.id.observations_sent_value); mAllTimeCellsSentView = (TextView) mView.findViewById(R.id.cells_sent_value); mAllTimeWifisSentView = (TextView) mView.findViewById(R.id.wifis_sent_value); mQueuedObservationsView = (TextView) mView.findViewById(R.id.observations_queued_value); mQueuedCellsView = (TextView) mView.findViewById(R.id.cells_queued_value); mQueuedWifisView = (TextView) mView.findViewById(R.id.wifis_queued_value); mThisSessionObservationsView = (TextView) mView.findViewById(R.id.this_session_observations_value); mUploadButton = (ImageButton) mView.findViewById(R.id.upload_observations_button); mUploadButton.setEnabled(false); mUploadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mHasQueuedObservations) { return; } // @TODO: Emit a signal here to initiate an upload // and have it handled by MainApp AsyncUploader uploader = new AsyncUploader(); AsyncUploadParam param = new AsyncUploadParam(false /* useWifiOnly */, Prefs.getInstance().getNickname(), Prefs.getInstance().getEmail()); uploader.execute(param); setUploadButtonToSyncing(true); } }); } public void setMapLayerToggleListener(IMapLayerToggleListener listener) { mMapLayerToggleListener = new WeakReference<IMapLayerToggleListener>(listener); mOnMapShowMLS.setChecked(ClientPrefs.getInstance().getOnMapShowMLS()); } private boolean buttonIsSyncIcon; private void updateUploadButtonEnabled() { if (buttonIsSyncIcon) { mUploadButton.setEnabled(false); } else { mUploadButton.setEnabled(mHasQueuedObservations); } } private void setUploadButtonToSyncing(boolean isSyncing) { if (isSyncing) { mUploadButton.setImageResource(android.R.drawable.ic_popup_sync); } else { mUploadButton.setImageResource(R.drawable.ic_action_upload); } buttonIsSyncIcon = isSyncing; updateUploadButtonEnabled(); } public void setUploadState(boolean isUploadingObservations) { updateUiThread(); } private void updateUiThread() { Handler h = new Handler(Looper.getMainLooper()); h.post(new Runnable() { @Override public void run() { update(); } }); } public void update() { DataStorageManager dm = DataStorageManager.getInstance(); if (dm == null) { return; } updateQueuedStats(dm); updateSentStats(dm); updateThisSessionStats(); setUploadButtonToSyncing(AsyncUploader.isUploading.get()); } public void onOpened() { if (ClientPrefs.getInstance().isOptionEnabledToShowMLSOnMap()) { mOnMapShowMLS.setVisibility(View.VISIBLE); } else { mOnMapShowMLS.setVisibility(View.GONE); } update(); } private void updateThisSessionStats() { if (mThisSessionObservationsCount < 1) { mThisSessionObservationsView.setText("0"); return; } long bytesUploadedThisSession = AsyncUploader.sTotalBytesUploadedThisSession.get(); String val = String.format(mObservationAndSize, mThisSessionObservationsCount, formatKb(bytesUploadedThisSession)); mThisSessionObservationsView.setText(val); } String formatKb(long bytes) { float kb = bytes / 1000.0f; if (kb < 0.1) { return ""; // don't show 0.0 for size. } return "(" + (Math.round(kb * 10.0f) / 10.0f) + " KB)"; } private void updateSentStats(DataStorageManager dataStorageManager) { try { Properties props = dataStorageManager.readSyncStats(); String value = (String) mView.getContext().getText(R.string.metrics_observations_last_upload_time_never); final long lastUploadTime = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_LAST_UPLOAD_TIME, "0")); if (lastUploadTime > 0) { if (Locale.getDefault().getLanguage().equals("en")) { value = new PrettyTime().format(new Date(lastUploadTime)); } else { value = DateTimeUtils.formatTimeForLocale(lastUploadTime); } } mLastUpdateTimeView.setText(value); final long bytes = Long.parseLong(props.getProperty(DataStorageContract.Stats.KEY_BYTES_SENT, "0")); if (mTotalBytesUploaded_lastDisplayed != -1 && mTotalBytesUploaded_lastDisplayed == bytes) { // no need to update return; } mTotalBytesUploaded_lastDisplayed = bytes; value = props.getProperty(DataStorageContract.Stats.KEY_CELLS_SENT, "0"); mAllTimeCellsSentView.setText(String.valueOf(value)); value = props.getProperty(DataStorageContract.Stats.KEY_WIFIS_SENT, "0"); mAllTimeWifisSentView.setText(String.valueOf(value)); value = props.getProperty(DataStorageContract.Stats.KEY_OBSERVATIONS_SENT, "0"); value = String.format(mObservationAndSize, Integer.parseInt(value), formatKb(bytes)); mAllTimeObservationsSentView.setText(value); } catch (IOException ex) { Log.e(LOG_TAG, "Exception in updateSentStats()", ex); } } private void updateQueuedStats(DataStorageManager dataStorageManager) { DataStorageManager.QueuedCounts q = dataStorageManager.getQueuedCounts(); mQueuedCellsView.setText(String.valueOf(q.mCellCount)); mQueuedWifisView.setText(String.valueOf(q.mWifiCount)); String val = String.format(mObservationAndSize, q.mReportCount, formatKb(q.mBytes)); mQueuedObservationsView.setText(val); mHasQueuedObservations = q.mReportCount > 0; updateUploadButtonEnabled(); } public void setObservationCount(int count) { mThisSessionObservationsCount = count; updateThisSessionStats(); } }
periodically update metrics last upload time
android/src/main/java/org/mozilla/mozstumbler/client/navdrawer/MetricsView.java
periodically update metrics last upload time
Java
agpl-3.0
9f05d97e93e479f1329efd871ced90566b24c6c5
0
jspacco/CloudCoder,x77686d/CloudCoder,jspacco/CloudCoder2,daveho/CloudCoder,daveho/CloudCoder,cloudcoderdotorg/CloudCoder,cloudcoderdotorg/CloudCoder,vjpudelski/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder2,cloudcoderdotorg/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,cloudcoderdotorg/CloudCoder,vjpudelski/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,csirkeee/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder,csirkeee/CloudCoder,wicky-info/CloudCoder,cloudcoderdotorg/CloudCoder,jspacco/CloudCoder,jspacco/CloudCoder2,vjpudelski/CloudCoder,vjpudelski/CloudCoder,vjpudelski/CloudCoder,daveho/CloudCoder,jspacco/CloudCoder2,jspacco/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,csirkeee/CloudCoder,x77686d/CloudCoder,csirkeee/CloudCoder,jspacco/CloudCoder2,csirkeee/CloudCoder,wicky-info/CloudCoder,wicky-info/CloudCoder,daveho/CloudCoder,vjpudelski/CloudCoder,x77686d/CloudCoder,x77686d/CloudCoder,jspacco/CloudCoder2,wicky-info/CloudCoder,x77686d/CloudCoder,wicky-info/CloudCoder,vjpudelski/CloudCoder,wicky-info/CloudCoder,cloudcoderdotorg/CloudCoder,daveho/CloudCoder
// CloudCoder - a web-based pedagogical programming environment // Copyright (C) 2011-2012, Jaime Spacco <[email protected]> // Copyright (C) 2011-2012, David H. Hovemeyer <[email protected]> // Copyright (C) 2013, York College of Pennsylvania // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.cloudcoder.builder2.csandbox; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Properties; import org.cloudcoder.builder2.ccompiler.Compiler; import org.cloudcoder.builder2.util.DeleteDirectoryRecursively; import org.cloudcoder.builder2.util.FileUtil; import org.cloudcoder.builder2.util.SingletonHolder; import org.cloudcoder.daemon.IOUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Compile the EasySandbox shared library. * This is a singleton object that can be used by many threads. * Some code in the overall process should guarantee that * the {@link #cleanup()} method is called on the singleton instance * before the process exits. * * @author David Hovemeyer */ public class EasySandboxSharedLibrary { private static Logger logger = LoggerFactory.getLogger(EasySandboxSharedLibrary.class); private static SingletonHolder<EasySandboxSharedLibrary, Properties> holder = new SingletonHolder<EasySandboxSharedLibrary, Properties>() { @Override protected EasySandboxSharedLibrary onCreate(Properties arg) { return new EasySandboxSharedLibrary(arg); } }; /** * Get the singleton instance. * * @return the singleton instance */ public static EasySandboxSharedLibrary getInstance(Properties config) { return holder.get(config); } /** * Check whether or not the singleton instance was created. * * @return true if the singleton instance was created, false if not */ public static boolean isCreated() { return holder.isCreated(); } // Fields private File tempDir; private String sharedLibraryPath; /** * Constructor. */ private EasySandboxSharedLibrary(Properties config) { try { build(config); } catch (Exception e) { logger.error("Could not build EasySandbox shared library", e); } } private void build(Properties config) throws IOException { // Get source code for the EasySandbox source files String source1 = sourceResourceToString("EasySandbox.c"); String source2 = sourceResourceToString("malloc.c"); this.tempDir = FileUtil.makeTempDir(config); // Compile the code and link it into a shared library Compiler compiler = new Compiler(tempDir, "EasySandbox.so"); compiler.addModule("EasySandbox.c", source1); compiler.addModule("malloc.c", source2); compiler.addFlag("-fPIC"); compiler.addFlag("-shared"); compiler.addEndFlag("-ldl"); if (!compiler.compile()) { for (String err : compiler.getCompilerOutput()) { logger.error("Compile error: {}", err); } throw new IOException("Error compiling EasySandbox shared library"); } sharedLibraryPath = tempDir.getAbsolutePath() + "/EasySandbox.so"; } /** * Get the path of the shared library. * * @return the path of the shared library, or null if the shared library is not available */ public String getSharedLibraryPath() { return sharedLibraryPath; } /** * Clean up. */ public void cleanup() { if (tempDir != null) { new DeleteDirectoryRecursively(tempDir).delete(); } } private String sourceResourceToString(String sourceFileName) throws IOException { InputStream in = null; try { in = this.getClass().getClassLoader().getResourceAsStream("org/cloudcoder/builder2/csandbox/res/" + sourceFileName); InputStreamReader r = new InputStreamReader(in); StringWriter sw = new StringWriter(); IOUtil.copy(r, sw); return sw.toString(); } finally { IOUtil.closeQuietly(in); } } }
CloudCoderBuilder2/src/org/cloudcoder/builder2/csandbox/EasySandboxSharedLibrary.java
// CloudCoder - a web-based pedagogical programming environment // Copyright (C) 2011-2012, Jaime Spacco <[email protected]> // Copyright (C) 2011-2012, David H. Hovemeyer <[email protected]> // Copyright (C) 2013, York College of Pennsylvania // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.cloudcoder.builder2.csandbox; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.Properties; import jline.internal.Log; import org.cloudcoder.builder2.ccompiler.Compiler; import org.cloudcoder.builder2.util.DeleteDirectoryRecursively; import org.cloudcoder.builder2.util.FileUtil; import org.cloudcoder.builder2.util.SingletonHolder; import org.cloudcoder.daemon.IOUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Compile the EasySandbox shared library. * This is a singleton object that can be used by many threads. * Some code in the overall process should guarantee that * the {@link #cleanup()} method is called on the singleton instance * before the process exits. * * @author David Hovemeyer */ public class EasySandboxSharedLibrary { private static Logger logger = LoggerFactory.getLogger(EasySandboxSharedLibrary.class); private static SingletonHolder<EasySandboxSharedLibrary, Properties> holder = new SingletonHolder<EasySandboxSharedLibrary, Properties>() { @Override protected EasySandboxSharedLibrary onCreate(Properties arg) { return new EasySandboxSharedLibrary(arg); } }; /** * Get the singleton instance. * * @return the singleton instance */ public static EasySandboxSharedLibrary getInstance(Properties config) { return holder.get(config); } /** * Check whether or not the singleton instance was created. * * @return true if the singleton instance was created, false if not */ public static boolean isCreated() { return holder.isCreated(); } // Fields private File tempDir; private String sharedLibraryPath; /** * Constructor. */ private EasySandboxSharedLibrary(Properties config) { try { build(config); } catch (Exception e) { logger.error("Could not build EasySandbox shared library", e); } } private void build(Properties config) throws IOException { // Get source code for the EasySandbox source files String source1 = sourceResourceToString("EasySandbox.c"); String source2 = sourceResourceToString("malloc.c"); this.tempDir = FileUtil.makeTempDir(config); // Compile the code and link it into a shared library Compiler compiler = new Compiler(tempDir, "EasySandbox.so"); compiler.addModule("EasySandbox.c", source1); compiler.addModule("malloc.c", source2); compiler.addFlag("-fPIC"); compiler.addFlag("-shared"); compiler.addEndFlag("-ldl"); if (!compiler.compile()) { for (String err : compiler.getCompilerOutput()) { Log.error("Compile error: {}", err); } throw new IOException("Error compiling EasySandbox shared library"); } sharedLibraryPath = tempDir.getAbsolutePath() + "/EasySandbox.so"; } /** * Get the path of the shared library. * * @return the path of the shared library, or null if the shared library is not available */ public String getSharedLibraryPath() { return sharedLibraryPath; } /** * Clean up. */ public void cleanup() { if (tempDir != null) { new DeleteDirectoryRecursively(tempDir).delete(); } } private String sourceResourceToString(String sourceFileName) throws IOException { InputStream in = null; try { in = this.getClass().getClassLoader().getResourceAsStream("org/cloudcoder/builder2/csandbox/res/" + sourceFileName); InputStreamReader r = new InputStreamReader(in); StringWriter sw = new StringWriter(); IOUtil.copy(r, sw); return sw.toString(); } finally { IOUtil.closeQuietly(in); } } }
fixed logging of compile errors
CloudCoderBuilder2/src/org/cloudcoder/builder2/csandbox/EasySandboxSharedLibrary.java
fixed logging of compile errors
Java
agpl-3.0
4ad151a17a9169870f8420ec8cff9a54a9da05a4
0
skylow95/libreplan,LibrePlan/libreplan,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan,dgray16/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,poum/libreplan,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,poum/libreplan,LibrePlan/libreplan,Marine-22/libre,dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,poum/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,skylow95/libreplan,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,Marine-22/libre,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.workreports.daos; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.libreplan.business.common.daos.IntegrationEntityDAO; import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.reports.dtos.WorkReportLineDTO; import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.workreports.entities.WorkReportLine; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * Dao for {@link WorkReportLineDAO} * * @author Diego Pino García <[email protected]> * @author Susana Montes Pedreira <[email protected]> */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) public class WorkReportLineDAO extends IntegrationEntityDAO<WorkReportLine> implements IWorkReportLineDAO { @SuppressWarnings("unchecked") @Override public List<WorkReportLine> findByOrderElement(OrderElement orderElement){ Criteria c = getSession().createCriteria(WorkReportLine.class).createCriteria("orderElement"); c.add(Restrictions.idEq(orderElement.getId())); return (List<WorkReportLine>) c.list(); } @SuppressWarnings("unchecked") @Override public List<WorkReportLineDTO> findByOrderElementGroupByResourceAndHourTypeAndDate( OrderElement orderElement) { String strQuery = "SELECT new org.libreplan.business.reports.dtos.WorkReportLineDTO(wrl.resource, wrl.typeOfWorkHours, wrl.date, SUM(wrl.effort)) " + "FROM WorkReportLine wrl " + "LEFT OUTER JOIN wrl.orderElement orderElement " + "WHERE orderElement = :orderElement " + "GROUP BY wrl.resource, wrl.typeOfWorkHours, wrl.date " + "ORDER BY wrl.resource, wrl.typeOfWorkHours, wrl.date"; // Set parameters Query query = getSession().createQuery(strQuery); query.setParameter("orderElement", orderElement); return (List<WorkReportLineDTO>) query.list(); } @Override public List<WorkReportLine> findByOrderElementAndChildren( OrderElement orderElement) { if (orderElement.isNewObject()) { return new ArrayList<WorkReportLine>(); } return findByOrderElementAndChildren(orderElement, false); } @SuppressWarnings("unchecked") @Override @Transactional(readOnly=true) public List<WorkReportLine> findByOrderElementAndChildren(OrderElement orderElement, boolean sortByDate) { // Create collection with current orderElement and all its children Collection<OrderElement> orderElements = orderElement.getAllChildren(); orderElements.add(orderElement); // Prepare criteria final Criteria criteria = getSession().createCriteria(WorkReportLine.class); criteria.add(Restrictions.in("orderElement", orderElements)); if (sortByDate) { criteria.addOrder(org.hibernate.criterion.Order.asc("date")); } return criteria.list(); } @Override @SuppressWarnings("unchecked") public List<WorkReportLine> findFilteredByDate(Date start, Date end) { Criteria criteria = getSession().createCriteria(WorkReportLine.class); if(start != null) { criteria.add(Restrictions.ge("date", start)); } if(end != null) { criteria.add(Restrictions.le("date", end)); } return criteria.list(); } @Override @SuppressWarnings("unchecked") public List<WorkReportLine> findByResources(List<Resource> resourcesList) { if (resourcesList.isEmpty()) { return Collections.emptyList(); } return getSession().createCriteria(WorkReportLine.class).add( Restrictions.in("resource", resourcesList)).list(); } }
libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportLineDAO.java
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.workreports.daos; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.libreplan.business.common.daos.IntegrationEntityDAO; import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.reports.dtos.WorkReportLineDTO; import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.workreports.entities.WorkReportLine; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; /** * Dao for {@link WorkReportLineDAO} * * @author Diego Pino García <[email protected]> * @author Susana Montes Pedreira <[email protected]> */ @Repository @Scope(BeanDefinition.SCOPE_SINGLETON) public class WorkReportLineDAO extends IntegrationEntityDAO<WorkReportLine> implements IWorkReportLineDAO { @SuppressWarnings("unchecked") @Override public List<WorkReportLine> findByOrderElement(OrderElement orderElement){ Criteria c = getSession().createCriteria(WorkReportLine.class).createCriteria("orderElement"); c.add(Restrictions.idEq(orderElement.getId())); return (List<WorkReportLine>) c.list(); } @SuppressWarnings("unchecked") @Override public List<WorkReportLineDTO> findByOrderElementGroupByResourceAndHourTypeAndDate( OrderElement orderElement) { String strQuery = "SELECT new org.libreplan.business.reports.dtos.WorkReportLineDTO(wrl.resource, wrl.typeOfWorkHours, wrl.date, SUM(wrl.effort)) " + "FROM WorkReportLine wrl " + "LEFT OUTER JOIN wrl.orderElement orderElement " + "WHERE orderElement = :orderElement " + "GROUP BY wrl.resource, wrl.typeOfWorkHours, wrl.date " + "ORDER BY wrl.resource, wrl.typeOfWorkHours, wrl.date"; // Set parameters Query query = getSession().createQuery(strQuery); query.setParameter("orderElement", orderElement); return (List<WorkReportLineDTO>) query.list(); } @Override public List<WorkReportLine> findByOrderElementAndChildren( OrderElement orderElement) { if (orderElement.isNewObject()) { return new ArrayList<WorkReportLine>(); } return findByOrderElementAndChildren(orderElement, false); } @SuppressWarnings("unchecked") @Override public List<WorkReportLine> findByOrderElementAndChildren(OrderElement orderElement, boolean sortByDate) { // Create collection with current orderElement and all its children Collection<OrderElement> orderElements = orderElement.getAllChildren(); orderElements.add(orderElement); // Prepare criteria final Criteria criteria = getSession().createCriteria(WorkReportLine.class); criteria.add(Restrictions.in("orderElement", orderElements)); if (sortByDate) { criteria.addOrder(org.hibernate.criterion.Order.asc("date")); } return criteria.list(); } @Override @SuppressWarnings("unchecked") public List<WorkReportLine> findFilteredByDate(Date start, Date end) { Criteria criteria = getSession().createCriteria(WorkReportLine.class); if(start != null) { criteria.add(Restrictions.ge("date", start)); } if(end != null) { criteria.add(Restrictions.le("date", end)); } return criteria.list(); } @Override @SuppressWarnings("unchecked") public List<WorkReportLine> findByResources(List<Resource> resourcesList) { if (resourcesList.isEmpty()) { return Collections.emptyList(); } return getSession().createCriteria(WorkReportLine.class).add( Restrictions.in("resource", resourcesList)).list(); } }
Set a method transactional. FEA: ItEr75S27PerProjectDashboard
libreplan-business/src/main/java/org/libreplan/business/workreports/daos/WorkReportLineDAO.java
Set a method transactional.
Java
lgpl-2.1
f465518593eb7aca8de023674a78ab8ace24be9a
0
lespea/Java-CEF,cmcotton/Java-CEF
/** * Extension.java 2011-09-06 * * Copyright 2011, Adam Lesperance * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.lespea.cef; //~--- non-JDK imports -------------------------------------------------------- import com.lespea.cef.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //~--- JDK imports ------------------------------------------------------------ import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; //~--- classes ---------------------------------------------------------------- /** * Object that holds the mapping of all the elements that are part of the CEF extension. * <p> * This object is immutable and once created no changes can be made! * * @version 1.0, 2011-09-06 * @author Adam Lesperance */ public class Extension implements Serializable { /** * Logger object */ private static final Logger LOG = LoggerFactory.getLogger( Extension.class ); /** Field description */ private static final long serialVersionUID = 1L; //~--- fields ------------------------------------------------------------- /** Field description */ private final String asString; /** Field description */ private final Map<String, String> fields; /** Field description */ private final int hashCode; //~--- constructors ------------------------------------------------------- /** * Create a new extension object using the provided map. All of the key/value pairs are checked * to ensure they are valid and the map is made read-only. * * @param extensionFields * the mapping of extension keys and their values * @throws InvalidExtensionKey * if one of the provided keys is invalid */ public Extension( final Map<String, String> extensionFields ) throws InvalidExtensionKey { // Use the # of pairs * 20 as an initial best-guess for the builder size final StringBuilder sb = new StringBuilder( extensionFields.size() * 20 ); Boolean first = true; /* * Loop over all of the element pairs and add them to the string builder. Conveniently when * we escape the keys/values we also check to make sure they're valid and if they aren't an * exception will be thrown. So we not only ensure everything is okay at creation, but we * also pre-calculate the string variable so future calls are instant for the small price of * memory space. */ for (final Entry<String, String> entry : extensionFields.entrySet()) { if (first) { first = false; } else { sb.append( " " ); } sb.append( StringUtils.escapeExtensionKey( entry.getKey() ) ); sb.append( "=" ); sb.append( StringUtils.escapeExtensionValue( entry.getValue() ) ); } Extension.LOG.debug( "The map was valid and turned into an unmodifiable collection" ); // Should be changeable but cast it anyway fields = Collections.unmodifiableMap( extensionFields ); Extension.LOG.debug( "The extension's string was calculated as {}", sb.toString() ); asString = sb.toString(); hashCode = fields.hashCode(); } //~--- methods ------------------------------------------------------------ @Override public boolean equals( final Object obj ) { if (this == obj) { return true; } else if (obj == null) { return false; } else if (this.getClass() != obj.getClass()) { return false; } else if (hashCode != obj.hashCode()) { return false; } else if (!fields.equals( ((Extension) obj).getFields() )) { return false; } return true; } @Override public int hashCode() { return hashCode; } @Override public String toString() { return asString; } //~--- get methods -------------------------------------------------------- /** * @return a copy of the fields present in the extension */ public Map<String, String> getFields() { return new HashMap<String, String>( fields ); } }
src/main/java/com/lespea/cef/Extension.java
/** * Extension.java 2011-09-06 * * Copyright 2011, Adam Lesperance * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.lespea.cef; //~--- non-JDK imports -------------------------------------------------------- import com.lespea.cef.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; //~--- JDK imports ------------------------------------------------------------ import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; //~--- classes ---------------------------------------------------------------- /** * Object that holds the mapping of all the elements that are part of the CEF extension. * <p> * This object is immutable and once created no changes can be made! * * @version 1.0, 2011-09-06 * @author Adam Lesperance */ public class Extension implements Serializable { /** * Logger object */ private static final Logger LOG = LoggerFactory.getLogger( Extension.class ); /** Field description */ private static final long serialVersionUID = 1L; //~--- fields ------------------------------------------------------------- /** Field description */ private final String asString; /** Field description */ private final Map<String, String> fields; //~--- constructors ------------------------------------------------------- /** * Create a new extension object using the provided map. All of the key/value pairs are checked * to ensure they are valid and the map is made read-only. * * @param extensionFields * the mapping of extension keys and their values * @throws InvalidExtensionKey * if one of the provided keys is invalid */ public Extension( final Map<String, String> extensionFields ) throws InvalidExtensionKey { // Use the # of pairs * 20 as an initial best-guess for the builder size final StringBuilder sb = new StringBuilder( extensionFields.size() * 20 ); Boolean first = true; /* * Loop over all of the element pairs and add them to the string builder. Conveniently when * we escape the keys/values we also check to make sure they're valid and if they aren't an * exception will be thrown. So we not only ensure everything is okay at creation, but we * also pre-calculate the string variable so future calls are instant for the small price of * memory space. */ for (final Entry<String, String> entry : extensionFields.entrySet()) { if (first) { first = false; } else { sb.append( " " ); } sb.append( StringUtils.escapeExtensionKey( entry.getKey() ) ); sb.append( "=" ); sb.append( StringUtils.escapeExtensionValue( entry.getValue() ) ); } Extension.LOG.debug( "The map was valid and turned into an unmodifiable collection" ); // Should be changeable but cast it anyway fields = Collections.unmodifiableMap( extensionFields ); Extension.LOG.debug( "The extension's string was calculated as {}", sb.toString() ); asString = sb.toString(); } //~--- methods ------------------------------------------------------------ @Override public boolean equals( final Object obj ) { if (this == obj) { return true; } else if (obj == null) { return false; } else if (this.getClass() != obj.getClass()) { return false; } else if (!fields.equals( ((Extension) obj).getFields() )) { return false; } return true; } @Override public int hashCode() { return fields.hashCode(); } @Override public String toString() { return asString; } //~--- get methods -------------------------------------------------------- /** * @return a copy of the fields present in the extension */ public Map<String, String> getFields() { return new HashMap<String, String>( fields ); } }
Precompute the hashcode as well and use it in equals to possibly save a lot of checks
src/main/java/com/lespea/cef/Extension.java
Precompute the hashcode as well and use it in equals to possibly save a lot of checks
Java
lgpl-2.1
534e1190ecaa30d78a513829be8fc26b9f3d2a38
0
hal/core,hal/core,hal/core,hal/core,hal/core
package org.jboss.as.console.client.shared.subsys.jca; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.shared.help.FormHelpPanel; import org.jboss.as.console.client.shared.subsys.Baseadress; import org.jboss.as.console.client.shared.subsys.jca.model.ResourceAdapter; import org.jboss.ballroom.client.widgets.forms.ComboBoxItem; import org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextBoxItem; import org.jboss.ballroom.client.widgets.forms.TextItem; import org.jboss.ballroom.client.widgets.tools.ToolButton; import org.jboss.ballroom.client.widgets.tools.ToolStrip; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; /** * @author Heiko Braun * @date 7/19/11 */ public class AdapterDetails { private VerticalPanel layout; private Form<ResourceAdapter> form; private ToolButton editBtn; private ResourceAdapterPresenter presenter; public AdapterDetails(final ResourceAdapterPresenter presenter) { this.presenter = presenter; layout = new VerticalPanel(); layout.setStyleName("fill-layout-width"); form = new Form<ResourceAdapter>(ResourceAdapter.class); form.setNumColumns(2); ToolStrip detailToolStrip = new ToolStrip(); editBtn = new ToolButton(Console.CONSTANTS.common_label_edit()); ClickHandler editHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { if(null == form.getEditedEntity()) return; if(editBtn.getText().equals(Console.CONSTANTS.common_label_edit())) presenter.onEdit(form.getEditedEntity()); else presenter.onSave(form.getEditedEntity().getName(), form.getChangedValues()); } }; editBtn.addClickHandler(editHandler); detailToolStrip.addToolButton(editBtn); ClickHandler clickHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { final ResourceAdapter ra = form.getEditedEntity(); Feedback.confirm( "Delete Resource Adapter", "Really delete Adapter '" + ra.getName() + "' ?", new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if (isConfirmed) { presenter.onDelete(ra); } } }); } }; ToolButton deleteBtn = new ToolButton(Console.CONSTANTS.common_label_delete()); deleteBtn.addClickHandler(clickHandler); detailToolStrip.addToolButton(deleteBtn); layout.add(detailToolStrip); // ---- TextItem nameItem = new TextItem("name", "Name"); TextBoxItem poolItem = new TextBoxItem("poolName", "Pool"); TextBoxItem jndiItem = new TextBoxItem("jndiName", "JNDI"); TextItem archiveItem = new TextItem("archive", "Archive"); ComboBoxItem txItem = new ComboBoxItem("transactionSupport", "TX"); txItem.setDefaultToFirstOption(true); txItem.setValueMap(new String[]{"NoTransaction", "LocalTransaction", "XATransaction"}); TextBoxItem classItem = new TextBoxItem("connectionClass", "Connection Class"); form.setFields(nameItem, jndiItem, poolItem, archiveItem); form.setFieldsInGroup("Advanced", new DisclosureGroupRenderer(), txItem, classItem); final FormHelpPanel helpPanel = new FormHelpPanel( new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = Baseadress.get(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "*"); return address; } }, form ); layout.add(helpPanel.asWidget()); layout.add(form.asWidget()); form.setEnabled(false ); } Widget asWidget() { return layout; } public Form<ResourceAdapter> getForm() { return form; } public void setEnabled(boolean b) { form.setEnabled(b); if(!b) editBtn.setText("Edit"); else editBtn.setText("Save"); } }
gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/AdapterDetails.java
package org.jboss.as.console.client.shared.subsys.jca; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.shared.help.FormHelpPanel; import org.jboss.as.console.client.shared.subsys.Baseadress; import org.jboss.as.console.client.shared.subsys.jca.model.ResourceAdapter; import org.jboss.ballroom.client.widgets.forms.ComboBoxItem; import org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextBoxItem; import org.jboss.ballroom.client.widgets.forms.TextItem; import org.jboss.ballroom.client.widgets.tools.ToolButton; import org.jboss.ballroom.client.widgets.tools.ToolStrip; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; /** * @author Heiko Braun * @date 7/19/11 */ public class AdapterDetails { private VerticalPanel layout; private Form<ResourceAdapter> form; private ToolButton editBtn; private ResourceAdapterPresenter presenter; public AdapterDetails(final ResourceAdapterPresenter presenter) { this.presenter = presenter; layout = new VerticalPanel(); layout.setStyleName("fill-layout-width"); form = new Form<ResourceAdapter>(ResourceAdapter.class); form.setNumColumns(2); ToolStrip detailToolStrip = new ToolStrip(); editBtn = new ToolButton(Console.CONSTANTS.common_label_edit()); ClickHandler editHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { if(editBtn.getText().equals(Console.CONSTANTS.common_label_edit())) presenter.onEdit(form.getEditedEntity()); else presenter.onSave(form.getEditedEntity().getName(), form.getChangedValues()); } }; editBtn.addClickHandler(editHandler); detailToolStrip.addToolButton(editBtn); ClickHandler clickHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { final ResourceAdapter ra = form.getEditedEntity(); Feedback.confirm( "Delete Resource Adapter", "Really delete Adapter '" + ra.getName() + "' ?", new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if (isConfirmed) { presenter.onDelete(ra); } } }); } }; ToolButton deleteBtn = new ToolButton(Console.CONSTANTS.common_label_delete()); deleteBtn.addClickHandler(clickHandler); detailToolStrip.addToolButton(deleteBtn); layout.add(detailToolStrip); // ---- TextItem nameItem = new TextItem("name", "Name"); TextBoxItem poolItem = new TextBoxItem("poolName", "Pool"); TextBoxItem jndiItem = new TextBoxItem("jndiName", "JNDI"); TextItem archiveItem = new TextItem("archive", "Archive"); ComboBoxItem txItem = new ComboBoxItem("transactionSupport", "TX"); txItem.setDefaultToFirstOption(true); txItem.setValueMap(new String[]{"NoTransaction", "LocalTransaction", "XATransaction"}); TextBoxItem classItem = new TextBoxItem("connectionClass", "Connection Class"); form.setFields(nameItem, jndiItem, poolItem, archiveItem); form.setFieldsInGroup("Advanced", new DisclosureGroupRenderer(), txItem, classItem); final FormHelpPanel helpPanel = new FormHelpPanel( new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = Baseadress.get(); address.add("subsystem", "resource-adapters"); address.add("resource-adapter", "*"); return address; } }, form ); layout.add(helpPanel.asWidget()); layout.add(form.asWidget()); form.setEnabled(false ); } Widget asWidget() { return layout; } public Form<ResourceAdapter> getForm() { return form; } public void setEnabled(boolean b) { form.setEnabled(b); if(!b) editBtn.setText("Edit"); else editBtn.setText("Save"); } }
prevent edit when no entity selected
gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/AdapterDetails.java
prevent edit when no entity selected
Java
lgpl-2.1
6d4d3fc90da3a4d8c1f36edc9898df5b3b883000
0
picketbox/picketbox,picketbox/picketbox,picketbox/picketbox
/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.security.auth.spi; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Principal; import java.security.acl.Group; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.FailedLoginException; import javax.security.auth.login.LoginException; import org.jboss.security.SecurityDomain; import org.jboss.security.auth.callback.ObjectCallback; import org.jboss.security.auth.certs.X509CertificateVerifier; /** * Base Login Module that uses X509Certificates as credentials for * authentication. * * This login module uses X509Certificates as a * credential. It takes the cert as an object and checks to see if the alias in * the truststore/keystore contains the same certificate. Subclasses of this * module should implement the getRoleSets() method defined by * AbstractServerLoginModule. Much of this module was patterned after the * UserNamePasswordLoginModule. * * @author <a href="mailto:[email protected]">Jason Essington</a> * @author [email protected] * @version $Revision$ */ public class BaseCertLoginModule extends AbstractServerLoginModule { /** A principal derived from the certificate alias */ private Principal identity; /** The client certificate */ private X509Certificate credential; /** The SecurityDomain to obtain the KeyStore/TrustStore from */ private SecurityDomain domain = null; /** An option certificate verifier */ private X509CertificateVerifier verifier; /** Override the super version to pickup the following options after first * calling the super method. * * option: securityDomain - the name of the SecurityDomain to obtain the * trust and keystore from. * option: verifier - the class name of the X509CertificateVerifier to use * for verification of the login certificate * * @see SecurityDomain * @see X509CertificateVerifier * * @param subject the Subject to update after a successful login. * @param callbackHandler the CallbackHandler that will be used to obtain the * the user identity and credentials. * @param sharedState a Map shared between all configured login module instances * @param options the parameters passed to the login module. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,?> sharedState, Map<String,?> options) { super.initialize(subject, callbackHandler, sharedState, options); trace = log.isTraceEnabled(); // Get the security domain and default to "other" String sd = (String) options.get("securityDomain"); if (sd == null) sd = "java:/jaas/other"; if( trace ) log.trace("securityDomain=" + sd); try { Object tempDomain = new InitialContext().lookup(sd); if (tempDomain instanceof SecurityDomain) { domain = (SecurityDomain) tempDomain; if( trace ) { if (domain != null) log.trace("found domain: " + domain.getClass().getName()); else log.trace("the domain " + sd + " is null!"); } } else { log.error("The domain " + sd + " is not a SecurityDomain. All authentication using this module will fail!"); } } catch (NamingException e) { log.error("Unable to find the securityDomain named: " + sd, e); } String option = (String) options.get("verifier"); if( option != null ) { try { ClassLoader loader = SecurityActions.getContextClassLoader(); Class<?> verifierClass = loader.loadClass(option); verifier = (X509CertificateVerifier) verifierClass.newInstance(); } catch(Throwable e) { if( trace ) log.trace("Failed to create X509CertificateVerifier", e); IllegalArgumentException ex = new IllegalArgumentException("Invalid verifier: "+option); ex.initCause(e); } } if( trace ) log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)"); } /** * Perform the authentication of the username and password. */ @SuppressWarnings("unchecked") public boolean login() throws LoginException { if( trace ) log.trace("enter: login()"); // See if shared credentials exist if (super.login() == true) { // Setup our view of the user Object username = sharedState.get("javax.security.auth.login.name"); if( username instanceof Principal ) identity = (Principal) username; else { String name = username.toString(); try { identity = createIdentity(name); } catch(Exception e) { log.debug("Failed to create principal", e); throw new LoginException("Failed to create principal: "+ e.getMessage()); } } Object password = sharedState.get("javax.security.auth.login.password"); if (password instanceof X509Certificate) credential = (X509Certificate) password; else if (password != null) { log.debug("javax.security.auth.login.password is not X509Certificate"); super.loginOk = false; return false; } return true; } super.loginOk = false; Object[] info = getAliasAndCert(); String alias = (String) info[0]; credential = (X509Certificate) info[1]; if (alias == null && credential == null) { identity = unauthenticatedIdentity; super.log.trace("Authenticating as unauthenticatedIdentity=" + identity); } if (identity == null) { try { identity = createIdentity(alias); } catch(Exception e) { log.debug("Failed to create identity for alias:"+alias, e); } if (!validateCredential(alias, credential)) { log.debug("Bad credential for alias=" + alias); throw new FailedLoginException("Supplied Credential did not match existing credential for " + alias); } } if (getUseFirstPass() == true) { // Add authentication info to shared state map sharedState.put("javax.security.auth.login.name", alias); sharedState.put("javax.security.auth.login.password", credential); } super.loginOk = true; if( trace ) { log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk); log.debug("exit: login()"); } return true; } /** Override to add the X509Certificate to the public credentials * @return * @throws LoginException */ public boolean commit() throws LoginException { boolean ok = super.commit(); if( ok == true ) { // Add the cert to the public credentials if (credential != null) { subject.getPublicCredentials().add(credential); } } return ok; } /** Subclasses need to override this to provide the roles for authorization * @return * @throws LoginException */ protected Group[] getRoleSets() throws LoginException { return new Group[0]; } protected Principal getIdentity() { return identity; } protected Object getCredentials() { return credential; } protected String getUsername() { String username = null; if (getIdentity() != null) username = getIdentity().getName(); return username; } protected Object[] getAliasAndCert() throws LoginException { if( trace ) log.trace("enter: getAliasAndCert()"); Object[] info = { null, null }; // prompt for a username and password if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available to collect authentication information"); } NameCallback nc = new NameCallback("Alias: "); ObjectCallback oc = new ObjectCallback("Certificate: "); Callback[] callbacks = { nc, oc }; String alias = null; X509Certificate cert = null; X509Certificate[] certChain; try { callbackHandler.handle(callbacks); alias = nc.getName(); Object tmpCert = oc.getCredential(); if (tmpCert != null) { if (tmpCert instanceof X509Certificate) { cert = (X509Certificate) tmpCert; if( trace ) log.trace("found cert " + cert.getSerialNumber().toString(16) + ":" + cert.getSubjectDN().getName()); } else if( tmpCert instanceof X509Certificate[] ) { certChain = (X509Certificate[]) tmpCert; if( certChain.length > 0 ) cert = certChain[0]; } else { String msg = "Don't know how to obtain X509Certificate from: " +tmpCert.getClass(); log.warn(msg); throw new LoginException(msg); } } else { log.warn("CallbackHandler did not provide a certificate"); } } catch (IOException e) { log.debug("Failed to invoke callback", e); throw new LoginException("Failed to invoke callback: "+e.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("CallbackHandler does not support: " + uce.getCallback()); } info[0] = alias; info[1] = cert; if( trace ) log.trace("exit: getAliasAndCert()"); return info; } protected boolean validateCredential(String alias, X509Certificate cert) { if( trace ) log.trace("enter: validateCredentail(String, X509Certificate)"); boolean isValid = false; // if we don't have a trust store, we'll just use the key store. KeyStore keyStore = null; KeyStore trustStore = null; if( domain != null ) { keyStore = domain.getKeyStore(); trustStore = domain.getTrustStore(); } if( trustStore == null ) trustStore = keyStore; if( verifier != null ) { // Have the verifier validate the cert if( trace ) log.trace("Validating cert using: "+verifier); isValid = verifier.verify(cert, alias, keyStore, trustStore); } else if (trustStore != null && cert != null) { // Look for the cert in the truststore using the alias X509Certificate storeCert = null; try { storeCert = (X509Certificate) trustStore.getCertificate(alias); if( trace ) { StringBuffer buf = new StringBuffer("\n\tSupplied Credential: "); buf.append(cert.getSerialNumber().toString(16)); buf.append("\n\t\t"); buf.append(cert.getSubjectDN().getName()); buf.append("\n\n\tExisting Credential: "); if( storeCert != null ) { buf.append(storeCert.getSerialNumber().toString(16)); buf.append("\n\t\t"); buf.append(storeCert.getSubjectDN().getName()); buf.append("\n"); } else { ArrayList<String> aliases = new ArrayList<String>(); Enumeration<String> en = trustStore.aliases(); while (en.hasMoreElements()) { aliases.add(en.nextElement()); } buf.append("No match for alias: "+alias+", we have aliases " + aliases); } log.trace(buf.toString()); } } catch (KeyStoreException e) { log.warn("failed to find the certificate for " + alias, e); } // Ensure that the two certs are equal if (cert.equals(storeCert)) isValid = true; } else { log.warn("Domain, KeyStore, or cert is null. Unable to validate the certificate."); } if( trace ) { log.trace("The supplied certificate " + (isValid ? "matched" : "DID NOT match") + " the certificate in the keystore."); log.trace("exit: validateCredentail(String, X509Certificate)"); } return isValid; } }
security-jboss-sx/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java
/* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.security.auth.spi; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.Principal; import java.security.acl.Group; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.FailedLoginException; import javax.security.auth.login.LoginException; import org.jboss.security.SecurityDomain; import org.jboss.security.auth.callback.ObjectCallback; import org.jboss.security.auth.certs.X509CertificateVerifier; /** * Base Login Module that uses X509Certificates as credentials for * authentication. * * This login module uses X509Certificates as a * credential. It takes the cert as an object and checks to see if the alias in * the truststore/keystore contains the same certificate. Subclasses of this * module should implement the getRoleSets() method defined by * AbstractServerLoginModule. Much of this module was patterned after the * UserNamePasswordLoginModule. * * @author <a href="mailto:[email protected]">Jason Essington</a> * @author [email protected] * @version $Revision$ */ public class BaseCertLoginModule extends AbstractServerLoginModule { /** A principal derived from the certificate alias */ private Principal identity; /** The client certificate */ private X509Certificate credential; /** The SecurityDomain to obtain the KeyStore/TrustStore from */ private SecurityDomain domain = null; /** An option certificate verifier */ private X509CertificateVerifier verifier; /** Override the super version to pickup the following options after first * calling the super method. * * option: securityDomain - the name of the SecurityDomain to obtain the * trust and keystore from. * option: verifier - the class name of the X509CertificateVerifier to use * for verification of the login certificate * * @see SecurityDomain * @see X509CertificateVerifier * * @param subject the Subject to update after a successful login. * @param callbackHandler the CallbackHandler that will be used to obtain the * the user identity and credentials. * @param sharedState a Map shared between all configured login module instances * @param options the parameters passed to the login module. */ public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,?> sharedState, Map<String,?> options) { super.initialize(subject, callbackHandler, sharedState, options); trace = log.isTraceEnabled(); // Get the security domain and default to "other" String sd = (String) options.get("securityDomain"); if (sd == null) sd = "java:/jaas/other"; if( trace ) log.trace("securityDomain=" + sd); try { Object tempDomain = new InitialContext().lookup(sd); if (tempDomain instanceof SecurityDomain) { domain = (SecurityDomain) tempDomain; if( trace ) { if (domain != null) log.trace("found domain: " + domain.getClass().getName()); else log.trace("the domain " + sd + " is null!"); } } else { log.error("The domain " + sd + " is not a SecurityDomain. All authentication using this module will fail!"); } } catch (NamingException e) { log.error("Unable to find the securityDomain named: " + sd, e); } String option = (String) options.get("verifier"); if( option != null ) { try { ClassLoader loader = SecurityActions.getContextClassLoader(); Class<?> verifierClass = loader.loadClass(option); verifier = (X509CertificateVerifier) verifierClass.newInstance(); } catch(Throwable e) { if( trace ) log.trace("Failed to create X509CertificateVerifier", e); IllegalArgumentException ex = new IllegalArgumentException("Invalid verifier: "+option); ex.initCause(e); } } if( trace ) log.trace("exit: initialize(Subject, CallbackHandler, Map, Map)"); } /** * Perform the authentication of the username and password. */ @SuppressWarnings("unchecked") public boolean login() throws LoginException { if( trace ) log.trace("enter: login()"); // See if shared credentials exist if (super.login() == true) { // Setup our view of the user Object username = sharedState.get("javax.security.auth.login.name"); if( username instanceof Principal ) identity = (Principal) username; else { String name = username.toString(); try { identity = createIdentity(name); } catch(Exception e) { log.debug("Failed to create principal", e); throw new LoginException("Failed to create principal: "+ e.getMessage()); } } Object password = sharedState.get("javax.security.auth.login.password"); if (password instanceof X509Certificate) credential = (X509Certificate) password; else if (password != null) { log.debug("javax.security.auth.login.password is not X509Certificate"); super.loginOk = false; return false; } return true; } super.loginOk = false; Object[] info = getAliasAndCert(); String alias = (String) info[0]; credential = (X509Certificate) info[1]; if (alias == null && credential == null) { identity = unauthenticatedIdentity; super.log.trace("Authenticating as unauthenticatedIdentity=" + identity); } if (identity == null) { try { identity = createIdentity(alias); } catch(Exception e) { log.debug("Failed to create identity for alias:"+alias, e); } if (!validateCredential(alias, credential)) { log.debug("Bad credential for alias=" + alias); throw new FailedLoginException("Supplied Credential did not match existing credential for " + alias); } } if (getUseFirstPass() == true) { // Add authentication info to shared state map sharedState.put("javax.security.auth.login.name", alias); sharedState.put("javax.security.auth.login.password", credential); } super.loginOk = true; if( trace ) { log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk); log.debug("exit: login()"); } return true; } /** Override to add the X509Certificate to the public credentials * @return * @throws LoginException */ public boolean commit() throws LoginException { boolean ok = super.commit(); if( ok == true ) { // Add the cert to the public credentials if (credential != null) { subject.getPublicCredentials().add(credential); } } return ok; } /** Subclasses need to override this to provide the roles for authorization * @return * @throws LoginException */ protected Group[] getRoleSets() throws LoginException { return new Group[0]; } protected Principal getIdentity() { return identity; } protected Object getCredentials() { return credential; } protected String getUsername() { String username = null; if (getIdentity() != null) username = getIdentity().getName(); return username; } protected Object[] getAliasAndCert() throws LoginException { if( trace ) log.trace("enter: getAliasAndCert()"); Object[] info = { null, null }; // prompt for a username and password if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available to collect authentication information"); } NameCallback nc = new NameCallback("Alias: "); ObjectCallback oc = new ObjectCallback("Certificate: "); Callback[] callbacks = { nc, oc }; String alias = null; X509Certificate cert = null; X509Certificate[] certChain; try { callbackHandler.handle(callbacks); alias = nc.getName(); Object tmpCert = oc.getCredential(); if (tmpCert != null) { if (tmpCert instanceof X509Certificate) { cert = (X509Certificate) tmpCert; if( trace ) log.trace("found cert " + cert.getSerialNumber().toString(16) + ":" + cert.getSubjectDN().getName()); } else if( tmpCert instanceof X509Certificate[] ) { certChain = (X509Certificate[]) tmpCert; if( certChain.length > 0 ) cert = certChain[0]; } else { String msg = "Don't know how to obtain X509Certificate from: " +tmpCert.getClass(); log.warn(msg); throw new LoginException(msg); } } else { log.warn("CallbackHandler did not provide a certificate"); } } catch (IOException e) { log.debug("Failed to invoke callback", e); throw new LoginException("Failed to invoke callback: "+e.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("CallbackHandler does not support: " + uce.getCallback()); } info[0] = alias; info[1] = cert; if( trace ) log.trace("exit: getAliasAndCert()"); return info; } protected boolean validateCredential(String alias, X509Certificate cert) { if( trace ) log.trace("enter: validateCredentail(String, X509Certificate)"); boolean isValid = false; // if we don't have a trust store, we'll just use the key store. KeyStore keyStore = null; KeyStore trustStore = null; if( domain != null ) { keyStore = domain.getKeyStore(); trustStore = domain.getTrustStore(); } if( trustStore == null ) trustStore = keyStore; if( verifier != null ) { // Have the verifier validate the cert if( trace ) log.trace("Validating cert using: "+verifier); isValid = verifier.verify(cert, alias, keyStore, trustStore); } else if (keyStore != null && cert != null) { // Look for the cert in the keystore using the alias X509Certificate storeCert = null; try { storeCert = (X509Certificate) keyStore.getCertificate(alias); if( trace ) { StringBuffer buf = new StringBuffer("\n\tSupplied Credential: "); buf.append(cert.getSerialNumber().toString(16)); buf.append("\n\t\t"); buf.append(cert.getSubjectDN().getName()); buf.append("\n\n\tExisting Credential: "); if( storeCert != null ) { buf.append(storeCert.getSerialNumber().toString(16)); buf.append("\n\t\t"); buf.append(storeCert.getSubjectDN().getName()); buf.append("\n"); } else { ArrayList<String> aliases = new ArrayList<String>(); Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { aliases.add(en.nextElement()); } buf.append("No match for alias: "+alias+", we have aliases " + aliases); } log.trace(buf.toString()); } } catch (KeyStoreException e) { log.warn("failed to find the certificate for " + alias, e); } // Ensure that the two certs are equal if (cert.equals(storeCert)) isValid = true; } else { log.warn("Domain, KeyStore, or cert is null. Unable to validate the certificate."); } if( trace ) { log.trace("The supplied certificate " + (isValid ? "matched" : "DID NOT match") + " the certificate in the keystore."); log.trace("exit: validateCredentail(String, X509Certificate)"); } return isValid; } }
SECURITY-558: use truststore by default and fallback to keystore
security-jboss-sx/jbosssx/src/main/java/org/jboss/security/auth/spi/BaseCertLoginModule.java
SECURITY-558: use truststore by default and fallback to keystore
Java
lgpl-2.1
81eb7b4a3366ca2fe9325c49fcaa5ae94497fd39
0
exedio/copernica,exedio/copernica,exedio/copernica
package com.exedio.cope.lib; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import bak.pcj.list.IntArrayList; public abstract class Database { public static final Database theInstance = createInstance(); private static final Database createInstance() { final String databaseName = Properties.getInstance().getDatabase(); final Class databaseClass; try { databaseClass = Class.forName(databaseName); } catch(ClassNotFoundException e) { final String m = "ERROR: class "+databaseName+" from cope.properties not found."; System.err.println(m); throw new RuntimeException(m); } if(!Database.class.isAssignableFrom(databaseClass)) { final String m = "ERROR: class "+databaseName+" from cope.properties not a subclass of "+Database.class.getName()+"."; System.err.println(m); throw new RuntimeException(m); } final Constructor constructor; try { constructor = databaseClass.getDeclaredConstructor(new Class[]{}); } catch(NoSuchMethodException e) { final String m = "ERROR: class "+databaseName+" from cope.properties has no default constructor."; System.err.println(m); throw new RuntimeException(m); } try { return (Database)constructor.newInstance(new Object[]{}); } catch(InstantiationException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } catch(IllegalAccessException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } catch(InvocationTargetException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } } private final boolean useDefineColumnTypes; protected Database() { this.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable; //System.out.println("using database "+getClass()); } private final Statement createStatement() { return new Statement(useDefineColumnTypes); } //private static int createTableTime = 0, dropTableTime = 0, checkEmptyTableTime = 0; public void createDatabase() { //final long time = System.currentTimeMillis(); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) createTable((Table)i.next()); for(Iterator i = Type.getTypes().iterator(); i.hasNext(); ) createMediaDirectories((Type)i.next()); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) createForeignKeyConstraints((Table)i.next()); //final long amount = (System.currentTimeMillis()-time); //createTableTime += amount; //System.out.println("CREATE TABLES "+amount+"ms accumulated "+createTableTime); } //private static int checkTableTime = 0; /** * Checks the database, * whether the database tables representing the types do exist. * Issues a single database statement, * that touches all tables and columns, * that would have been created by * {@link #createDatabase()}. * @throws SystemException * if something is wrong with the database. * TODO: use a more specific exception. */ public void checkDatabase() { //final long time = System.currentTimeMillis(); final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Table table = (Table)i.next(); bf.append(table.protectedID); } final Long testDate = new Long(System.currentTimeMillis()); bf.append(" where "); first = true; for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(" and "); final Table table = (Table)i.next(); final Column primaryKey = table.primaryKey; bf.append(table.protectedID). append('.'). append(primaryKey.protectedID). append('='). append(Type.NOT_A_PK); for(Iterator j = table.getColumns().iterator(); j.hasNext(); ) { final Column column = (Column)j.next(); bf.append(" and "). append(table.protectedID). append('.'). append(column.protectedID). append('='); if(column instanceof IntegerColumn) bf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1)); else if(column instanceof DoubleColumn) bf.appendValue(column, new Double(2.2)); else if(column instanceof StringColumn) bf.appendValue(column, "z"); else if(column instanceof TimestampColumn) bf.appendValue(column, testDate); else throw new RuntimeException(column.toString()); } } try { //System.out.println("checkDatabase:"+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } //final long amount = (System.currentTimeMillis()-time); //checkTableTime += amount; //System.out.println("CHECK TABLES "+amount+"ms accumulated "+checkTableTime); } public void dropDatabase() { //final long time = System.currentTimeMillis(); { final List types = Type.getTypes(); for(ListIterator i = types.listIterator(types.size()); i.hasPrevious(); ) ((Type)i.previous()).onDropTable(); } { final List tables = Table.getTables(); // must delete in reverse order, to obey integrity constraints for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); ) dropForeignKeyConstraints((Table)i.previous()); for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); ) dropTable((Table)i.previous()); } //final long amount = (System.currentTimeMillis()-time); //dropTableTime += amount; //System.out.println("DROP TABLES "+amount+"ms accumulated "+dropTableTime); } public void tearDownDatabase() { System.err.println("TEAR DOWN ALL DATABASE"); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { try { final Table table = (Table)i.next(); System.err.print("DROPPING FOREIGN KEY CONSTRAINTS "+table+"... "); dropForeignKeyConstraints(table); System.err.println("done."); } catch(SystemException e2) { System.err.println("failed:"+e2.getMessage()); } } for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { try { final Table table = (Table)i.next(); System.err.print("DROPPING TABLE "+table+" ... "); dropTable(table); System.err.println("done."); } catch(SystemException e2) { System.err.println("failed:"+e2.getMessage()); } } } public void checkEmptyTables() { //final long time = System.currentTimeMillis(); for(Iterator i = Type.getTypes().iterator(); i.hasNext(); ) { final Type type = (Type)i.next(); final int count = countTable(type); if(count>0) throw new RuntimeException("there are "+count+" items left for type "+type); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } final IntArrayList search(final Query query) { final Table selectTable = query.selectType.table; final Statement bf = createStatement(); bf.append("select "). append(selectTable.protectedID). append('.'). append(selectTable.primaryKey.protectedID).defineColumnInteger(). append(" from "); boolean first = true; for(Iterator i = query.fromTypes.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); bf.append(((Type)i.next()).table.protectedID); } if(query.condition!=null) { bf.append(" where "); query.condition.appendStatement(bf); } if(query.orderBy!=null) { bf.append(" order by "). append(query.orderBy); if(!query.orderAscending) bf.append(" desc"); } //System.out.println("searching "+bf.toString()); try { final QueryResultSetHandler handler = new QueryResultSetHandler(query.start, query.count); executeSQL(bf, handler); return handler.result; } catch(ConstraintViolationException e) { throw new SystemException(e); } } void load(final Row row) { final Statement bf = createStatement(); bf.append("select "); boolean first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { final Table table = type.table; final List columns = table.getColumns(); for(Iterator i = columns.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(table.protectedID). append('.'). append(column.protectedID).defineColumn(column); } } bf.append(" from "); first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(','); bf.append(type.table.protectedID); } bf.append(" where "); first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(" and "); final Table table = type.table; bf.append(table.protectedID). append('.'). append(table.primaryKey.protectedID). append('='). append(row.pk); } //System.out.println("loading "+bf.toString()); try { executeSQL(bf, new LoadResultSetHandler(row)); } catch(ConstraintViolationException e) { throw new SystemException(e); } } void store(final Row row) throws UniqueViolationException { store(row, row.type); } private void store(final Row row, final Type theType) // TODO: rename to type throws UniqueViolationException { final Type supertype = theType.getSupertype(); if(supertype!=null) store(row, supertype); final Table type = theType.table; // TODO: rename to table final List columns = type.getColumns(); final Statement bf = createStatement(); if(row.present) { bf.append("update "). append(type.protectedID). append(" set "); boolean first = true; for(Iterator i = columns.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID). append('='); final Object value = row.store(column); bf.append(column.cacheToDatabase(value)); } bf.append(" where "). append(type.primaryKey.protectedID). append('='). append(row.pk); } else { bf.append("insert into "). append(type.protectedID). append("("). append(type.primaryKey.protectedID); boolean first = true; for(Iterator i = columns.iterator(); i.hasNext(); ) { bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID); } bf.append(")values("). append(row.pk); for(Iterator i = columns.iterator(); i.hasNext(); ) { bf.append(','); final Column column = (Column)i.next(); final Object value = row.store(column); bf.append(column.cacheToDatabase(value)); } bf.append(')'); } try { //System.out.println("storing "+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(UniqueViolationException e) { throw e; } catch(ConstraintViolationException e) { throw new SystemException(e); } } void delete(final Type type, final int pk) throws IntegrityViolationException { for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype()) { final Table currentTable = currentType.table; final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). append(pk); //System.out.println("deleting "+bf.toString()); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(IntegrityViolationException e) { throw e; } catch(ConstraintViolationException e) { throw new SystemException(e); } } } private static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private static final ResultSetHandler EMPTY_RESULT_SET_HANDLER = new ResultSetHandler() { public void run(ResultSet resultSet) { } }; private static class QueryResultSetHandler implements ResultSetHandler { private final int start; private final int count; private final IntArrayList result = new IntArrayList(); QueryResultSetHandler(final int start, final int count) { this.start = start; this.count = count; if(start<0) throw new RuntimeException(); } public void run(ResultSet resultSet) throws SQLException { if(start>0) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(start+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = start; i>0; i--) resultSet.next(); } int i = (count>=0 ? count : Integer.MAX_VALUE); while(resultSet.next() && (--i)>=0) { final int pk = resultSet.getInt(1); //System.out.println("pk:"+pk); result.add(pk); } } } private static class LoadResultSetHandler implements ResultSetHandler { private final Row row; LoadResultSetHandler(final Row row) { this.row = row; } public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException("no such pk"); // TODO use some better exception int columnIndex = 1; for(Type type = row.type; type!=null; type = type.getSupertype()) { for(Iterator i = type.table.getColumns().iterator(); i.hasNext(); ) ((Column)i.next()).load(resultSet, columnIndex++, row); } return; } } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE for Oracle // Whether the returned object is an Integer or a BigDecimal, // depends on whether OracleStatement.defineColumnType is used or not, // so we support both here. if(sqlInteger instanceof BigDecimal) return ((BigDecimal)sqlInteger).intValue(); else return ((Integer)sqlInteger).intValue(); } private static class IntegerResultSetHandler implements ResultSetHandler { int result; public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); result = convertSQLResult(resultSet.getObject(1)); } } private static class NextPKResultSetHandler implements ResultSetHandler { int resultLo; int resultHi; public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); final Object oLo = resultSet.getObject(1); if(oLo==null) { resultLo = -1; resultHi = 0; } else { resultLo = convertSQLResult(oLo)-1; final Object oHi = resultSet.getObject(2); resultHi = convertSQLResult(oHi)+1; } } } //private static int timeExecuteQuery = 0; private void executeSQL(final Statement statement, final ResultSetHandler resultSetHandler) throws ConstraintViolationException { final ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { connection = connectionPool.getConnection(); // TODO: use prepared statements and reuse the statement. sqlStatement = connection.createStatement(); final String sqlText = statement.getText(); if(!sqlText.startsWith("select ")) { final int rows = sqlStatement.executeUpdate(sqlText); //System.out.println("("+rows+"): "+statement.getText()); } else { //long time = System.currentTimeMillis(); if(useDefineColumnTypes) ((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement); resultSet = sqlStatement.executeQuery(sqlText); //long interval = System.currentTimeMillis() - time; //timeExecuteQuery += interval; //System.out.println("executeQuery: "+interval+"ms sum "+timeExecuteQuery+"ms"); resultSetHandler.run(resultSet); } } catch(SQLException e) { final ConstraintViolationException wrappedException = wrapException(e); if(wrappedException!=null) throw wrappedException; else throw new SystemException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } if(connection!=null) { try { connectionPool.putConnection(connection); } catch(SQLException e) { // exception is already thrown } } } } protected abstract String extractUniqueConstraintName(SQLException e); protected abstract String extractIntegrityConstraintName(SQLException e); private final ConstraintViolationException wrapException(final SQLException e) { { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint = UniqueConstraint.findByID(uniqueConstraintID, e); return new UniqueViolationException(e, null, constraint); } } { final String integrityConstraintName = extractIntegrityConstraintName(e); if(integrityConstraintName!=null) { final ItemAttribute attribute = ItemAttribute.getItemAttributeByIntegrityConstraintName(integrityConstraintName, e); return new IntegrityViolationException(e, null, attribute); } } return null; } protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList words = new ArrayList(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength--; } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--) { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(Iterator i = words.iterator(); i.hasNext(); ) { final String word = (String)i.next(); //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder--; } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } //System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words); if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } String trimName(final Type type) { final String className = type.getJavaClass().getName(); final int pos = className.lastIndexOf('.'); return trimString(className.substring(pos+1), 25); } /** * Trims a name to length for being be a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ String trimName(final String longName) { return trimString(longName, 25); } /** * Protects a database name from being interpreted as a SQL keyword. * This is usually done by enclosing the name with some (database specific) delimiters. * The default implementation uses double quotes as delimiter. */ protected String protectName(String name) { return '"' + name + '"'; } abstract String getIntegerType(int precision); abstract String getDoubleType(int precision); abstract String getStringType(int maxLength); abstract String getDateTimestampType(); private void createTable(final Table table) { final Statement bf = createStatement(); bf.append("create table "). append(table.protectedID). append('('); boolean firstColumn = true; for(Iterator i = table.getAllColumns().iterator(); i.hasNext(); ) { if(firstColumn) firstColumn = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID). append(' '). append(column.databaseType); if(column.primaryKey) { bf.append(" primary key"); } else { if(column.notNull) bf.append(" not null"); } } // attribute constraints for(Iterator i = table.getColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(column instanceof StringColumn) { final StringColumn stringColumn = (StringColumn)column; if(stringColumn.minimumLengthID!=null) { bf.append(",constraint "). append(protectName(stringColumn.minimumLengthID)). append(" check(length("). append(column.protectedID). append(")>="). append(stringColumn.minimumLength); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } if(stringColumn.maximumLengthID!=null) { bf.append(",constraint "). append(protectName(stringColumn.maximumLengthID)). append(" check(length("). append(column.protectedID). append(")<="). append(stringColumn.maximumLength); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } } else if(column instanceof IntegerColumn) { final IntegerColumn intColumn = (IntegerColumn)column; final int[] allowedValues = intColumn.allowedValues; if(allowedValues!=null) { bf.append(",constraint "). append(protectName(intColumn.allowedValuesID)). append(" check("). append(column.protectedID). append(" in ("); for(int j = 0; j<allowedValues.length; j++) { if(j>0) bf.append(','); bf.append(allowedValues[j]); } bf.append(')'); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } } } for(Iterator i = table.getUniqueConstraints().iterator(); i.hasNext(); ) { final UniqueConstraint uniqueConstraint = (UniqueConstraint)i.next(); bf.append(",constraint "). append(uniqueConstraint.getProtectedID()). append(" unique("); boolean first = true; for(Iterator j = uniqueConstraint.getUniqueAttributes().iterator(); j.hasNext(); ) { if(first) first = false; else bf.append(','); final Attribute uniqueAttribute = (Attribute)j.next(); bf.append(uniqueAttribute.getMainColumn().protectedID); } bf.append(')'); } bf.append(')'); try { //System.out.println("createTable:"+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } private void createForeignKeyConstraints(final Table type) // TODO: rename to table { //System.out.println("createForeignKeyConstraints:"+bf); for(Iterator i = type.getAllColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); //System.out.println("createForeignKeyConstraints("+column+"):"+bf); if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; final Statement bf = createStatement(); bf.append("alter table "). append(type.protectedID). append(" add constraint "). append(Database.theInstance.protectName(itemColumn.integrityConstraintName)). append(" foreign key ("). append(column.protectedID). append(") references "). append(itemColumn.getForeignTableNameProtected()); try { //System.out.println("createForeignKeyConstraints:"+bf); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } } } private void createMediaDirectories(final Type type) { File typeDirectory = null; for(Iterator i = type.getAttributes().iterator(); i.hasNext(); ) { final Attribute attribute = (Attribute)i.next(); if(attribute instanceof MediaAttribute) { if(typeDirectory==null) { final File directory = Properties.getInstance().getMediaDirectory(); typeDirectory = new File(directory, type.id); typeDirectory.mkdir(); } final File attributeDirectory = new File(typeDirectory, attribute.getName()); attributeDirectory.mkdir(); } } } private void dropTable(final Table type) // TODO: rename to table { final Statement bf = createStatement(); bf.append("drop table "). append(type.protectedID); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } private int countTable(final Type type) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(type.table.protectedID); try { final IntegerResultSetHandler handler = new IntegerResultSetHandler(); executeSQL(bf, handler); return handler.result; } catch(ConstraintViolationException e) { throw new SystemException(e); } } private void dropForeignKeyConstraints(final Table type) // TODO: rename to table { for(Iterator i = type.getColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); //System.out.println("dropForeignKeyConstraints("+column+")"); if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; final Statement bf = createStatement(); boolean hasOne = false; bf.append("alter table "). append(type.protectedID). append(" drop constraint "). append(Database.theInstance.protectName(itemColumn.integrityConstraintName)); //System.out.println("dropForeignKeyConstraints:"+bf); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } } } int[] getNextPK(final Type type) { final Statement bf = createStatement(); final Table table = type.table; final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); try { final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQL(bf, handler); //System.err.println("select max("+type.primaryKey.trimmedName+") from "+type.trimmedName+" : "+handler.result); return new int[] {handler.resultLo, handler.resultHi}; } catch(ConstraintViolationException e) { throw new SystemException(e); } } }
lib/src/com/exedio/cope/lib/Database.java
package com.exedio.cope.lib; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import bak.pcj.list.IntArrayList; public abstract class Database { public static final Database theInstance = createInstance(); private static final Database createInstance() { final String databaseName = Properties.getInstance().getDatabase(); final Class databaseClass; try { databaseClass = Class.forName(databaseName); } catch(ClassNotFoundException e) { final String m = "ERROR: class "+databaseName+" from cope.properties not found."; System.err.println(m); throw new RuntimeException(m); } if(!Database.class.isAssignableFrom(databaseClass)) { final String m = "ERROR: class "+databaseName+" from cope.properties not a subclass of "+Database.class.getName()+"."; System.err.println(m); throw new RuntimeException(m); } final Constructor constructor; try { constructor = databaseClass.getDeclaredConstructor(new Class[]{}); } catch(NoSuchMethodException e) { final String m = "ERROR: class "+databaseName+" from cope.properties has no default constructor."; System.err.println(m); throw new RuntimeException(m); } try { return (Database)constructor.newInstance(new Object[]{}); } catch(InstantiationException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } catch(IllegalAccessException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } catch(InvocationTargetException e) { e.printStackTrace(); System.err.println(e.getMessage()); throw new SystemException(e); } } private final boolean useDefineColumnTypes; protected Database() { this.useDefineColumnTypes = this instanceof DatabaseColumnTypesDefinable; //System.out.println("using database "+getClass()); } private final Statement createStatement() { return new Statement(useDefineColumnTypes); } //private static int createTableTime = 0, dropTableTime = 0, checkEmptyTableTime = 0; public void createDatabase() { //final long time = System.currentTimeMillis(); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) createTable((Table)i.next()); for(Iterator i = Type.getTypes().iterator(); i.hasNext(); ) createMediaDirectories((Type)i.next()); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) createForeignKeyConstraints((Table)i.next()); //final long amount = (System.currentTimeMillis()-time); //createTableTime += amount; //System.out.println("CREATE TABLES "+amount+"ms accumulated "+createTableTime); } //private static int checkTableTime = 0; /** * Checks the database, * whether the database tables representing the types do exist. * Issues a single database statement, * that touches all tables and columns, * that would have been created by * {@link #createDatabase()}. * @throws SystemException * if something is wrong with the database. * TODO: use a more specific exception. */ public void checkDatabase() { //final long time = System.currentTimeMillis(); final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(); boolean first = true; for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Table table = (Table)i.next(); bf.append(table.protectedID); } final Long testDate = new Long(System.currentTimeMillis()); bf.append(" where "); first = true; for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(" and "); final Table table = (Table)i.next(); final Column primaryKey = table.primaryKey; bf.append(table.protectedID). append('.'). append(primaryKey.protectedID). append('='). append(Type.NOT_A_PK); for(Iterator j = table.getColumns().iterator(); j.hasNext(); ) { final Column column = (Column)j.next(); bf.append(" and "). append(table.protectedID). append('.'). append(column.protectedID). append('='); if(column instanceof IntegerColumn) bf.appendValue(column, ((IntegerColumn)column).longInsteadOfInt ? (Number)new Long(1) : new Integer(1)); else if(column instanceof DoubleColumn) bf.appendValue(column, new Double(2.2)); else if(column instanceof StringColumn) bf.appendValue(column, "z"); else if(column instanceof TimestampColumn) bf.appendValue(column, testDate); else throw new RuntimeException(column.toString()); } } try { //System.out.println("checkDatabase:"+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } //final long amount = (System.currentTimeMillis()-time); //checkTableTime += amount; //System.out.println("CHECK TABLES "+amount+"ms accumulated "+checkTableTime); } public void dropDatabase() { //final long time = System.currentTimeMillis(); { final List types = Type.getTypes(); for(ListIterator i = types.listIterator(types.size()); i.hasPrevious(); ) ((Type)i.previous()).onDropTable(); } { final List tables = Table.getTables(); // must delete in reverse order, to obey integrity constraints for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); ) dropForeignKeyConstraints((Table)i.previous()); for(ListIterator i = tables.listIterator(tables.size()); i.hasPrevious(); ) dropTable((Table)i.previous()); } //final long amount = (System.currentTimeMillis()-time); //dropTableTime += amount; //System.out.println("DROP TABLES "+amount+"ms accumulated "+dropTableTime); } public void tearDownDatabase() { System.err.println("TEAR DOWN ALL DATABASE"); for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { try { final Table table = (Table)i.next(); System.err.print("DROPPING FOREIGN KEY CONSTRAINTS "+table+"... "); dropForeignKeyConstraints(table); System.err.println("done."); } catch(SystemException e2) { System.err.println("failed:"+e2.getMessage()); } } for(Iterator i = Table.getTables().iterator(); i.hasNext(); ) { try { final Table table = (Table)i.next(); System.err.print("DROPPING TABLE "+table+" ... "); dropTable(table); System.err.println("done."); } catch(SystemException e2) { System.err.println("failed:"+e2.getMessage()); } } } public void checkEmptyTables() { //final long time = System.currentTimeMillis(); for(Iterator i = Type.getTypes().iterator(); i.hasNext(); ) { final Type type = (Type)i.next(); final int count = countTable(type); if(count>0) throw new RuntimeException("there are "+count+" items left for type "+type); } //final long amount = (System.currentTimeMillis()-time); //checkEmptyTableTime += amount; //System.out.println("CHECK EMPTY TABLES "+amount+"ms accumulated "+checkEmptyTableTime); } final IntArrayList search(final Query query) { final Table selectType = query.selectType.table; // TODO: rename to selectTable final Statement bf = createStatement(); bf.append("select "). append(selectType.protectedID). append('.'). append(selectType.primaryKey.protectedID).defineColumnInteger(). append(" from "); boolean first = true; for(Iterator i = query.fromTypes.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); bf.append(((Type)i.next()).table.protectedID); } if(query.condition!=null) { bf.append(" where "); query.condition.appendStatement(bf); } if(query.orderBy!=null) { bf.append(" order by "). append(query.orderBy); if(!query.orderAscending) bf.append(" desc"); } //System.out.println("searching "+bf.toString()); try { final QueryResultSetHandler handler = new QueryResultSetHandler(query.start, query.count); executeSQL(bf, handler); return handler.result; } catch(ConstraintViolationException e) { throw new SystemException(e); } } void load(final Row row) { final Statement bf = createStatement(); bf.append("select "); boolean first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { final Table table = type.table; final List columns = table.getColumns(); for(Iterator i = columns.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(table.protectedID). append('.'). append(column.protectedID).defineColumn(column); } } bf.append(" from "); first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(','); bf.append(type.table.protectedID); } bf.append(" where "); first = true; for(Type type = row.type; type!=null; type = type.getSupertype()) { if(first) first = false; else bf.append(" and "); final Table table = type.table; bf.append(table.protectedID). append('.'). append(table.primaryKey.protectedID). append('='). append(row.pk); } //System.out.println("loading "+bf.toString()); try { executeSQL(bf, new LoadResultSetHandler(row)); } catch(ConstraintViolationException e) { throw new SystemException(e); } } void store(final Row row) throws UniqueViolationException { store(row, row.type); } private void store(final Row row, final Type theType) // TODO: rename to type throws UniqueViolationException { final Type supertype = theType.getSupertype(); if(supertype!=null) store(row, supertype); final Table type = theType.table; // TODO: rename to table final List columns = type.getColumns(); final Statement bf = createStatement(); if(row.present) { bf.append("update "). append(type.protectedID). append(" set "); boolean first = true; for(Iterator i = columns.iterator(); i.hasNext(); ) { if(first) first = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID). append('='); final Object value = row.store(column); bf.append(column.cacheToDatabase(value)); } bf.append(" where "). append(type.primaryKey.protectedID). append('='). append(row.pk); } else { bf.append("insert into "). append(type.protectedID). append("("). append(type.primaryKey.protectedID); boolean first = true; for(Iterator i = columns.iterator(); i.hasNext(); ) { bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID); } bf.append(")values("). append(row.pk); for(Iterator i = columns.iterator(); i.hasNext(); ) { bf.append(','); final Column column = (Column)i.next(); final Object value = row.store(column); bf.append(column.cacheToDatabase(value)); } bf.append(')'); } try { //System.out.println("storing "+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(UniqueViolationException e) { throw e; } catch(ConstraintViolationException e) { throw new SystemException(e); } } void delete(final Type type, final int pk) throws IntegrityViolationException { for(Type currentType = type; currentType!=null; currentType = currentType.getSupertype()) { final Table currentTable = currentType.table; final Statement bf = createStatement(); bf.append("delete from "). append(currentTable.protectedID). append(" where "). append(currentTable.primaryKey.protectedID). append('='). append(pk); //System.out.println("deleting "+bf.toString()); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(IntegrityViolationException e) { throw e; } catch(ConstraintViolationException e) { throw new SystemException(e); } } } private static interface ResultSetHandler { public void run(ResultSet resultSet) throws SQLException; } private static final ResultSetHandler EMPTY_RESULT_SET_HANDLER = new ResultSetHandler() { public void run(ResultSet resultSet) { } }; private static class QueryResultSetHandler implements ResultSetHandler { private final int start; private final int count; private final IntArrayList result = new IntArrayList(); QueryResultSetHandler(final int start, final int count) { this.start = start; this.count = count; if(start<0) throw new RuntimeException(); } public void run(ResultSet resultSet) throws SQLException { if(start>0) { // TODO: ResultSet.relative // Would like to use // resultSet.relative(start+1); // but this throws a java.sql.SQLException: // Invalid operation for forward only resultset : relative for(int i = start; i>0; i--) resultSet.next(); } int i = (count>=0 ? count : Integer.MAX_VALUE); while(resultSet.next() && (--i)>=0) { final int pk = resultSet.getInt(1); //System.out.println("pk:"+pk); result.add(pk); } } } private static class LoadResultSetHandler implements ResultSetHandler { private final Row row; LoadResultSetHandler(final Row row) { this.row = row; } public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException("no such pk"); // TODO use some better exception int columnIndex = 1; for(Type type = row.type; type!=null; type = type.getSupertype()) { for(Iterator i = type.table.getColumns().iterator(); i.hasNext(); ) ((Column)i.next()).load(resultSet, columnIndex++, row); } return; } } private final static int convertSQLResult(final Object sqlInteger) { // IMPLEMENTATION NOTE for Oracle // Whether the returned object is an Integer or a BigDecimal, // depends on whether OracleStatement.defineColumnType is used or not, // so we support both here. if(sqlInteger instanceof BigDecimal) return ((BigDecimal)sqlInteger).intValue(); else return ((Integer)sqlInteger).intValue(); } private static class IntegerResultSetHandler implements ResultSetHandler { int result; public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); result = convertSQLResult(resultSet.getObject(1)); } } private static class NextPKResultSetHandler implements ResultSetHandler { int resultLo; int resultHi; public void run(ResultSet resultSet) throws SQLException { if(!resultSet.next()) throw new RuntimeException(); final Object oLo = resultSet.getObject(1); if(oLo==null) { resultLo = -1; resultHi = 0; } else { resultLo = convertSQLResult(oLo)-1; final Object oHi = resultSet.getObject(2); resultHi = convertSQLResult(oHi)+1; } } } //private static int timeExecuteQuery = 0; private void executeSQL(final Statement statement, final ResultSetHandler resultSetHandler) throws ConstraintViolationException { final ConnectionPool connectionPool = ConnectionPool.getInstance(); Connection connection = null; java.sql.Statement sqlStatement = null; ResultSet resultSet = null; try { connection = connectionPool.getConnection(); // TODO: use prepared statements and reuse the statement. sqlStatement = connection.createStatement(); final String sqlText = statement.getText(); if(!sqlText.startsWith("select ")) { final int rows = sqlStatement.executeUpdate(sqlText); //System.out.println("("+rows+"): "+statement.getText()); } else { //long time = System.currentTimeMillis(); if(useDefineColumnTypes) ((DatabaseColumnTypesDefinable)this).defineColumnTypes(statement.columnTypes, sqlStatement); resultSet = sqlStatement.executeQuery(sqlText); //long interval = System.currentTimeMillis() - time; //timeExecuteQuery += interval; //System.out.println("executeQuery: "+interval+"ms sum "+timeExecuteQuery+"ms"); resultSetHandler.run(resultSet); } } catch(SQLException e) { final ConstraintViolationException wrappedException = wrapException(e); if(wrappedException!=null) throw wrappedException; else throw new SystemException(e, statement.toString()); } finally { if(resultSet!=null) { try { resultSet.close(); } catch(SQLException e) { // exception is already thrown } } if(sqlStatement!=null) { try { sqlStatement.close(); } catch(SQLException e) { // exception is already thrown } } if(connection!=null) { try { connectionPool.putConnection(connection); } catch(SQLException e) { // exception is already thrown } } } } protected abstract String extractUniqueConstraintName(SQLException e); protected abstract String extractIntegrityConstraintName(SQLException e); private final ConstraintViolationException wrapException(final SQLException e) { { final String uniqueConstraintID = extractUniqueConstraintName(e); if(uniqueConstraintID!=null) { final UniqueConstraint constraint = UniqueConstraint.findByID(uniqueConstraintID, e); return new UniqueViolationException(e, null, constraint); } } { final String integrityConstraintName = extractIntegrityConstraintName(e); if(integrityConstraintName!=null) { final ItemAttribute attribute = ItemAttribute.getItemAttributeByIntegrityConstraintName(integrityConstraintName, e); return new IntegrityViolationException(e, null, attribute); } } return null; } protected static final String trimString(final String longString, final int maxLength) { if(maxLength<=0) throw new RuntimeException("maxLength must be greater zero"); if(longString.length()==0) throw new RuntimeException("longString must not be empty"); if(longString.length()<=maxLength) return longString; int longStringLength = longString.length(); final int[] trimPotential = new int[maxLength]; final ArrayList words = new ArrayList(); { final StringBuffer buf = new StringBuffer(); for(int i=0; i<longString.length(); i++) { final char c = longString.charAt(i); if((c=='_' || Character.isUpperCase(c) || Character.isDigit(c)) && buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } if(buf.length()<maxLength) buf.append(c); else longStringLength--; } if(buf.length()>0) { words.add(buf.toString()); int potential = 1; for(int j = buf.length()-1; j>=0; j--, potential++) trimPotential[j] += potential; buf.setLength(0); } } final int expectedTrimPotential = longStringLength - maxLength; //System.out.println("expected trim potential = "+expectedTrimPotential); int wordLength; int remainder = 0; for(wordLength = trimPotential.length-1; wordLength>=0; wordLength--) { //System.out.println("trim potential ["+wordLength+"] = "+trimPotential[wordLength]); remainder = trimPotential[wordLength] - expectedTrimPotential; if(remainder>=0) break; } final StringBuffer result = new StringBuffer(longStringLength); for(Iterator i = words.iterator(); i.hasNext(); ) { final String word = (String)i.next(); //System.out.println("word "+word+" remainder:"+remainder); if((word.length()>wordLength) && remainder>0) { result.append(word.substring(0, wordLength+1)); remainder--; } else if(word.length()>wordLength) result.append(word.substring(0, wordLength)); else result.append(word); } //System.out.println("---- trimName("+longString+","+maxLength+") == "+result+" --- "+words); if(result.length()!=maxLength) throw new RuntimeException(result.toString()+maxLength); return result.toString(); } String trimName(final Type type) { final String className = type.getJavaClass().getName(); final int pos = className.lastIndexOf('.'); return trimString(className.substring(pos+1), 25); } /** * Trims a name to length for being be a suitable qualifier for database entities, * such as tables, columns, indexes, constraints, partitions etc. */ String trimName(final String longName) { return trimString(longName, 25); } /** * Protects a database name from being interpreted as a SQL keyword. * This is usually done by enclosing the name with some (database specific) delimiters. * The default implementation uses double quotes as delimiter. */ protected String protectName(String name) { return '"' + name + '"'; } abstract String getIntegerType(int precision); abstract String getDoubleType(int precision); abstract String getStringType(int maxLength); abstract String getDateTimestampType(); private void createTable(final Table table) { final Statement bf = createStatement(); bf.append("create table "). append(table.protectedID). append('('); boolean firstColumn = true; for(Iterator i = table.getAllColumns().iterator(); i.hasNext(); ) { if(firstColumn) firstColumn = false; else bf.append(','); final Column column = (Column)i.next(); bf.append(column.protectedID). append(' '). append(column.databaseType); if(column.primaryKey) { bf.append(" primary key"); } else { if(column.notNull) bf.append(" not null"); } } // attribute constraints for(Iterator i = table.getColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); if(column instanceof StringColumn) { final StringColumn stringColumn = (StringColumn)column; if(stringColumn.minimumLengthID!=null) { bf.append(",constraint "). append(protectName(stringColumn.minimumLengthID)). append(" check(length("). append(column.protectedID). append(")>="). append(stringColumn.minimumLength); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } if(stringColumn.maximumLengthID!=null) { bf.append(",constraint "). append(protectName(stringColumn.maximumLengthID)). append(" check(length("). append(column.protectedID). append(")<="). append(stringColumn.maximumLength); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } } else if(column instanceof IntegerColumn) { final IntegerColumn intColumn = (IntegerColumn)column; final int[] allowedValues = intColumn.allowedValues; if(allowedValues!=null) { bf.append(",constraint "). append(protectName(intColumn.allowedValuesID)). append(" check("). append(column.protectedID). append(" in ("); for(int j = 0; j<allowedValues.length; j++) { if(j>0) bf.append(','); bf.append(allowedValues[j]); } bf.append(')'); if(!column.notNull) { bf.append(" or "). append(column.protectedID). append(" is null"); } bf.append(')'); } } } for(Iterator i = table.getUniqueConstraints().iterator(); i.hasNext(); ) { final UniqueConstraint uniqueConstraint = (UniqueConstraint)i.next(); bf.append(",constraint "). append(uniqueConstraint.getProtectedID()). append(" unique("); boolean first = true; for(Iterator j = uniqueConstraint.getUniqueAttributes().iterator(); j.hasNext(); ) { if(first) first = false; else bf.append(','); final Attribute uniqueAttribute = (Attribute)j.next(); bf.append(uniqueAttribute.getMainColumn().protectedID); } bf.append(')'); } bf.append(')'); try { //System.out.println("createTable:"+bf.toString()); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } private void createForeignKeyConstraints(final Table type) // TODO: rename to table { //System.out.println("createForeignKeyConstraints:"+bf); for(Iterator i = type.getAllColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); //System.out.println("createForeignKeyConstraints("+column+"):"+bf); if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; final Statement bf = createStatement(); bf.append("alter table "). append(type.protectedID). append(" add constraint "). append(Database.theInstance.protectName(itemColumn.integrityConstraintName)). append(" foreign key ("). append(column.protectedID). append(") references "). append(itemColumn.getForeignTableNameProtected()); try { //System.out.println("createForeignKeyConstraints:"+bf); executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } } } private void createMediaDirectories(final Type type) { File typeDirectory = null; for(Iterator i = type.getAttributes().iterator(); i.hasNext(); ) { final Attribute attribute = (Attribute)i.next(); if(attribute instanceof MediaAttribute) { if(typeDirectory==null) { final File directory = Properties.getInstance().getMediaDirectory(); typeDirectory = new File(directory, type.id); typeDirectory.mkdir(); } final File attributeDirectory = new File(typeDirectory, attribute.getName()); attributeDirectory.mkdir(); } } } private void dropTable(final Table type) // TODO: rename to table { final Statement bf = createStatement(); bf.append("drop table "). append(type.protectedID); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } private int countTable(final Type type) { final Statement bf = createStatement(); bf.append("select count(*) from ").defineColumnInteger(). append(type.table.protectedID); try { final IntegerResultSetHandler handler = new IntegerResultSetHandler(); executeSQL(bf, handler); return handler.result; } catch(ConstraintViolationException e) { throw new SystemException(e); } } private void dropForeignKeyConstraints(final Table type) // TODO: rename to table { for(Iterator i = type.getColumns().iterator(); i.hasNext(); ) { final Column column = (Column)i.next(); //System.out.println("dropForeignKeyConstraints("+column+")"); if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; final Statement bf = createStatement(); boolean hasOne = false; bf.append("alter table "). append(type.protectedID). append(" drop constraint "). append(Database.theInstance.protectName(itemColumn.integrityConstraintName)); //System.out.println("dropForeignKeyConstraints:"+bf); try { executeSQL(bf, EMPTY_RESULT_SET_HANDLER); } catch(ConstraintViolationException e) { throw new SystemException(e); } } } } int[] getNextPK(final Type type) { final Statement bf = createStatement(); final Table table = type.table; final String primaryKeyProtectedID = table.primaryKey.protectedID; bf.append("select min("). append(primaryKeyProtectedID).defineColumnInteger(). append("),max("). append(primaryKeyProtectedID).defineColumnInteger(). append(") from "). append(table.protectedID); try { final NextPKResultSetHandler handler = new NextPKResultSetHandler(); executeSQL(bf, handler); //System.err.println("select max("+type.primaryKey.trimmedName+") from "+type.trimmedName+" : "+handler.result); return new int[] {handler.resultLo, handler.resultHi}; } catch(ConstraintViolationException e) { throw new SystemException(e); } } }
rename selectType to selectTable git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@1091 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/src/com/exedio/cope/lib/Database.java
rename selectType to selectTable
Java
apache-2.0
68014bf3b3a0027b5fde22c7d2a194af60dd01fa
0
ImmobilienScout24/deadcode4j
package de.is24.deadcode4j.analyzer.webxml; import de.is24.deadcode4j.AnalysisContext; import de.is24.deadcode4j.analyzer.XmlAnalyzer; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; import javax.annotation.Nonnull; import java.util.*; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Iterables.elementsEqual; import static java.util.Arrays.asList; /** * Parses {@code web.xml} and translates XML events into {@code web.xml} * specific events that can be consumed by a {@link WebXmlHandler}. It only * creates events for {@code web.xml} nodes that are needed by existing * {@link de.is24.deadcode4j.Analyzer}s. Please add further events if needed. * * @since 2.1.0 */ public abstract class BaseWebXmlAnalyzer extends XmlAnalyzer { protected BaseWebXmlAnalyzer() { super("web.xml"); } /** * This method is called to provide a <code>WebXmlHandler</code> for each file being processed. */ @Nonnull protected abstract WebXmlHandler createWebXmlHandlerFor(@Nonnull AnalysisContext analysisContext); @Nonnull @Override protected DefaultHandler createHandlerFor(@Nonnull AnalysisContext analysisContext) { WebXmlHandler webXmlHandler = createWebXmlHandlerFor(analysisContext); return new WebXmlAdapter(webXmlHandler); } // Translates XML events into web.xml events that can be consumed by a WebXmlHandler private static class WebXmlAdapter extends DefaultHandler { @SuppressWarnings("unchecked") static final Collection<List<String>> NODES_WITH_TEXT = asList( asList("web-app", "context-param", "param-name"), asList("web-app", "context-param", "param-value"), asList("web-app", "filter", "filter-class"), asList("web-app", "filter", "init-param", "param-name"), asList("web-app", "filter", "init-param", "param-value"), asList("web-app", "listener", "listener-class"), asList("web-app", "servlet", "servlet-class"), asList("web-app", "servlet", "init-param", "param-name"), asList("web-app", "servlet", "init-param", "param-value")); static final Collection<String> CONTEXT_PARAM_PATH = asList("web-app", "context-param"); static final Collection<String> FILTER_PATH = asList("web-app", "filter"); static final Collection<String> FILTER_INIT_PARAM_PATH = asList("web-app", "filter", "init-param"); static final Collection<String> LISTENER_PATH = asList("web-app", "listener"); static final Collection<String> SERVLET_INIT_PARAM_PATH = asList("web-app", "servlet", "init-param"); static final Collection<String> SERVLET_PATH = asList("web-app", "servlet"); final Deque<String> deque = new ArrayDeque<String>(); final List<Param> initParams = new ArrayList<Param>(); final Map<String, String> texts = new HashMap<String, String>(); StringBuilder buffer; final WebXmlHandler webXmlHandler; WebXmlAdapter(WebXmlHandler webXmlHandler) { this.webXmlHandler = webXmlHandler; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { deque.add(localName); if (isNodeWithText()) { buffer = new StringBuilder(128); } } @Override public void characters(char[] ch, int start, int length) { if (isNodeWithText()) { buffer.append(new String(ch, start, length).trim()); } } @Override public void endElement(String uri, String localName, String qName) { if (isNodeWithText()) { storeCharacters(localName); } else if (matchesPath(CONTEXT_PARAM_PATH)) { reportContextParam(); } else if (matchesPath(FILTER_INIT_PARAM_PATH)) { storeInitParam(); } else if (matchesPath(FILTER_PATH)) { reportFilter(); } else if (matchesPath(LISTENER_PATH)) { reportListener(); } else if (matchesPath(SERVLET_INIT_PARAM_PATH)) { storeInitParam(); } else if (matchesPath(SERVLET_PATH)) { reportServlet(); } deque.removeLast(); } boolean isNodeWithText() { for (List<String> candidate : NODES_WITH_TEXT) { if (matchesPath(candidate)) { return true; } } return false; } void reportContextParam() { webXmlHandler.contextParam(createParam()); } void storeInitParam() { initParams.add(createParam()); } Param createParam() { return new Param(getText("param-name"), getText("param-value")); } void reportFilter() { webXmlHandler.filter( getText("filter-class"), new ArrayList<Param>(initParams)); initParams.clear(); } void reportListener() { webXmlHandler.listener(getText("listener-class")); } void reportServlet() { webXmlHandler.servlet( getText("servlet-class"), new ArrayList<Param>(initParams)); initParams.clear(); } boolean matchesPath(Collection<String> path) { return path.size() == deque.size() && elementsEqual(path, deque); } void storeCharacters(String localName) { texts.put(localName, buffer.toString()); } String getText(String localName) { String text = texts.remove(localName); return nullToEmpty(text); } } }
src/main/java/de/is24/deadcode4j/analyzer/webxml/BaseWebXmlAnalyzer.java
package de.is24.deadcode4j.analyzer.webxml; import de.is24.deadcode4j.AnalysisContext; import de.is24.deadcode4j.analyzer.XmlAnalyzer; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; import javax.annotation.Nonnull; import java.util.*; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Iterables.elementsEqual; import static java.util.Arrays.asList; /** * Parses {@code web.xml} and translates XML events into {@code web.xml} * specific events that can be consumed by a {@link WebXmlHandler}. It only * creates events for {@code web.xml} nodes that are needed by existing * {@link de.is24.deadcode4j.Analyzer}s. Please add further events if needed. * * @since 2.1.0 */ public abstract class BaseWebXmlAnalyzer extends XmlAnalyzer { protected BaseWebXmlAnalyzer() { super("web.xml"); } /** * This method is called to provide a <code>WebXmlHandler</code> for each file being processed. */ @Nonnull protected abstract WebXmlHandler createWebXmlHandlerFor(@Nonnull AnalysisContext analysisContext); @Nonnull @Override protected DefaultHandler createHandlerFor(@Nonnull AnalysisContext analysisContext) { WebXmlHandler webXmlHandler = createWebXmlHandlerFor(analysisContext); return new WebXmlAdapter(webXmlHandler); } // Translates XML events into web.xml events that can be consumed by a WebXmlHandler private static class WebXmlAdapter extends DefaultHandler { static final Collection<List<String>> NODES_WITH_TEXT = asList( asList("web-app", "context-param", "param-name"), asList("web-app", "context-param", "param-value"), asList("web-app", "filter", "filter-class"), asList("web-app", "filter", "init-param", "param-name"), asList("web-app", "filter", "init-param", "param-value"), asList("web-app", "listener", "listener-class"), asList("web-app", "servlet", "servlet-class"), asList("web-app", "servlet", "init-param", "param-name"), asList("web-app", "servlet", "init-param", "param-value")); static final Collection<String> CONTEXT_PARAM_PATH = asList("web-app", "context-param"); static final Collection<String> FILTER_PATH = asList("web-app", "filter"); static final Collection<String> FILTER_INIT_PARAM_PATH = asList("web-app", "filter", "init-param"); static final Collection<String> LISTENER_PATH = asList("web-app", "listener"); static final Collection<String> SERVLET_INIT_PARAM_PATH = asList("web-app", "servlet", "init-param"); static final Collection<String> SERVLET_PATH = asList("web-app", "servlet"); final Deque<String> deque = new ArrayDeque<String>(); final List<Param> initParams = new ArrayList<Param>(); final Map<String, String> texts = new HashMap<String, String>(); StringBuilder buffer; final WebXmlHandler webXmlHandler; WebXmlAdapter(WebXmlHandler webXmlHandler) { this.webXmlHandler = webXmlHandler; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { deque.add(localName); if (isNodeWithText()) { buffer = new StringBuilder(128); } } @Override public void characters(char[] ch, int start, int length) { if (isNodeWithText()) { buffer.append(new String(ch, start, length).trim()); } } @Override public void endElement(String uri, String localName, String qName) { if (isNodeWithText()) { storeCharacters(localName); } else if (matchesPath(CONTEXT_PARAM_PATH)) { reportContextParam(); } else if (matchesPath(FILTER_INIT_PARAM_PATH)) { storeInitParam(); } else if (matchesPath(FILTER_PATH)) { reportFilter(); } else if (matchesPath(LISTENER_PATH)) { reportListener(); } else if (matchesPath(SERVLET_INIT_PARAM_PATH)) { storeInitParam(); } else if (matchesPath(SERVLET_PATH)) { reportServlet(); } deque.removeLast(); } boolean isNodeWithText() { for (List<String> candidate : NODES_WITH_TEXT) { if (matchesPath(candidate)) { return true; } } return false; } void reportContextParam() { webXmlHandler.contextParam(createParam()); } void storeInitParam() { initParams.add(createParam()); } Param createParam() { return new Param(getText("param-name"), getText("param-value")); } void reportFilter() { webXmlHandler.filter( getText("filter-class"), new ArrayList<Param>(initParams)); initParams.clear(); } void reportListener() { webXmlHandler.listener(getText("listener-class")); } void reportServlet() { webXmlHandler.servlet( getText("servlet-class"), new ArrayList<Param>(initParams)); initParams.clear(); } boolean matchesPath(Collection<String> path) { return path.size() == deque.size() && elementsEqual(path, deque); } void storeCharacters(String localName) { texts.put(localName, buffer.toString()); } String getText(String localName) { String text = texts.remove(localName); return nullToEmpty(text); } } }
suppress unchecked warning
src/main/java/de/is24/deadcode4j/analyzer/webxml/BaseWebXmlAnalyzer.java
suppress unchecked warning
Java
apache-2.0
24e296b86971d8e075cba241bbb44fe6f76b472a
0
sdnwiselab/onos,mengmoya/onos,opennetworkinglab/onos,osinstom/onos,LorenzReinhart/ONOSnew,osinstom/onos,maheshraju-Huawei/actn,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,VinodKumarS-Huawei/ietf96yang,sonu283304/onos,maheshraju-Huawei/actn,y-higuchi/onos,kuujo/onos,sdnwiselab/onos,y-higuchi/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,kuujo/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,VinodKumarS-Huawei/ietf96yang,Shashikanth-Huawei/bmp,opennetworkinglab/onos,sdnwiselab/onos,Shashikanth-Huawei/bmp,lsinfo3/onos,kuujo/onos,kuujo/onos,oplinkoms/onos,mengmoya/onos,lsinfo3/onos,kuujo/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,donNewtonAlpha/onos,donNewtonAlpha/onos,sdnwiselab/onos,mengmoya/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,sonu283304/onos,donNewtonAlpha/onos,oplinkoms/onos,gkatsikas/onos,donNewtonAlpha/onos,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,mengmoya/onos,y-higuchi/onos,kuujo/onos,osinstom/onos,lsinfo3/onos,Shashikanth-Huawei/bmp,sonu283304/onos,sdnwiselab/onos,osinstom/onos,sonu283304/onos,LorenzReinhart/ONOSnew,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,osinstom/onos,kuujo/onos,opennetworkinglab/onos,y-higuchi/onos,gkatsikas/onos,sdnwiselab/onos,y-higuchi/onos,donNewtonAlpha/onos,maheshraju-Huawei/actn,mengmoya/onos,lsinfo3/onos
/* * Copyright 2014 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.flow; import com.google.common.annotations.Beta; import org.onosproject.core.ApplicationId; import org.onosproject.core.DefaultGroupId; import org.onosproject.core.GroupId; import org.onosproject.net.DeviceId; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class DefaultFlowRule implements FlowRule { private final DeviceId deviceId; private final int priority; private final TrafficSelector selector; private final TrafficTreatment treatment; private final long created; private final FlowId id; private final Short appId; private final int timeout; private final boolean permanent; private final GroupId groupId; private final Integer tableId; private final FlowRuleExtPayLoad payLoad; public DefaultFlowRule(FlowRule rule) { this.deviceId = rule.deviceId(); this.priority = rule.priority(); this.selector = rule.selector(); this.treatment = rule.treatment(); this.appId = rule.appId(); this.groupId = rule.groupId(); this.id = rule.id(); this.timeout = rule.timeout(); this.permanent = rule.isPermanent(); this.created = System.currentTimeMillis(); this.tableId = rule.tableId(); this.payLoad = rule.payLoad(); } private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, Integer priority, FlowId flowId, Boolean permanent, Integer timeout, Integer tableId) { this.deviceId = deviceId; this.selector = selector; this.treatment = treatment; this.priority = priority; this.appId = (short) (flowId.value() >>> 48); this.id = flowId; this.permanent = permanent; this.timeout = timeout; this.tableId = tableId; this.created = System.currentTimeMillis(); //FIXME: fields below will be removed. this.groupId = new DefaultGroupId(0); this.payLoad = null; } /** * Support for the third party flow rule. Creates a flow rule of flow table. * * @param deviceId the identity of the device where this rule applies * @param selector the traffic selector that identifies what traffic this * rule * @param treatment the traffic treatment that applies to selected traffic * @param priority the flow rule priority given in natural order * @param appId the application id of this flow * @param timeout the timeout for this flow requested by an application * @param permanent whether the flow is permanent i.e. does not time out * @param payLoad 3rd-party origin private flow */ public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, int priority, ApplicationId appId, int timeout, boolean permanent, FlowRuleExtPayLoad payLoad) { if (priority < FlowRule.MIN_PRIORITY) { throw new IllegalArgumentException("Priority cannot be less than " + MIN_PRIORITY); } this.deviceId = deviceId; this.priority = priority; this.selector = selector; this.treatment = treatment; this.appId = appId.id(); this.groupId = new DefaultGroupId(0); this.timeout = timeout; this.permanent = permanent; this.tableId = 0; this.created = System.currentTimeMillis(); this.payLoad = payLoad; /* * id consists of the following. | appId (16 bits) | groupId (16 bits) | * flowId (32 bits) | */ this.id = FlowId.valueOf((((long) this.appId) << 48) | (((long) this.groupId.id()) << 32) | (this.hash() & 0xffffffffL)); } /** * Support for the third party flow rule. Creates a flow rule of group * table. * * @param deviceId the identity of the device where this rule applies * @param selector the traffic selector that identifies what traffic this * rule * @param treatment the traffic treatment that applies to selected traffic * @param priority the flow rule priority given in natural order * @param appId the application id of this flow * @param groupId the group id of this flow * @param timeout the timeout for this flow requested by an application * @param permanent whether the flow is permanent i.e. does not time out * @param payLoad 3rd-party origin private flow * */ public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, int priority, ApplicationId appId, GroupId groupId, int timeout, boolean permanent, FlowRuleExtPayLoad payLoad) { if (priority < FlowRule.MIN_PRIORITY) { throw new IllegalArgumentException("Priority cannot be less than " + MIN_PRIORITY); } this.deviceId = deviceId; this.priority = priority; this.selector = selector; this.treatment = treatment; this.appId = appId.id(); this.groupId = groupId; this.timeout = timeout; this.permanent = permanent; this.created = System.currentTimeMillis(); this.tableId = 0; this.payLoad = payLoad; /* * id consists of the following. | appId (16 bits) | groupId (16 bits) | * flowId (32 bits) | */ this.id = FlowId.valueOf((((long) this.appId) << 48) | (((long) this.groupId.id()) << 32) | (this.hash() & 0xffffffffL)); } @Override public FlowId id() { return id; } @Override public short appId() { return appId; } @Override public GroupId groupId() { return groupId; } @Override public int priority() { return priority; } @Override public DeviceId deviceId() { return deviceId; } @Override public TrafficSelector selector() { return selector; } @Override public TrafficTreatment treatment() { return treatment; } @Override /* * The priority and statistics can change on a given treatment and selector * * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public int hashCode() { return Objects.hash(deviceId, selector, tableId, payLoad); } //FIXME do we need this method in addition to hashCode()? private int hash() { return Objects.hash(deviceId, selector, tableId, payLoad); } @Override /* * The priority and statistics can change on a given treatment and selector * * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultFlowRule) { DefaultFlowRule that = (DefaultFlowRule) obj; return Objects.equals(deviceId, that.deviceId) && Objects.equals(priority, that.priority) && Objects.equals(selector, that.selector) && Objects.equals(tableId, that.tableId) && Objects.equals(payLoad, that.payLoad); } return false; } @Override public boolean exactMatch(FlowRule rule) { return this.equals(rule) && Objects.equals(this.id, rule.id()) && Objects.equals(this.treatment, rule.treatment()); } @Override public String toString() { return toStringHelper(this) .add("id", Long.toHexString(id.value())) .add("deviceId", deviceId) .add("priority", priority) .add("selector", selector.criteria()) .add("treatment", treatment == null ? "N/A" : treatment.allInstructions()) .add("tableId", tableId) .add("created", created) .add("payLoad", payLoad) .toString(); } @Override public int timeout() { return timeout; } @Override public boolean isPermanent() { return permanent; } @Override public int tableId() { return tableId; } @Beta public long created() { return created; } public static Builder builder() { return new Builder(); } public static final class Builder implements FlowRule.Builder { private FlowId flowId; private ApplicationId appId; private Integer priority; private DeviceId deviceId; private Integer tableId = 0; private TrafficSelector selector = DefaultTrafficSelector.builder().build(); private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build(); private Integer timeout; private Boolean permanent; @Override public FlowRule.Builder withCookie(long cookie) { this.flowId = FlowId.valueOf(cookie); return this; } @Override public FlowRule.Builder fromApp(ApplicationId appId) { this.appId = appId; return this; } @Override public FlowRule.Builder withPriority(int priority) { this.priority = priority; return this; } @Override public FlowRule.Builder forDevice(DeviceId deviceId) { this.deviceId = deviceId; return this; } @Override public FlowRule.Builder forTable(int tableId) { this.tableId = tableId; return this; } @Override public FlowRule.Builder withSelector(TrafficSelector selector) { this.selector = selector; return this; } @Override public FlowRule.Builder withTreatment(TrafficTreatment treatment) { this.treatment = checkNotNull(treatment); return this; } @Override public FlowRule.Builder makePermanent() { this.timeout = 0; this.permanent = true; return this; } @Override public FlowRule.Builder makeTemporary(int timeout) { this.permanent = false; this.timeout = timeout; return this; } @Override public FlowRule build() { checkArgument(flowId != null || appId != null, "Either an application" + " id or a cookie must be supplied"); checkNotNull(selector, "Traffic selector cannot be null"); checkArgument(timeout != null || permanent != null, "Must either have " + "a timeout or be permanent"); checkNotNull(deviceId, "Must refer to a device"); checkNotNull(priority, "Priority cannot be null"); checkArgument(priority >= MIN_PRIORITY, "Priority cannot be less than " + MIN_PRIORITY); // Computing a flow ID based on appId takes precedence over setting // the flow ID directly if (appId != null) { flowId = computeFlowId(appId); } return new DefaultFlowRule(deviceId, selector, treatment, priority, flowId, permanent, timeout, tableId); } private FlowId computeFlowId(ApplicationId appId) { return FlowId.valueOf((((long) appId.id()) << 48) | (hash() & 0xffffffffL)); } private int hash() { return Objects.hash(deviceId, priority, selector, tableId); } } @Override public FlowRuleExtPayLoad payLoad() { return payLoad; } }
core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java
/* * Copyright 2014 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.net.flow; import com.google.common.annotations.Beta; import org.onosproject.core.ApplicationId; import org.onosproject.core.DefaultGroupId; import org.onosproject.core.GroupId; import org.onosproject.net.DeviceId; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class DefaultFlowRule implements FlowRule { private final DeviceId deviceId; private final int priority; private final TrafficSelector selector; private final TrafficTreatment treatment; private final long created; private final FlowId id; private final Short appId; private final int timeout; private final boolean permanent; private final GroupId groupId; private final Integer tableId; private final FlowRuleExtPayLoad payLoad; public DefaultFlowRule(FlowRule rule) { this.deviceId = rule.deviceId(); this.priority = rule.priority(); this.selector = rule.selector(); this.treatment = rule.treatment(); this.appId = rule.appId(); this.groupId = rule.groupId(); this.id = rule.id(); this.timeout = rule.timeout(); this.permanent = rule.isPermanent(); this.created = System.currentTimeMillis(); this.tableId = rule.tableId(); this.payLoad = rule.payLoad(); } private DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, Integer priority, FlowId flowId, Boolean permanent, Integer timeout, Integer tableId) { this.deviceId = deviceId; this.selector = selector; this.treatment = treatment; this.priority = priority; this.appId = (short) (flowId.value() >>> 48); this.id = flowId; this.permanent = permanent; this.timeout = timeout; this.tableId = tableId; this.created = System.currentTimeMillis(); //FIXME: fields below will be removed. this.groupId = new DefaultGroupId(0); this.payLoad = null; } /** * Support for the third party flow rule. Creates a flow rule of flow table. * * @param deviceId the identity of the device where this rule applies * @param selector the traffic selector that identifies what traffic this * rule * @param treatment the traffic treatment that applies to selected traffic * @param priority the flow rule priority given in natural order * @param appId the application id of this flow * @param timeout the timeout for this flow requested by an application * @param permanent whether the flow is permanent i.e. does not time out * @param payLoad 3rd-party origin private flow */ public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, int priority, ApplicationId appId, int timeout, boolean permanent, FlowRuleExtPayLoad payLoad) { if (priority < FlowRule.MIN_PRIORITY) { throw new IllegalArgumentException("Priority cannot be less than " + MIN_PRIORITY); } this.deviceId = deviceId; this.priority = priority; this.selector = selector; this.treatment = treatment; this.appId = appId.id(); this.groupId = new DefaultGroupId(0); this.timeout = timeout; this.permanent = permanent; this.tableId = 0; this.created = System.currentTimeMillis(); this.payLoad = payLoad; /* * id consists of the following. | appId (16 bits) | groupId (16 bits) | * flowId (32 bits) | */ this.id = FlowId.valueOf((((long) this.appId) << 48) | (((long) this.groupId.id()) << 32) | (this.hash() & 0xffffffffL)); } /** * Support for the third party flow rule. Creates a flow rule of group * table. * * @param deviceId the identity of the device where this rule applies * @param selector the traffic selector that identifies what traffic this * rule * @param treatment the traffic treatment that applies to selected traffic * @param priority the flow rule priority given in natural order * @param appId the application id of this flow * @param groupId the group id of this flow * @param timeout the timeout for this flow requested by an application * @param permanent whether the flow is permanent i.e. does not time out * @param payLoad 3rd-party origin private flow * */ public DefaultFlowRule(DeviceId deviceId, TrafficSelector selector, TrafficTreatment treatment, int priority, ApplicationId appId, GroupId groupId, int timeout, boolean permanent, FlowRuleExtPayLoad payLoad) { if (priority < FlowRule.MIN_PRIORITY) { throw new IllegalArgumentException("Priority cannot be less than " + MIN_PRIORITY); } this.deviceId = deviceId; this.priority = priority; this.selector = selector; this.treatment = treatment; this.appId = appId.id(); this.groupId = groupId; this.timeout = timeout; this.permanent = permanent; this.created = System.currentTimeMillis(); this.tableId = 0; this.payLoad = payLoad; /* * id consists of the following. | appId (16 bits) | groupId (16 bits) | * flowId (32 bits) | */ this.id = FlowId.valueOf((((long) this.appId) << 48) | (((long) this.groupId.id()) << 32) | (this.hash() & 0xffffffffL)); } @Override public FlowId id() { return id; } @Override public short appId() { return appId; } @Override public GroupId groupId() { return groupId; } @Override public int priority() { return priority; } @Override public DeviceId deviceId() { return deviceId; } @Override public TrafficSelector selector() { return selector; } @Override public TrafficTreatment treatment() { return treatment; } @Override /* * The priority and statistics can change on a given treatment and selector * * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public int hashCode() { return Objects.hash(deviceId, selector, tableId, payLoad); } //FIXME do we need this method in addition to hashCode()? private int hash() { return Objects.hash(deviceId, selector, tableId, payLoad); } @Override /* * The priority and statistics can change on a given treatment and selector * * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultFlowRule) { DefaultFlowRule that = (DefaultFlowRule) obj; return Objects.equals(deviceId, that.deviceId) && Objects.equals(priority, that.priority) && Objects.equals(selector, that.selector) && Objects.equals(tableId, that.tableId) && Objects.equals(payLoad, that.payLoad); } return false; } @Override public boolean exactMatch(FlowRule rule) { return this.equals(rule) && Objects.equals(this.id, rule.id()) && Objects.equals(this.treatment, rule.treatment()); } @Override public String toString() { return toStringHelper(this) .add("id", Long.toHexString(id.value())) .add("deviceId", deviceId) .add("priority", priority) .add("selector", selector.criteria()) .add("treatment", treatment == null ? "N/A" : treatment.allInstructions()) .add("tableId", tableId) .add("created", created) .add("payLoad", payLoad) .toString(); } @Override public int timeout() { return timeout; } @Override public boolean isPermanent() { return permanent; } @Override public int tableId() { return tableId; } @Beta public long created() { return created; } public static Builder builder() { return new Builder(); } public static final class Builder implements FlowRule.Builder { private FlowId flowId; private ApplicationId appId; private Integer priority; private DeviceId deviceId; private Integer tableId = 0; private TrafficSelector selector = DefaultTrafficSelector.builder().build(); private TrafficTreatment treatment = DefaultTrafficTreatment.builder().build(); private Integer timeout; private Boolean permanent; @Override public FlowRule.Builder withCookie(long cookie) { this.flowId = FlowId.valueOf(cookie); return this; } @Override public FlowRule.Builder fromApp(ApplicationId appId) { this.appId = appId; return this; } @Override public FlowRule.Builder withPriority(int priority) { this.priority = priority; return this; } @Override public FlowRule.Builder forDevice(DeviceId deviceId) { this.deviceId = deviceId; return this; } @Override public FlowRule.Builder forTable(int tableId) { this.tableId = tableId; return this; } @Override public FlowRule.Builder withSelector(TrafficSelector selector) { this.selector = selector; return this; } @Override public FlowRule.Builder withTreatment(TrafficTreatment treatment) { this.treatment = treatment; return this; } @Override public FlowRule.Builder makePermanent() { this.timeout = 0; this.permanent = true; return this; } @Override public FlowRule.Builder makeTemporary(int timeout) { this.permanent = false; this.timeout = timeout; return this; } @Override public FlowRule build() { checkArgument(flowId != null || appId != null, "Either an application" + " id or a cookie must be supplied"); checkNotNull(selector, "Traffic selector cannot be null"); checkArgument(timeout != null || permanent != null, "Must either have " + "a timeout or be permanent"); checkNotNull(deviceId, "Must refer to a device"); checkNotNull(priority, "Priority cannot be null"); checkArgument(priority >= MIN_PRIORITY, "Priority cannot be less than " + MIN_PRIORITY); // Computing a flow ID based on appId takes precedence over setting // the flow ID directly if (appId != null) { flowId = computeFlowId(appId); } return new DefaultFlowRule(deviceId, selector, treatment, priority, flowId, permanent, timeout, tableId); } private FlowId computeFlowId(ApplicationId appId) { return FlowId.valueOf((((long) appId.id()) << 48) | (hash() & 0xffffffffL)); } private int hash() { return Objects.hash(deviceId, priority, selector, tableId); } } @Override public FlowRuleExtPayLoad payLoad() { return payLoad; } }
Prevent null treatments Change-Id: Icd40ab7f986f9738d0445428cd1f0c9053ed4e88
core/api/src/main/java/org/onosproject/net/flow/DefaultFlowRule.java
Prevent null treatments
Java
apache-2.0
11e5c67356852b144e67d701eeed4f950cc8cc0a
0
google/ExoPlayer,google/ExoPlayer,androidx/media,google/ExoPlayer,androidx/media,androidx/media
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.media3.exoplayer; import static androidx.media3.common.C.TRACK_TYPE_AUDIO; import static androidx.media3.common.C.TRACK_TYPE_CAMERA_MOTION; import static androidx.media3.common.C.TRACK_TYPE_VIDEO; import static androidx.media3.common.Player.COMMAND_ADJUST_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_CHANGE_MEDIA_ITEMS; import static androidx.media3.common.Player.COMMAND_GET_AUDIO_ATTRIBUTES; import static androidx.media3.common.Player.COMMAND_GET_CURRENT_MEDIA_ITEM; import static androidx.media3.common.Player.COMMAND_GET_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_GET_MEDIA_ITEMS_METADATA; import static androidx.media3.common.Player.COMMAND_GET_TEXT; import static androidx.media3.common.Player.COMMAND_GET_TIMELINE; import static androidx.media3.common.Player.COMMAND_GET_TRACK_INFOS; import static androidx.media3.common.Player.COMMAND_GET_VOLUME; import static androidx.media3.common.Player.COMMAND_PLAY_PAUSE; import static androidx.media3.common.Player.COMMAND_PREPARE; import static androidx.media3.common.Player.COMMAND_SEEK_TO_DEFAULT_POSITION; import static androidx.media3.common.Player.COMMAND_SEEK_TO_MEDIA_ITEM; import static androidx.media3.common.Player.COMMAND_SET_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_SET_MEDIA_ITEMS_METADATA; import static androidx.media3.common.Player.COMMAND_SET_REPEAT_MODE; import static androidx.media3.common.Player.COMMAND_SET_SHUFFLE_MODE; import static androidx.media3.common.Player.COMMAND_SET_SPEED_AND_PITCH; import static androidx.media3.common.Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS; import static androidx.media3.common.Player.COMMAND_SET_VIDEO_SURFACE; import static androidx.media3.common.Player.COMMAND_SET_VOLUME; import static androidx.media3.common.Player.COMMAND_STOP; import static androidx.media3.common.Player.DISCONTINUITY_REASON_AUTO_TRANSITION; import static androidx.media3.common.Player.DISCONTINUITY_REASON_INTERNAL; import static androidx.media3.common.Player.DISCONTINUITY_REASON_REMOVE; import static androidx.media3.common.Player.DISCONTINUITY_REASON_SEEK; import static androidx.media3.common.Player.EVENT_MEDIA_METADATA_CHANGED; import static androidx.media3.common.Player.EVENT_PLAYLIST_METADATA_CHANGED; import static androidx.media3.common.Player.EVENT_TRACK_SELECTION_PARAMETERS_CHANGED; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_AUTO; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_SEEK; import static androidx.media3.common.Player.PLAYBACK_SUPPRESSION_REASON_NONE; import static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS; import static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST; import static androidx.media3.common.Player.STATE_BUFFERING; import static androidx.media3.common.Player.STATE_ENDED; import static androidx.media3.common.Player.STATE_IDLE; import static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED; import static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_SOURCE_UPDATE; import static androidx.media3.common.util.Assertions.checkNotNull; import static androidx.media3.common.util.Assertions.checkState; import static androidx.media3.common.util.Util.castNonNull; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_ATTRIBUTES; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_SESSION_ID; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUX_EFFECT_INFO; import static androidx.media3.exoplayer.Renderer.MSG_SET_CAMERA_MOTION_LISTENER; import static androidx.media3.exoplayer.Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY; import static androidx.media3.exoplayer.Renderer.MSG_SET_SCALING_MODE; import static androidx.media3.exoplayer.Renderer.MSG_SET_SKIP_SILENCE_ENABLED; import static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER; import static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_OUTPUT; import static androidx.media3.exoplayer.Renderer.MSG_SET_VOLUME; import static java.lang.Math.max; import static java.lang.Math.min; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.media.AudioFormat; import android.media.AudioTrack; import android.media.MediaFormat; import android.media.metrics.LogSessionId; import android.os.Handler; import android.os.Looper; import android.util.Pair; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import androidx.annotation.DoNotInline; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.media3.common.AudioAttributes; import androidx.media3.common.AuxEffectInfo; import androidx.media3.common.C; import androidx.media3.common.DeviceInfo; import androidx.media3.common.Format; import androidx.media3.common.IllegalSeekPositionException; import androidx.media3.common.MediaItem; import androidx.media3.common.MediaLibraryInfo; import androidx.media3.common.MediaMetadata; import androidx.media3.common.Metadata; import androidx.media3.common.PlaybackException; import androidx.media3.common.PlaybackParameters; import androidx.media3.common.Player; import androidx.media3.common.Player.Commands; import androidx.media3.common.Player.DiscontinuityReason; import androidx.media3.common.Player.Events; import androidx.media3.common.Player.Listener; import androidx.media3.common.Player.PlayWhenReadyChangeReason; import androidx.media3.common.Player.PlaybackSuppressionReason; import androidx.media3.common.Player.PositionInfo; import androidx.media3.common.Player.RepeatMode; import androidx.media3.common.Player.State; import androidx.media3.common.Player.TimelineChangeReason; import androidx.media3.common.PriorityTaskManager; import androidx.media3.common.Timeline; import androidx.media3.common.TrackGroup; import androidx.media3.common.TrackGroupArray; import androidx.media3.common.TrackSelectionArray; import androidx.media3.common.TrackSelectionParameters; import androidx.media3.common.TracksInfo; import androidx.media3.common.VideoSize; import androidx.media3.common.text.Cue; import androidx.media3.common.util.Assertions; import androidx.media3.common.util.Clock; import androidx.media3.common.util.ConditionVariable; import androidx.media3.common.util.HandlerWrapper; import androidx.media3.common.util.ListenerSet; import androidx.media3.common.util.Log; import androidx.media3.common.util.Util; import androidx.media3.exoplayer.ExoPlayer.AudioOffloadListener; import androidx.media3.exoplayer.PlayerMessage.Target; import androidx.media3.exoplayer.Renderer.MessageType; import androidx.media3.exoplayer.analytics.AnalyticsCollector; import androidx.media3.exoplayer.analytics.AnalyticsListener; import androidx.media3.exoplayer.analytics.PlayerId; import androidx.media3.exoplayer.audio.AudioRendererEventListener; import androidx.media3.exoplayer.metadata.MetadataOutput; import androidx.media3.exoplayer.source.MediaSource; import androidx.media3.exoplayer.source.MediaSource.MediaPeriodId; import androidx.media3.exoplayer.source.ShuffleOrder; import androidx.media3.exoplayer.text.TextOutput; import androidx.media3.exoplayer.trackselection.ExoTrackSelection; import androidx.media3.exoplayer.trackselection.TrackSelector; import androidx.media3.exoplayer.trackselection.TrackSelectorResult; import androidx.media3.exoplayer.upstream.BandwidthMeter; import androidx.media3.exoplayer.video.VideoDecoderOutputBufferRenderer; import androidx.media3.exoplayer.video.VideoFrameMetadataListener; import androidx.media3.exoplayer.video.VideoRendererEventListener; import androidx.media3.exoplayer.video.spherical.CameraMotionListener; import androidx.media3.exoplayer.video.spherical.SphericalGLSurfaceView; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeoutException; /** A helper class for the {@link SimpleExoPlayer} implementation of {@link ExoPlayer}. */ /* package */ final class ExoPlayerImpl { static { MediaLibraryInfo.registerModule("media3.exoplayer"); } private static final String TAG = "ExoPlayerImpl"; /** * This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult} * when the player does not have any track selection made (such as when player is reset, or when * player seeks to an unprepared period). It will not be used as result of any {@link * TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)} * operation. */ /* package */ final TrackSelectorResult emptyTrackSelectorResult; /* package */ final Commands permanentAvailableCommands; private final ConditionVariable constructorFinished; private final Context applicationContext; private final Player wrappingPlayer; private final Renderer[] renderers; private final TrackSelector trackSelector; private final HandlerWrapper playbackInfoUpdateHandler; private final ExoPlayerImplInternal.PlaybackInfoUpdateListener playbackInfoUpdateListener; private final ExoPlayerImplInternal internalPlayer; private final ListenerSet<Listener> listeners; // TODO(b/187152483): Remove this once all events are dispatched via ListenerSet. private final CopyOnWriteArraySet<Listener> listenerArraySet; private final CopyOnWriteArraySet<AudioOffloadListener> audioOffloadListeners; private final Timeline.Period period; private final Timeline.Window window; private final List<MediaSourceHolderSnapshot> mediaSourceHolderSnapshots; private final boolean useLazyPreparation; private final MediaSource.Factory mediaSourceFactory; private final AnalyticsCollector analyticsCollector; private final Looper applicationLooper; private final BandwidthMeter bandwidthMeter; private final long seekBackIncrementMs; private final long seekForwardIncrementMs; private final Clock clock; private final ComponentListener componentListener; private final FrameMetadataListener frameMetadataListener; private final AudioBecomingNoisyManager audioBecomingNoisyManager; private final AudioFocusManager audioFocusManager; private final StreamVolumeManager streamVolumeManager; private final WakeLockManager wakeLockManager; private final WifiLockManager wifiLockManager; private final long detachSurfaceTimeoutMs; private @RepeatMode int repeatMode; private boolean shuffleModeEnabled; private int pendingOperationAcks; private @DiscontinuityReason int pendingDiscontinuityReason; private boolean pendingDiscontinuity; private @PlayWhenReadyChangeReason int pendingPlayWhenReadyChangeReason; private boolean foregroundMode; private SeekParameters seekParameters; private ShuffleOrder shuffleOrder; private boolean pauseAtEndOfMediaItems; private Commands availableCommands; private MediaMetadata mediaMetadata; private MediaMetadata playlistMetadata; @Nullable private Format videoFormat; @Nullable private Format audioFormat; @Nullable private AudioTrack keepSessionIdAudioTrack; @Nullable private Object videoOutput; @Nullable private Surface ownedSurface; @Nullable private SurfaceHolder surfaceHolder; @Nullable private SphericalGLSurfaceView sphericalGLSurfaceView; private boolean surfaceHolderSurfaceIsVideoOutput; @Nullable private TextureView textureView; private @C.VideoScalingMode int videoScalingMode; private @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy; private int surfaceWidth; private int surfaceHeight; @Nullable private DecoderCounters videoDecoderCounters; @Nullable private DecoderCounters audioDecoderCounters; private int audioSessionId; private AudioAttributes audioAttributes; private float volume; private boolean skipSilenceEnabled; private List<Cue> currentCues; @Nullable private VideoFrameMetadataListener videoFrameMetadataListener; @Nullable private CameraMotionListener cameraMotionListener; private boolean throwsWhenUsingWrongThread; private boolean hasNotifiedFullWrongThreadWarning; @Nullable private PriorityTaskManager priorityTaskManager; private boolean isPriorityTaskManagerRegistered; private boolean playerReleased; private DeviceInfo deviceInfo; private VideoSize videoSize; // MediaMetadata built from static (TrackGroup Format) and dynamic (onMetadata(Metadata)) metadata // sources. private MediaMetadata staticAndDynamicMediaMetadata; // Playback information when there is no pending seek/set source operation. private PlaybackInfo playbackInfo; // Playback information when there is a pending seek/set source operation. private int maskingWindowIndex; private int maskingPeriodIndex; private long maskingWindowPositionMs; @SuppressLint("HandlerLeak") public ExoPlayerImpl(ExoPlayer.Builder builder, Player wrappingPlayer) { constructorFinished = new ConditionVariable(); try { Log.i( TAG, "Init " + Integer.toHexString(System.identityHashCode(this)) + " [" + MediaLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "]"); applicationContext = builder.context.getApplicationContext(); analyticsCollector = builder.analyticsCollectorSupplier.get(); priorityTaskManager = builder.priorityTaskManager; audioAttributes = builder.audioAttributes; videoScalingMode = builder.videoScalingMode; videoChangeFrameRateStrategy = builder.videoChangeFrameRateStrategy; skipSilenceEnabled = builder.skipSilenceEnabled; detachSurfaceTimeoutMs = builder.detachSurfaceTimeoutMs; componentListener = new ComponentListener(); frameMetadataListener = new FrameMetadataListener(); Handler eventHandler = new Handler(builder.looper); renderers = builder .renderersFactorySupplier .get() .createRenderers( eventHandler, componentListener, componentListener, componentListener, componentListener); checkState(renderers.length > 0); this.trackSelector = builder.trackSelectorSupplier.get(); this.mediaSourceFactory = builder.mediaSourceFactorySupplier.get(); this.bandwidthMeter = builder.bandwidthMeterSupplier.get(); this.useLazyPreparation = builder.useLazyPreparation; this.seekParameters = builder.seekParameters; this.seekBackIncrementMs = builder.seekBackIncrementMs; this.seekForwardIncrementMs = builder.seekForwardIncrementMs; this.pauseAtEndOfMediaItems = builder.pauseAtEndOfMediaItems; this.applicationLooper = builder.looper; this.clock = builder.clock; this.wrappingPlayer = wrappingPlayer; listeners = new ListenerSet<>( applicationLooper, clock, (listener, flags) -> listener.onEvents(wrappingPlayer, new Events(flags))); listenerArraySet = new CopyOnWriteArraySet<>(); audioOffloadListeners = new CopyOnWriteArraySet<>(); mediaSourceHolderSnapshots = new ArrayList<>(); shuffleOrder = new ShuffleOrder.DefaultShuffleOrder(/* length= */ 0); emptyTrackSelectorResult = new TrackSelectorResult( new RendererConfiguration[renderers.length], new ExoTrackSelection[renderers.length], TracksInfo.EMPTY, /* info= */ null); period = new Timeline.Period(); window = new Timeline.Window(); permanentAvailableCommands = new Commands.Builder() .addAll( COMMAND_PLAY_PAUSE, COMMAND_PREPARE, COMMAND_STOP, COMMAND_SET_SPEED_AND_PITCH, COMMAND_SET_SHUFFLE_MODE, COMMAND_SET_REPEAT_MODE, COMMAND_GET_CURRENT_MEDIA_ITEM, COMMAND_GET_TIMELINE, COMMAND_GET_MEDIA_ITEMS_METADATA, COMMAND_SET_MEDIA_ITEMS_METADATA, COMMAND_CHANGE_MEDIA_ITEMS, COMMAND_GET_TRACK_INFOS, COMMAND_GET_AUDIO_ATTRIBUTES, COMMAND_GET_VOLUME, COMMAND_GET_DEVICE_VOLUME, COMMAND_SET_VOLUME, COMMAND_SET_DEVICE_VOLUME, COMMAND_ADJUST_DEVICE_VOLUME, COMMAND_SET_VIDEO_SURFACE, COMMAND_GET_TEXT) .addIf( COMMAND_SET_TRACK_SELECTION_PARAMETERS, trackSelector.isSetParametersSupported()) .build(); availableCommands = new Commands.Builder() .addAll(permanentAvailableCommands) .add(COMMAND_SEEK_TO_DEFAULT_POSITION) .add(COMMAND_SEEK_TO_MEDIA_ITEM) .build(); playbackInfoUpdateHandler = clock.createHandler(applicationLooper, /* callback= */ null); playbackInfoUpdateListener = playbackInfoUpdate -> playbackInfoUpdateHandler.post(() -> handlePlaybackInfo(playbackInfoUpdate)); playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult); analyticsCollector.setPlayer(wrappingPlayer, applicationLooper); PlayerId playerId = Util.SDK_INT < 31 ? new PlayerId() : Api31.createPlayerId(); internalPlayer = new ExoPlayerImplInternal( renderers, trackSelector, emptyTrackSelectorResult, builder.loadControlSupplier.get(), bandwidthMeter, repeatMode, shuffleModeEnabled, analyticsCollector, seekParameters, builder.livePlaybackSpeedControl, builder.releaseTimeoutMs, pauseAtEndOfMediaItems, applicationLooper, clock, playbackInfoUpdateListener, playerId); volume = 1; repeatMode = Player.REPEAT_MODE_OFF; mediaMetadata = MediaMetadata.EMPTY; playlistMetadata = MediaMetadata.EMPTY; staticAndDynamicMediaMetadata = MediaMetadata.EMPTY; maskingWindowIndex = C.INDEX_UNSET; if (Util.SDK_INT < 21) { audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET); } else { audioSessionId = Util.generateAudioSessionIdV21(applicationContext); } currentCues = ImmutableList.of(); throwsWhenUsingWrongThread = true; listeners.add(analyticsCollector); bandwidthMeter.addEventListener(new Handler(applicationLooper), analyticsCollector); addAudioOffloadListener(componentListener); if (builder.foregroundModeTimeoutMs > 0) { experimentalSetForegroundModeTimeoutMs(builder.foregroundModeTimeoutMs); } audioBecomingNoisyManager = new AudioBecomingNoisyManager(builder.context, eventHandler, componentListener); audioBecomingNoisyManager.setEnabled(builder.handleAudioBecomingNoisy); audioFocusManager = new AudioFocusManager(builder.context, eventHandler, componentListener); audioFocusManager.setAudioAttributes(builder.handleAudioFocus ? audioAttributes : null); streamVolumeManager = new StreamVolumeManager(builder.context, eventHandler, componentListener); streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage)); wakeLockManager = new WakeLockManager(builder.context); wakeLockManager.setEnabled(builder.wakeMode != C.WAKE_MODE_NONE); wifiLockManager = new WifiLockManager(builder.context); wifiLockManager.setEnabled(builder.wakeMode == C.WAKE_MODE_NETWORK); deviceInfo = createDeviceInfo(streamVolumeManager); videoSize = VideoSize.UNKNOWN; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode); sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled); sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_VIDEO_FRAME_METADATA_LISTENER, frameMetadataListener); sendRendererMessage( TRACK_TYPE_CAMERA_MOTION, MSG_SET_CAMERA_MOTION_LISTENER, frameMetadataListener); } finally { constructorFinished.open(); } } /** * Sets a limit on the time a call to {@link #setForegroundMode} can spend. If a call to {@link * #setForegroundMode} takes more than {@code timeoutMs} milliseconds to complete, the player will * raise an error via {@link Player.Listener#onPlayerError}. * * <p>This method is experimental, and will be renamed or removed in a future release. It should * only be called before the player is used. * * @param timeoutMs The time limit in milliseconds. */ public void experimentalSetForegroundModeTimeoutMs(long timeoutMs) { internalPlayer.experimentalSetForegroundModeTimeoutMs(timeoutMs); } public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) { verifyApplicationThread(); internalPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled); } public boolean experimentalIsSleepingForOffload() { verifyApplicationThread(); return playbackInfo.sleepingForOffload; } public Looper getPlaybackLooper() { // Don't verify application thread. We allow calls to this method from any thread. return internalPlayer.getPlaybackLooper(); } public Looper getApplicationLooper() { // Don't verify application thread. We allow calls to this method from any thread. return applicationLooper; } public Clock getClock() { // Don't verify application thread. We allow calls to this method from any thread. return clock; } public void addAudioOffloadListener(AudioOffloadListener listener) { // Don't verify application thread. We allow calls to this method from any thread. audioOffloadListeners.add(listener); } public void removeAudioOffloadListener(AudioOffloadListener listener) { // Don't verify application thread. We allow calls to this method from any thread. audioOffloadListeners.remove(listener); } public Commands getAvailableCommands() { verifyApplicationThread(); return availableCommands; } public @State int getPlaybackState() { verifyApplicationThread(); return playbackInfo.playbackState; } public @PlaybackSuppressionReason int getPlaybackSuppressionReason() { verifyApplicationThread(); return playbackInfo.playbackSuppressionReason; } @Nullable public ExoPlaybackException getPlayerError() { verifyApplicationThread(); return playbackInfo.playbackError; } /** @deprecated Use {@link #prepare()} instead. */ @Deprecated public void retry() { prepare(); } public void prepare() { verifyApplicationThread(); boolean playWhenReady = getPlayWhenReady(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, Player.STATE_BUFFERING); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); if (playbackInfo.playbackState != Player.STATE_IDLE) { return; } PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlaybackError(null); playbackInfo = playbackInfo.copyWithPlaybackState( playbackInfo.timeline.isEmpty() ? STATE_ENDED : STATE_BUFFERING); // Trigger internal prepare first before updating the playback info and notifying external // listeners to ensure that new operations issued in the listener notifications reach the // player after this prepare. The internal player can't change the playback info immediately // because it uses a callback. pendingOperationAcks++; internalPlayer.prepare(); updatePlaybackInfo( playbackInfo, /* ignored */ TIMELINE_CHANGE_REASON_SOURCE_UPDATE, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } /** * @deprecated Use {@link #setMediaSource(MediaSource)} and {@link ExoPlayer#prepare()} instead. */ @Deprecated public void prepare(MediaSource mediaSource) { verifyApplicationThread(); setMediaSource(mediaSource); prepare(); } /** * @deprecated Use {@link #setMediaSource(MediaSource, boolean)} and {@link ExoPlayer#prepare()} * instead. */ @Deprecated public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) { verifyApplicationThread(); setMediaSource(mediaSource, resetPosition); prepare(); } public void setMediaItems(List<MediaItem> mediaItems, boolean resetPosition) { verifyApplicationThread(); setMediaSources(createMediaSources(mediaItems), resetPosition); } public void setMediaItems(List<MediaItem> mediaItems, int startIndex, long startPositionMs) { verifyApplicationThread(); setMediaSources(createMediaSources(mediaItems), startIndex, startPositionMs); } public void setMediaSource(MediaSource mediaSource) { verifyApplicationThread(); setMediaSources(Collections.singletonList(mediaSource)); } public void setMediaSource(MediaSource mediaSource, long startPositionMs) { verifyApplicationThread(); setMediaSources( Collections.singletonList(mediaSource), /* startWindowIndex= */ 0, startPositionMs); } public void setMediaSource(MediaSource mediaSource, boolean resetPosition) { verifyApplicationThread(); setMediaSources(Collections.singletonList(mediaSource), resetPosition); } public void setMediaSources(List<MediaSource> mediaSources) { verifyApplicationThread(); setMediaSources(mediaSources, /* resetPosition= */ true); } public void setMediaSources(List<MediaSource> mediaSources, boolean resetPosition) { verifyApplicationThread(); setMediaSourcesInternal( mediaSources, /* startWindowIndex= */ C.INDEX_UNSET, /* startPositionMs= */ C.TIME_UNSET, /* resetToDefaultPosition= */ resetPosition); } public void setMediaSources( List<MediaSource> mediaSources, int startWindowIndex, long startPositionMs) { verifyApplicationThread(); setMediaSourcesInternal( mediaSources, startWindowIndex, startPositionMs, /* resetToDefaultPosition= */ false); } public void addMediaItems(int index, List<MediaItem> mediaItems) { verifyApplicationThread(); index = min(index, mediaSourceHolderSnapshots.size()); addMediaSources(index, createMediaSources(mediaItems)); } public void addMediaSource(MediaSource mediaSource) { verifyApplicationThread(); addMediaSources(Collections.singletonList(mediaSource)); } public void addMediaSource(int index, MediaSource mediaSource) { verifyApplicationThread(); addMediaSources(index, Collections.singletonList(mediaSource)); } public void addMediaSources(List<MediaSource> mediaSources) { verifyApplicationThread(); addMediaSources(/* index= */ mediaSourceHolderSnapshots.size(), mediaSources); } public void addMediaSources(int index, List<MediaSource> mediaSources) { verifyApplicationThread(); Assertions.checkArgument(index >= 0); Timeline oldTimeline = getCurrentTimeline(); pendingOperationAcks++; List<MediaSourceList.MediaSourceHolder> holders = addMediaSourceHolders(index, mediaSources); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); internalPlayer.addMediaSources(index, holders, shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void removeMediaItems(int fromIndex, int toIndex) { verifyApplicationThread(); toIndex = min(toIndex, mediaSourceHolderSnapshots.size()); PlaybackInfo newPlaybackInfo = removeMediaItemsInternal(fromIndex, toIndex); boolean positionDiscontinuity = !newPlaybackInfo.periodId.periodUid.equals(playbackInfo.periodId.periodUid); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), /* ignored */ C.INDEX_UNSET); } public void moveMediaItems(int fromIndex, int toIndex, int newFromIndex) { verifyApplicationThread(); Assertions.checkArgument( fromIndex >= 0 && fromIndex <= toIndex && toIndex <= mediaSourceHolderSnapshots.size() && newFromIndex >= 0); Timeline oldTimeline = getCurrentTimeline(); pendingOperationAcks++; newFromIndex = min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex)); Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); internalPlayer.moveMediaSources(fromIndex, toIndex, newFromIndex, shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void setShuffleOrder(ShuffleOrder shuffleOrder) { verifyApplicationThread(); Timeline timeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs( timeline, getCurrentMediaItemIndex(), getCurrentPosition())); pendingOperationAcks++; this.shuffleOrder = shuffleOrder; internalPlayer.setShuffleOrder(shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void setPauseAtEndOfMediaItems(boolean pauseAtEndOfMediaItems) { verifyApplicationThread(); if (this.pauseAtEndOfMediaItems == pauseAtEndOfMediaItems) { return; } this.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems; internalPlayer.setPauseAtEndOfWindow(pauseAtEndOfMediaItems); } public boolean getPauseAtEndOfMediaItems() { verifyApplicationThread(); return pauseAtEndOfMediaItems; } public void setPlayWhenReady(boolean playWhenReady) { verifyApplicationThread(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState()); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } public void setPlayWhenReady( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason, @PlayWhenReadyChangeReason int playWhenReadyChangeReason) { if (playbackInfo.playWhenReady == playWhenReady && playbackInfo.playbackSuppressionReason == playbackSuppressionReason) { return; } pendingOperationAcks++; PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason); internalPlayer.setPlayWhenReady(playWhenReady, playbackSuppressionReason); updatePlaybackInfo( playbackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, playWhenReadyChangeReason, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public boolean getPlayWhenReady() { verifyApplicationThread(); return playbackInfo.playWhenReady; } public void setRepeatMode(@RepeatMode int repeatMode) { verifyApplicationThread(); if (this.repeatMode != repeatMode) { this.repeatMode = repeatMode; internalPlayer.setRepeatMode(repeatMode); listeners.queueEvent( Player.EVENT_REPEAT_MODE_CHANGED, listener -> listener.onRepeatModeChanged(repeatMode)); updateAvailableCommands(); listeners.flushEvents(); } } public @RepeatMode int getRepeatMode() { verifyApplicationThread(); return repeatMode; } public void setShuffleModeEnabled(boolean shuffleModeEnabled) { verifyApplicationThread(); if (this.shuffleModeEnabled != shuffleModeEnabled) { this.shuffleModeEnabled = shuffleModeEnabled; internalPlayer.setShuffleModeEnabled(shuffleModeEnabled); listeners.queueEvent( Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED, listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled)); updateAvailableCommands(); listeners.flushEvents(); } } public boolean getShuffleModeEnabled() { verifyApplicationThread(); return shuffleModeEnabled; } public boolean isLoading() { verifyApplicationThread(); return playbackInfo.isLoading; } public void seekTo(int mediaItemIndex, long positionMs) { verifyApplicationThread(); analyticsCollector.notifySeekStarted(); Timeline timeline = playbackInfo.timeline; if (mediaItemIndex < 0 || (!timeline.isEmpty() && mediaItemIndex >= timeline.getWindowCount())) { throw new IllegalSeekPositionException(timeline, mediaItemIndex, positionMs); } pendingOperationAcks++; if (isPlayingAd()) { // TODO: Investigate adding support for seeking during ads. This is complicated to do in // general because the midroll ad preceding the seek destination must be played before the // content position can be played, if a different ad is playing at the moment. Log.w(TAG, "seekTo ignored because an ad is playing"); ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate = new ExoPlayerImplInternal.PlaybackInfoUpdate(this.playbackInfo); playbackInfoUpdate.incrementPendingOperationAcks(1); playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate); return; } @Player.State int newPlaybackState = getPlaybackState() == Player.STATE_IDLE ? Player.STATE_IDLE : STATE_BUFFERING; int oldMaskingMediaItemIndex = getCurrentMediaItemIndex(); PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackState(newPlaybackState); newPlaybackInfo = maskTimelineAndPosition( newPlaybackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs(timeline, mediaItemIndex, positionMs)); internalPlayer.seekTo(timeline, mediaItemIndex, Util.msToUs(positionMs)); updatePlaybackInfo( newPlaybackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ true, /* positionDiscontinuity= */ true, /* positionDiscontinuityReason= */ DISCONTINUITY_REASON_SEEK, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), oldMaskingMediaItemIndex); } public long getSeekBackIncrement() { verifyApplicationThread(); return seekBackIncrementMs; } public long getSeekForwardIncrement() { verifyApplicationThread(); return seekForwardIncrementMs; } public long getMaxSeekToPreviousPosition() { verifyApplicationThread(); return C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS; } public void setPlaybackParameters(PlaybackParameters playbackParameters) { verifyApplicationThread(); if (playbackParameters == null) { playbackParameters = PlaybackParameters.DEFAULT; } if (playbackInfo.playbackParameters.equals(playbackParameters)) { return; } PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters); pendingOperationAcks++; internalPlayer.setPlaybackParameters(playbackParameters); updatePlaybackInfo( newPlaybackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public PlaybackParameters getPlaybackParameters() { verifyApplicationThread(); return playbackInfo.playbackParameters; } public void setSeekParameters(@Nullable SeekParameters seekParameters) { verifyApplicationThread(); if (seekParameters == null) { seekParameters = SeekParameters.DEFAULT; } if (!this.seekParameters.equals(seekParameters)) { this.seekParameters = seekParameters; internalPlayer.setSeekParameters(seekParameters); } } public SeekParameters getSeekParameters() { verifyApplicationThread(); return seekParameters; } public void setForegroundMode(boolean foregroundMode) { verifyApplicationThread(); if (this.foregroundMode != foregroundMode) { this.foregroundMode = foregroundMode; if (!internalPlayer.setForegroundMode(foregroundMode)) { // One of the renderers timed out releasing its resources. stop( /* reset= */ false, ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_SET_FOREGROUND_MODE), PlaybackException.ERROR_CODE_TIMEOUT)); } } } public void stop() { stop(/* reset= */ false); } public void stop(boolean reset) { verifyApplicationThread(); audioFocusManager.updateAudioFocus(getPlayWhenReady(), Player.STATE_IDLE); stop(reset, /* error= */ null); currentCues = ImmutableList.of(); } /** * Stops the player. * * @param reset Whether the playlist should be cleared and whether the playback position and * playback error should be reset. * @param error An optional {@link ExoPlaybackException} to set. */ public void stop(boolean reset, @Nullable ExoPlaybackException error) { PlaybackInfo playbackInfo; if (reset) { playbackInfo = removeMediaItemsInternal( /* fromIndex= */ 0, /* toIndex= */ mediaSourceHolderSnapshots.size()); playbackInfo = playbackInfo.copyWithPlaybackError(null); } else { playbackInfo = this.playbackInfo.copyWithLoadingMediaPeriodId(this.playbackInfo.periodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; playbackInfo.totalBufferedDurationUs = 0; } playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE); if (error != null) { playbackInfo = playbackInfo.copyWithPlaybackError(error); } pendingOperationAcks++; internalPlayer.stop(); boolean positionDiscontinuity = playbackInfo.timeline.isEmpty() && !this.playbackInfo.timeline.isEmpty(); updatePlaybackInfo( playbackInfo, TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(playbackInfo), /* ignored */ C.INDEX_UNSET); } public void release() { Log.i( TAG, "Release " + Integer.toHexString(System.identityHashCode(this)) + " [" + MediaLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "] [" + MediaLibraryInfo.registeredModules() + "]"); verifyApplicationThread(); if (Util.SDK_INT < 21 && keepSessionIdAudioTrack != null) { keepSessionIdAudioTrack.release(); keepSessionIdAudioTrack = null; } audioBecomingNoisyManager.setEnabled(false); streamVolumeManager.release(); wakeLockManager.setStayAwake(false); wifiLockManager.setStayAwake(false); audioFocusManager.release(); if (!internalPlayer.release()) { // One of the renderers timed out releasing its resources. listeners.sendEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerError( ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_RELEASE), PlaybackException.ERROR_CODE_TIMEOUT))); } listeners.release(); playbackInfoUpdateHandler.removeCallbacksAndMessages(null); bandwidthMeter.removeEventListener(analyticsCollector); playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(playbackInfo.periodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; playbackInfo.totalBufferedDurationUs = 0; analyticsCollector.release(); removeSurfaceCallbacks(); if (ownedSurface != null) { ownedSurface.release(); ownedSurface = null; } if (isPriorityTaskManagerRegistered) { checkNotNull(priorityTaskManager).remove(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = false; } currentCues = ImmutableList.of(); playerReleased = true; } public PlayerMessage createMessage(Target target) { verifyApplicationThread(); return createMessageInternal(target); } public int getCurrentPeriodIndex() { verifyApplicationThread(); if (playbackInfo.timeline.isEmpty()) { return maskingPeriodIndex; } else { return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid); } } public int getCurrentMediaItemIndex() { verifyApplicationThread(); int currentWindowIndex = getCurrentWindowIndexInternal(); return currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex; } public long getDuration() { verifyApplicationThread(); if (isPlayingAd()) { MediaPeriodId periodId = playbackInfo.periodId; playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period); long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup); return Util.usToMs(adDurationUs); } return getContentDuration(); } private long getContentDuration() { Timeline timeline = getCurrentTimeline(); return timeline.isEmpty() ? C.TIME_UNSET : timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs(); } public long getCurrentPosition() { verifyApplicationThread(); return Util.usToMs(getCurrentPositionUsInternal(playbackInfo)); } public long getBufferedPosition() { verifyApplicationThread(); if (isPlayingAd()) { return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId) ? Util.usToMs(playbackInfo.bufferedPositionUs) : getDuration(); } return getContentBufferedPosition(); } public long getTotalBufferedDuration() { verifyApplicationThread(); return Util.usToMs(playbackInfo.totalBufferedDurationUs); } public boolean isPlayingAd() { verifyApplicationThread(); return playbackInfo.periodId.isAd(); } public int getCurrentAdGroupIndex() { verifyApplicationThread(); return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET; } public int getCurrentAdIndexInAdGroup() { verifyApplicationThread(); return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET; } public long getContentPosition() { verifyApplicationThread(); if (isPlayingAd()) { playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period); return playbackInfo.requestedContentPositionUs == C.TIME_UNSET ? playbackInfo .timeline .getWindow(getCurrentMediaItemIndex(), window) .getDefaultPositionMs() : period.getPositionInWindowMs() + Util.usToMs(playbackInfo.requestedContentPositionUs); } else { return getCurrentPosition(); } } public long getContentBufferedPosition() { verifyApplicationThread(); if (playbackInfo.timeline.isEmpty()) { return maskingWindowPositionMs; } if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber != playbackInfo.periodId.windowSequenceNumber) { return playbackInfo.timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs(); } long contentBufferedPositionUs = playbackInfo.bufferedPositionUs; if (playbackInfo.loadingMediaPeriodId.isAd()) { Timeline.Period loadingPeriod = playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period); contentBufferedPositionUs = loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex); if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) { contentBufferedPositionUs = loadingPeriod.durationUs; } } return Util.usToMs( periodPositionUsToWindowPositionUs( playbackInfo.timeline, playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs)); } public int getRendererCount() { verifyApplicationThread(); return renderers.length; } public @C.TrackType int getRendererType(int index) { verifyApplicationThread(); return renderers[index].getTrackType(); } public Renderer getRenderer(int index) { verifyApplicationThread(); return renderers[index]; } public TrackSelector getTrackSelector() { verifyApplicationThread(); return trackSelector; } public TrackGroupArray getCurrentTrackGroups() { verifyApplicationThread(); return playbackInfo.trackGroups; } public TrackSelectionArray getCurrentTrackSelections() { verifyApplicationThread(); return new TrackSelectionArray(playbackInfo.trackSelectorResult.selections); } public TracksInfo getCurrentTracksInfo() { verifyApplicationThread(); return playbackInfo.trackSelectorResult.tracksInfo; } public TrackSelectionParameters getTrackSelectionParameters() { verifyApplicationThread(); return trackSelector.getParameters(); } public void setTrackSelectionParameters(TrackSelectionParameters parameters) { verifyApplicationThread(); if (!trackSelector.isSetParametersSupported() || parameters.equals(trackSelector.getParameters())) { return; } trackSelector.setParameters(parameters); listeners.queueEvent( EVENT_TRACK_SELECTION_PARAMETERS_CHANGED, listener -> listener.onTrackSelectionParametersChanged(parameters)); } public MediaMetadata getMediaMetadata() { verifyApplicationThread(); return mediaMetadata; } private void onMetadata(Metadata metadata) { staticAndDynamicMediaMetadata = staticAndDynamicMediaMetadata.buildUpon().populateFromMetadata(metadata).build(); MediaMetadata newMediaMetadata = buildUpdatedMediaMetadata(); if (newMediaMetadata.equals(mediaMetadata)) { return; } mediaMetadata = newMediaMetadata; listeners.sendEvent( EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(mediaMetadata)); } public MediaMetadata getPlaylistMetadata() { verifyApplicationThread(); return playlistMetadata; } public void setPlaylistMetadata(MediaMetadata playlistMetadata) { verifyApplicationThread(); checkNotNull(playlistMetadata); if (playlistMetadata.equals(this.playlistMetadata)) { return; } this.playlistMetadata = playlistMetadata; listeners.sendEvent( EVENT_PLAYLIST_METADATA_CHANGED, listener -> listener.onPlaylistMetadataChanged(this.playlistMetadata)); } public Timeline getCurrentTimeline() { verifyApplicationThread(); return playbackInfo.timeline; } public void setVideoScalingMode(@C.VideoScalingMode int videoScalingMode) { verifyApplicationThread(); this.videoScalingMode = videoScalingMode; sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode); } public @C.VideoScalingMode int getVideoScalingMode() { return videoScalingMode; } public void setVideoChangeFrameRateStrategy( @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy) { verifyApplicationThread(); if (this.videoChangeFrameRateStrategy == videoChangeFrameRateStrategy) { return; } this.videoChangeFrameRateStrategy = videoChangeFrameRateStrategy; sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy); } public @C.VideoChangeFrameRateStrategy int getVideoChangeFrameRateStrategy() { return videoChangeFrameRateStrategy; } public VideoSize getVideoSize() { return videoSize; } public void clearVideoSurface() { verifyApplicationThread(); removeSurfaceCallbacks(); setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } public void clearVideoSurface(@Nullable Surface surface) { verifyApplicationThread(); if (surface != null && surface == videoOutput) { clearVideoSurface(); } } public void setVideoSurface(@Nullable Surface surface) { verifyApplicationThread(); removeSurfaceCallbacks(); setVideoOutputInternal(surface); int newSurfaceSize = surface == null ? 0 : C.LENGTH_UNSET; maybeNotifySurfaceSizeChanged(/* width= */ newSurfaceSize, /* height= */ newSurfaceSize); } public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { verifyApplicationThread(); if (surfaceHolder == null) { clearVideoSurface(); } else { removeSurfaceCallbacks(); this.surfaceHolderSurfaceIsVideoOutput = true; this.surfaceHolder = surfaceHolder; surfaceHolder.addCallback(componentListener); Surface surface = surfaceHolder.getSurface(); if (surface != null && surface.isValid()) { setVideoOutputInternal(surface); Rect surfaceSize = surfaceHolder.getSurfaceFrame(); maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height()); } else { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } } } public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { verifyApplicationThread(); if (surfaceHolder != null && surfaceHolder == this.surfaceHolder) { clearVideoSurface(); } } public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) { verifyApplicationThread(); if (surfaceView instanceof VideoDecoderOutputBufferRenderer) { removeSurfaceCallbacks(); setVideoOutputInternal(surfaceView); setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder()); } else if (surfaceView instanceof SphericalGLSurfaceView) { removeSurfaceCallbacks(); sphericalGLSurfaceView = (SphericalGLSurfaceView) surfaceView; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW) .setPayload(sphericalGLSurfaceView) .send(); sphericalGLSurfaceView.addVideoSurfaceListener(componentListener); setVideoOutputInternal(sphericalGLSurfaceView.getVideoSurface()); setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder()); } else { setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder()); } } public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) { verifyApplicationThread(); clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder()); } public void setVideoTextureView(@Nullable TextureView textureView) { verifyApplicationThread(); if (textureView == null) { clearVideoSurface(); } else { removeSurfaceCallbacks(); this.textureView = textureView; if (textureView.getSurfaceTextureListener() != null) { Log.w(TAG, "Replacing existing SurfaceTextureListener."); } textureView.setSurfaceTextureListener(componentListener); @Nullable SurfaceTexture surfaceTexture = textureView.isAvailable() ? textureView.getSurfaceTexture() : null; if (surfaceTexture == null) { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } else { setSurfaceTextureInternal(surfaceTexture); maybeNotifySurfaceSizeChanged(textureView.getWidth(), textureView.getHeight()); } } } public void clearVideoTextureView(@Nullable TextureView textureView) { verifyApplicationThread(); if (textureView != null && textureView == this.textureView) { clearVideoSurface(); } } public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) { verifyApplicationThread(); if (playerReleased) { return; } if (!Util.areEqual(this.audioAttributes, audioAttributes)) { this.audioAttributes = audioAttributes; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes); streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage)); analyticsCollector.onAudioAttributesChanged(audioAttributes); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onAudioAttributesChanged(audioAttributes); } } audioFocusManager.setAudioAttributes(handleAudioFocus ? audioAttributes : null); boolean playWhenReady = getPlayWhenReady(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState()); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } public AudioAttributes getAudioAttributes() { return audioAttributes; } public void setAudioSessionId(int audioSessionId) { verifyApplicationThread(); if (this.audioSessionId == audioSessionId) { return; } if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) { if (Util.SDK_INT < 21) { audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET); } else { audioSessionId = Util.generateAudioSessionIdV21(applicationContext); } } else if (Util.SDK_INT < 21) { // We need to re-initialize keepSessionIdAudioTrack to make sure the session is kept alive for // as long as the player is using it. initializeKeepSessionIdAudioTrack(audioSessionId); } this.audioSessionId = audioSessionId; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); analyticsCollector.onAudioSessionIdChanged(audioSessionId); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onAudioSessionIdChanged(audioSessionId); } } public int getAudioSessionId() { return audioSessionId; } public void setAuxEffectInfo(AuxEffectInfo auxEffectInfo) { verifyApplicationThread(); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUX_EFFECT_INFO, auxEffectInfo); } public void clearAuxEffectInfo() { setAuxEffectInfo(new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, /* sendLevel= */ 0f)); } public void setVolume(float volume) { verifyApplicationThread(); volume = Util.constrainValue(volume, /* min= */ 0, /* max= */ 1); if (this.volume == volume) { return; } this.volume = volume; sendVolumeToRenderers(); analyticsCollector.onVolumeChanged(volume); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onVolumeChanged(volume); } } public float getVolume() { return volume; } public boolean getSkipSilenceEnabled() { return skipSilenceEnabled; } public void setSkipSilenceEnabled(boolean skipSilenceEnabled) { verifyApplicationThread(); if (this.skipSilenceEnabled == skipSilenceEnabled) { return; } this.skipSilenceEnabled = skipSilenceEnabled; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled); notifySkipSilenceEnabledChanged(); } public AnalyticsCollector getAnalyticsCollector() { return analyticsCollector; } public void addAnalyticsListener(AnalyticsListener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); analyticsCollector.addListener(listener); } public void removeAnalyticsListener(AnalyticsListener listener) { // Don't verify application thread. We allow calls to this method from any thread. analyticsCollector.removeListener(listener); } public void setHandleAudioBecomingNoisy(boolean handleAudioBecomingNoisy) { verifyApplicationThread(); if (playerReleased) { return; } audioBecomingNoisyManager.setEnabled(handleAudioBecomingNoisy); } public void setPriorityTaskManager(@Nullable PriorityTaskManager priorityTaskManager) { verifyApplicationThread(); if (Util.areEqual(this.priorityTaskManager, priorityTaskManager)) { return; } if (isPriorityTaskManagerRegistered) { checkNotNull(this.priorityTaskManager).remove(C.PRIORITY_PLAYBACK); } if (priorityTaskManager != null && isLoading()) { priorityTaskManager.add(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = true; } else { isPriorityTaskManagerRegistered = false; } this.priorityTaskManager = priorityTaskManager; } @Nullable public Format getVideoFormat() { return videoFormat; } @Nullable public Format getAudioFormat() { return audioFormat; } @Nullable public DecoderCounters getVideoDecoderCounters() { return videoDecoderCounters; } @Nullable public DecoderCounters getAudioDecoderCounters() { return audioDecoderCounters; } public void setVideoFrameMetadataListener(VideoFrameMetadataListener listener) { verifyApplicationThread(); videoFrameMetadataListener = listener; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER) .setPayload(listener) .send(); } public void clearVideoFrameMetadataListener(VideoFrameMetadataListener listener) { verifyApplicationThread(); if (videoFrameMetadataListener != listener) { return; } createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER) .setPayload(null) .send(); } public void setCameraMotionListener(CameraMotionListener listener) { verifyApplicationThread(); cameraMotionListener = listener; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER) .setPayload(listener) .send(); } public void clearCameraMotionListener(CameraMotionListener listener) { verifyApplicationThread(); if (cameraMotionListener != listener) { return; } createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER) .setPayload(null) .send(); } public List<Cue> getCurrentCues() { verifyApplicationThread(); return currentCues; } public void addListener(Listener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); listeners.add(listener); listenerArraySet.add(listener); } public void removeListener(Listener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); listeners.remove(listener); listenerArraySet.remove(listener); } public void setHandleWakeLock(boolean handleWakeLock) { setWakeMode(handleWakeLock ? C.WAKE_MODE_LOCAL : C.WAKE_MODE_NONE); } public void setWakeMode(@C.WakeMode int wakeMode) { verifyApplicationThread(); switch (wakeMode) { case C.WAKE_MODE_NONE: wakeLockManager.setEnabled(false); wifiLockManager.setEnabled(false); break; case C.WAKE_MODE_LOCAL: wakeLockManager.setEnabled(true); wifiLockManager.setEnabled(false); break; case C.WAKE_MODE_NETWORK: wakeLockManager.setEnabled(true); wifiLockManager.setEnabled(true); break; default: break; } } public DeviceInfo getDeviceInfo() { verifyApplicationThread(); return deviceInfo; } public int getDeviceVolume() { verifyApplicationThread(); return streamVolumeManager.getVolume(); } public boolean isDeviceMuted() { verifyApplicationThread(); return streamVolumeManager.isMuted(); } public void setDeviceVolume(int volume) { verifyApplicationThread(); streamVolumeManager.setVolume(volume); } public void increaseDeviceVolume() { verifyApplicationThread(); streamVolumeManager.increaseVolume(); } public void decreaseDeviceVolume() { verifyApplicationThread(); streamVolumeManager.decreaseVolume(); } public void setDeviceMuted(boolean muted) { verifyApplicationThread(); streamVolumeManager.setMuted(muted); } /* package */ void setThrowsWhenUsingWrongThread(boolean throwsWhenUsingWrongThread) { this.throwsWhenUsingWrongThread = throwsWhenUsingWrongThread; } private int getCurrentWindowIndexInternal() { if (playbackInfo.timeline.isEmpty()) { return maskingWindowIndex; } else { return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period) .windowIndex; } } private long getCurrentPositionUsInternal(PlaybackInfo playbackInfo) { if (playbackInfo.timeline.isEmpty()) { return Util.msToUs(maskingWindowPositionMs); } else if (playbackInfo.periodId.isAd()) { return playbackInfo.positionUs; } else { return periodPositionUsToWindowPositionUs( playbackInfo.timeline, playbackInfo.periodId, playbackInfo.positionUs); } } private List<MediaSource> createMediaSources(List<MediaItem> mediaItems) { List<MediaSource> mediaSources = new ArrayList<>(); for (int i = 0; i < mediaItems.size(); i++) { mediaSources.add(mediaSourceFactory.createMediaSource(mediaItems.get(i))); } return mediaSources; } private void handlePlaybackInfo(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate) { pendingOperationAcks -= playbackInfoUpdate.operationAcks; if (playbackInfoUpdate.positionDiscontinuity) { pendingDiscontinuityReason = playbackInfoUpdate.discontinuityReason; pendingDiscontinuity = true; } if (playbackInfoUpdate.hasPlayWhenReadyChangeReason) { pendingPlayWhenReadyChangeReason = playbackInfoUpdate.playWhenReadyChangeReason; } if (pendingOperationAcks == 0) { Timeline newTimeline = playbackInfoUpdate.playbackInfo.timeline; if (!this.playbackInfo.timeline.isEmpty() && newTimeline.isEmpty()) { // Update the masking variables, which are used when the timeline becomes empty because a // ConcatenatingMediaSource has been cleared. maskingWindowIndex = C.INDEX_UNSET; maskingWindowPositionMs = 0; maskingPeriodIndex = 0; } if (!newTimeline.isEmpty()) { List<Timeline> timelines = ((PlaylistTimeline) newTimeline).getChildTimelines(); checkState(timelines.size() == mediaSourceHolderSnapshots.size()); for (int i = 0; i < timelines.size(); i++) { mediaSourceHolderSnapshots.get(i).timeline = timelines.get(i); } } boolean positionDiscontinuity = false; long discontinuityWindowStartPositionUs = C.TIME_UNSET; if (pendingDiscontinuity) { positionDiscontinuity = !playbackInfoUpdate.playbackInfo.periodId.equals(playbackInfo.periodId) || playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs != playbackInfo.positionUs; if (positionDiscontinuity) { discontinuityWindowStartPositionUs = newTimeline.isEmpty() || playbackInfoUpdate.playbackInfo.periodId.isAd() ? playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs : periodPositionUsToWindowPositionUs( newTimeline, playbackInfoUpdate.playbackInfo.periodId, playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs); } } pendingDiscontinuity = false; updatePlaybackInfo( playbackInfoUpdate.playbackInfo, TIMELINE_CHANGE_REASON_SOURCE_UPDATE, pendingPlayWhenReadyChangeReason, /* seekProcessed= */ false, positionDiscontinuity, pendingDiscontinuityReason, discontinuityWindowStartPositionUs, /* ignored */ C.INDEX_UNSET); } } // Calling deprecated listeners. @SuppressWarnings("deprecation") private void updatePlaybackInfo( PlaybackInfo playbackInfo, @TimelineChangeReason int timelineChangeReason, @PlayWhenReadyChangeReason int playWhenReadyChangeReason, boolean seekProcessed, boolean positionDiscontinuity, @DiscontinuityReason int positionDiscontinuityReason, long discontinuityWindowStartPositionUs, int oldMaskingMediaItemIndex) { // Assign playback info immediately such that all getters return the right values, but keep // snapshot of previous and new state so that listener invocations are triggered correctly. PlaybackInfo previousPlaybackInfo = this.playbackInfo; PlaybackInfo newPlaybackInfo = playbackInfo; this.playbackInfo = playbackInfo; Pair<Boolean, Integer> mediaItemTransitionInfo = evaluateMediaItemTransitionReason( newPlaybackInfo, previousPlaybackInfo, positionDiscontinuity, positionDiscontinuityReason, !previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)); boolean mediaItemTransitioned = mediaItemTransitionInfo.first; int mediaItemTransitionReason = mediaItemTransitionInfo.second; MediaMetadata newMediaMetadata = mediaMetadata; @Nullable MediaItem mediaItem = null; if (mediaItemTransitioned) { if (!newPlaybackInfo.timeline.isEmpty()) { int windowIndex = newPlaybackInfo.timeline.getPeriodByUid(newPlaybackInfo.periodId.periodUid, period) .windowIndex; mediaItem = newPlaybackInfo.timeline.getWindow(windowIndex, window).mediaItem; } staticAndDynamicMediaMetadata = MediaMetadata.EMPTY; } if (mediaItemTransitioned || !previousPlaybackInfo.staticMetadata.equals(newPlaybackInfo.staticMetadata)) { staticAndDynamicMediaMetadata = staticAndDynamicMediaMetadata .buildUpon() .populateFromMetadata(newPlaybackInfo.staticMetadata) .build(); newMediaMetadata = buildUpdatedMediaMetadata(); } boolean metadataChanged = !newMediaMetadata.equals(mediaMetadata); mediaMetadata = newMediaMetadata; boolean playWhenReadyChanged = previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady; boolean playbackStateChanged = previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState; if (playbackStateChanged || playWhenReadyChanged) { updateWakeAndWifiLock(); } boolean isLoadingChanged = previousPlaybackInfo.isLoading != newPlaybackInfo.isLoading; if (isLoadingChanged) { updatePriorityTaskManagerForIsLoadingChange(newPlaybackInfo.isLoading); } if (!previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)) { listeners.queueEvent( Player.EVENT_TIMELINE_CHANGED, listener -> listener.onTimelineChanged(newPlaybackInfo.timeline, timelineChangeReason)); } if (positionDiscontinuity) { PositionInfo previousPositionInfo = getPreviousPositionInfo( positionDiscontinuityReason, previousPlaybackInfo, oldMaskingMediaItemIndex); PositionInfo positionInfo = getPositionInfo(discontinuityWindowStartPositionUs); listeners.queueEvent( Player.EVENT_POSITION_DISCONTINUITY, listener -> { listener.onPositionDiscontinuity(positionDiscontinuityReason); listener.onPositionDiscontinuity( previousPositionInfo, positionInfo, positionDiscontinuityReason); }); } if (mediaItemTransitioned) { @Nullable final MediaItem finalMediaItem = mediaItem; listeners.queueEvent( Player.EVENT_MEDIA_ITEM_TRANSITION, listener -> listener.onMediaItemTransition(finalMediaItem, mediaItemTransitionReason)); } if (previousPlaybackInfo.playbackError != newPlaybackInfo.playbackError) { listeners.queueEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerErrorChanged(newPlaybackInfo.playbackError)); if (newPlaybackInfo.playbackError != null) { listeners.queueEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerError(newPlaybackInfo.playbackError)); } } if (previousPlaybackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult) { trackSelector.onSelectionActivated(newPlaybackInfo.trackSelectorResult.info); TrackSelectionArray newSelection = new TrackSelectionArray(newPlaybackInfo.trackSelectorResult.selections); listeners.queueEvent( Player.EVENT_TRACKS_CHANGED, listener -> listener.onTracksChanged(newPlaybackInfo.trackGroups, newSelection)); listeners.queueEvent( Player.EVENT_TRACKS_CHANGED, listener -> listener.onTracksInfoChanged(newPlaybackInfo.trackSelectorResult.tracksInfo)); } if (metadataChanged) { final MediaMetadata finalMediaMetadata = mediaMetadata; listeners.queueEvent( EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(finalMediaMetadata)); } if (isLoadingChanged) { listeners.queueEvent( Player.EVENT_IS_LOADING_CHANGED, listener -> { listener.onLoadingChanged(newPlaybackInfo.isLoading); listener.onIsLoadingChanged(newPlaybackInfo.isLoading); }); } if (playbackStateChanged || playWhenReadyChanged) { listeners.queueEvent( /* eventFlag= */ C.INDEX_UNSET, listener -> listener.onPlayerStateChanged( newPlaybackInfo.playWhenReady, newPlaybackInfo.playbackState)); } if (playbackStateChanged) { listeners.queueEvent( Player.EVENT_PLAYBACK_STATE_CHANGED, listener -> listener.onPlaybackStateChanged(newPlaybackInfo.playbackState)); } if (playWhenReadyChanged) { listeners.queueEvent( Player.EVENT_PLAY_WHEN_READY_CHANGED, listener -> listener.onPlayWhenReadyChanged( newPlaybackInfo.playWhenReady, playWhenReadyChangeReason)); } if (previousPlaybackInfo.playbackSuppressionReason != newPlaybackInfo.playbackSuppressionReason) { listeners.queueEvent( Player.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED, listener -> listener.onPlaybackSuppressionReasonChanged( newPlaybackInfo.playbackSuppressionReason)); } if (isPlaying(previousPlaybackInfo) != isPlaying(newPlaybackInfo)) { listeners.queueEvent( Player.EVENT_IS_PLAYING_CHANGED, listener -> listener.onIsPlayingChanged(isPlaying(newPlaybackInfo))); } if (!previousPlaybackInfo.playbackParameters.equals(newPlaybackInfo.playbackParameters)) { listeners.queueEvent( Player.EVENT_PLAYBACK_PARAMETERS_CHANGED, listener -> listener.onPlaybackParametersChanged(newPlaybackInfo.playbackParameters)); } if (seekProcessed) { listeners.queueEvent(/* eventFlag= */ C.INDEX_UNSET, Listener::onSeekProcessed); } updateAvailableCommands(); listeners.flushEvents(); if (previousPlaybackInfo.offloadSchedulingEnabled != newPlaybackInfo.offloadSchedulingEnabled) { for (AudioOffloadListener listener : audioOffloadListeners) { listener.onExperimentalOffloadSchedulingEnabledChanged( newPlaybackInfo.offloadSchedulingEnabled); } } if (previousPlaybackInfo.sleepingForOffload != newPlaybackInfo.sleepingForOffload) { for (AudioOffloadListener listener : audioOffloadListeners) { listener.onExperimentalSleepingForOffloadChanged(newPlaybackInfo.sleepingForOffload); } } } private PositionInfo getPreviousPositionInfo( @DiscontinuityReason int positionDiscontinuityReason, PlaybackInfo oldPlaybackInfo, int oldMaskingMediaItemIndex) { @Nullable Object oldWindowUid = null; @Nullable Object oldPeriodUid = null; int oldMediaItemIndex = oldMaskingMediaItemIndex; int oldPeriodIndex = C.INDEX_UNSET; @Nullable MediaItem oldMediaItem = null; Timeline.Period oldPeriod = new Timeline.Period(); if (!oldPlaybackInfo.timeline.isEmpty()) { oldPeriodUid = oldPlaybackInfo.periodId.periodUid; oldPlaybackInfo.timeline.getPeriodByUid(oldPeriodUid, oldPeriod); oldMediaItemIndex = oldPeriod.windowIndex; oldPeriodIndex = oldPlaybackInfo.timeline.getIndexOfPeriod(oldPeriodUid); oldWindowUid = oldPlaybackInfo.timeline.getWindow(oldMediaItemIndex, window).uid; oldMediaItem = window.mediaItem; } long oldPositionUs; long oldContentPositionUs; if (positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) { if (oldPlaybackInfo.periodId.isAd()) { // The old position is the end of the previous ad. oldPositionUs = oldPeriod.getAdDurationUs( oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup); // The ad cue point is stored in the old requested content position. oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo); } else if (oldPlaybackInfo.periodId.nextAdGroupIndex != C.INDEX_UNSET) { // The old position is the end of a clipped content before an ad group. Use the exact ad // cue point as the transition position. oldPositionUs = getRequestedContentPositionUs(playbackInfo); oldContentPositionUs = oldPositionUs; } else { // The old position is the end of a Timeline period. Use the exact duration. oldPositionUs = oldPeriod.positionInWindowUs + oldPeriod.durationUs; oldContentPositionUs = oldPositionUs; } } else if (oldPlaybackInfo.periodId.isAd()) { oldPositionUs = oldPlaybackInfo.positionUs; oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo); } else { oldPositionUs = oldPeriod.positionInWindowUs + oldPlaybackInfo.positionUs; oldContentPositionUs = oldPositionUs; } return new PositionInfo( oldWindowUid, oldMediaItemIndex, oldMediaItem, oldPeriodUid, oldPeriodIndex, Util.usToMs(oldPositionUs), Util.usToMs(oldContentPositionUs), oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup); } private PositionInfo getPositionInfo(long discontinuityWindowStartPositionUs) { @Nullable Object newWindowUid = null; @Nullable Object newPeriodUid = null; int newMediaItemIndex = getCurrentMediaItemIndex(); int newPeriodIndex = C.INDEX_UNSET; @Nullable MediaItem newMediaItem = null; if (!playbackInfo.timeline.isEmpty()) { newPeriodUid = playbackInfo.periodId.periodUid; playbackInfo.timeline.getPeriodByUid(newPeriodUid, period); newPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(newPeriodUid); newWindowUid = playbackInfo.timeline.getWindow(newMediaItemIndex, window).uid; newMediaItem = window.mediaItem; } long positionMs = Util.usToMs(discontinuityWindowStartPositionUs); return new PositionInfo( newWindowUid, newMediaItemIndex, newMediaItem, newPeriodUid, newPeriodIndex, positionMs, /* contentPositionMs= */ playbackInfo.periodId.isAd() ? Util.usToMs(getRequestedContentPositionUs(playbackInfo)) : positionMs, playbackInfo.periodId.adGroupIndex, playbackInfo.periodId.adIndexInAdGroup); } private static long getRequestedContentPositionUs(PlaybackInfo playbackInfo) { Timeline.Window window = new Timeline.Window(); Timeline.Period period = new Timeline.Period(); playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period); return playbackInfo.requestedContentPositionUs == C.TIME_UNSET ? playbackInfo.timeline.getWindow(period.windowIndex, window).getDefaultPositionUs() : period.getPositionInWindowUs() + playbackInfo.requestedContentPositionUs; } private Pair<Boolean, Integer> evaluateMediaItemTransitionReason( PlaybackInfo playbackInfo, PlaybackInfo oldPlaybackInfo, boolean positionDiscontinuity, @DiscontinuityReason int positionDiscontinuityReason, boolean timelineChanged) { Timeline oldTimeline = oldPlaybackInfo.timeline; Timeline newTimeline = playbackInfo.timeline; if (newTimeline.isEmpty() && oldTimeline.isEmpty()) { return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET); } else if (newTimeline.isEmpty() != oldTimeline.isEmpty()) { return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED); } int oldWindowIndex = oldTimeline.getPeriodByUid(oldPlaybackInfo.periodId.periodUid, period).windowIndex; Object oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid; int newWindowIndex = newTimeline.getPeriodByUid(playbackInfo.periodId.periodUid, period).windowIndex; Object newWindowUid = newTimeline.getWindow(newWindowIndex, window).uid; if (!oldWindowUid.equals(newWindowUid)) { @Player.MediaItemTransitionReason int transitionReason; if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_AUTO; } else if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_SEEK; } else if (timelineChanged) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED; } else { // A change in window uid must be justified by one of the reasons above. throw new IllegalStateException(); } return new Pair<>(/* isTransitioning */ true, transitionReason); } else if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION && oldPlaybackInfo.periodId.windowSequenceNumber < playbackInfo.periodId.windowSequenceNumber) { return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_REPEAT); } return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET); } private void updateAvailableCommands() { Commands previousAvailableCommands = availableCommands; availableCommands = Util.getAvailableCommands(wrappingPlayer, permanentAvailableCommands); if (!availableCommands.equals(previousAvailableCommands)) { listeners.queueEvent( Player.EVENT_AVAILABLE_COMMANDS_CHANGED, listener -> listener.onAvailableCommandsChanged(availableCommands)); } } private void setMediaSourcesInternal( List<MediaSource> mediaSources, int startWindowIndex, long startPositionMs, boolean resetToDefaultPosition) { int currentWindowIndex = getCurrentWindowIndexInternal(); long currentPositionMs = getCurrentPosition(); pendingOperationAcks++; if (!mediaSourceHolderSnapshots.isEmpty()) { removeMediaSourceHolders( /* fromIndex= */ 0, /* toIndexExclusive= */ mediaSourceHolderSnapshots.size()); } List<MediaSourceList.MediaSourceHolder> holders = addMediaSourceHolders(/* index= */ 0, mediaSources); Timeline timeline = createMaskingTimeline(); if (!timeline.isEmpty() && startWindowIndex >= timeline.getWindowCount()) { throw new IllegalSeekPositionException(timeline, startWindowIndex, startPositionMs); } // Evaluate the actual start position. if (resetToDefaultPosition) { startWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); startPositionMs = C.TIME_UNSET; } else if (startWindowIndex == C.INDEX_UNSET) { startWindowIndex = currentWindowIndex; startPositionMs = currentPositionMs; } PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs(timeline, startWindowIndex, startPositionMs)); // Mask the playback state. int maskingPlaybackState = newPlaybackInfo.playbackState; if (startWindowIndex != C.INDEX_UNSET && newPlaybackInfo.playbackState != STATE_IDLE) { // Position reset to startWindowIndex (results in pending initial seek). if (timeline.isEmpty() || startWindowIndex >= timeline.getWindowCount()) { // Setting an empty timeline or invalid seek transitions to ended. maskingPlaybackState = STATE_ENDED; } else { maskingPlaybackState = STATE_BUFFERING; } } newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(maskingPlaybackState); internalPlayer.setMediaSources( holders, startWindowIndex, Util.msToUs(startPositionMs), shuffleOrder); boolean positionDiscontinuity = !playbackInfo.periodId.periodUid.equals(newPlaybackInfo.periodId.periodUid) && !playbackInfo.timeline.isEmpty(); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), /* ignored */ C.INDEX_UNSET); } private List<MediaSourceList.MediaSourceHolder> addMediaSourceHolders( int index, List<MediaSource> mediaSources) { List<MediaSourceList.MediaSourceHolder> holders = new ArrayList<>(); for (int i = 0; i < mediaSources.size(); i++) { MediaSourceList.MediaSourceHolder holder = new MediaSourceList.MediaSourceHolder(mediaSources.get(i), useLazyPreparation); holders.add(holder); mediaSourceHolderSnapshots.add( i + index, new MediaSourceHolderSnapshot(holder.uid, holder.mediaSource.getTimeline())); } shuffleOrder = shuffleOrder.cloneAndInsert( /* insertionIndex= */ index, /* insertionCount= */ holders.size()); return holders; } private PlaybackInfo removeMediaItemsInternal(int fromIndex, int toIndex) { Assertions.checkArgument( fromIndex >= 0 && toIndex >= fromIndex && toIndex <= mediaSourceHolderSnapshots.size()); int currentIndex = getCurrentMediaItemIndex(); Timeline oldTimeline = getCurrentTimeline(); int currentMediaSourceCount = mediaSourceHolderSnapshots.size(); pendingOperationAcks++; removeMediaSourceHolders(fromIndex, /* toIndexExclusive= */ toIndex); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); // Player transitions to STATE_ENDED if the current index is part of the removed tail. final boolean transitionsToEnded = newPlaybackInfo.playbackState != STATE_IDLE && newPlaybackInfo.playbackState != STATE_ENDED && fromIndex < toIndex && toIndex == currentMediaSourceCount && currentIndex >= newPlaybackInfo.timeline.getWindowCount(); if (transitionsToEnded) { newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(STATE_ENDED); } internalPlayer.removeMediaSources(fromIndex, toIndex, shuffleOrder); return newPlaybackInfo; } private void removeMediaSourceHolders(int fromIndex, int toIndexExclusive) { for (int i = toIndexExclusive - 1; i >= fromIndex; i--) { mediaSourceHolderSnapshots.remove(i); } shuffleOrder = shuffleOrder.cloneAndRemove(fromIndex, toIndexExclusive); } private Timeline createMaskingTimeline() { return new PlaylistTimeline(mediaSourceHolderSnapshots, shuffleOrder); } private PlaybackInfo maskTimelineAndPosition( PlaybackInfo playbackInfo, Timeline timeline, @Nullable Pair<Object, Long> periodPositionUs) { Assertions.checkArgument(timeline.isEmpty() || periodPositionUs != null); Timeline oldTimeline = playbackInfo.timeline; // Mask the timeline. playbackInfo = playbackInfo.copyWithTimeline(timeline); if (timeline.isEmpty()) { // Reset periodId and loadingPeriodId. MediaPeriodId dummyMediaPeriodId = PlaybackInfo.getDummyPeriodForEmptyTimeline(); long positionUs = Util.msToUs(maskingWindowPositionMs); playbackInfo = playbackInfo.copyWithNewPosition( dummyMediaPeriodId, positionUs, /* requestedContentPositionUs= */ positionUs, /* discontinuityStartPositionUs= */ positionUs, /* totalBufferedDurationUs= */ 0, TrackGroupArray.EMPTY, emptyTrackSelectorResult, /* staticMetadata= */ ImmutableList.of()); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(dummyMediaPeriodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; return playbackInfo; } Object oldPeriodUid = playbackInfo.periodId.periodUid; boolean playingPeriodChanged = !oldPeriodUid.equals(castNonNull(periodPositionUs).first); MediaPeriodId newPeriodId = playingPeriodChanged ? new MediaPeriodId(periodPositionUs.first) : playbackInfo.periodId; long newContentPositionUs = periodPositionUs.second; long oldContentPositionUs = Util.msToUs(getContentPosition()); if (!oldTimeline.isEmpty()) { oldContentPositionUs -= oldTimeline.getPeriodByUid(oldPeriodUid, period).getPositionInWindowUs(); } if (playingPeriodChanged || newContentPositionUs < oldContentPositionUs) { checkState(!newPeriodId.isAd()); // The playing period changes or a backwards seek within the playing period occurs. playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ newContentPositionUs, /* requestedContentPositionUs= */ newContentPositionUs, /* discontinuityStartPositionUs= */ newContentPositionUs, /* totalBufferedDurationUs= */ 0, playingPeriodChanged ? TrackGroupArray.EMPTY : playbackInfo.trackGroups, playingPeriodChanged ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult, playingPeriodChanged ? ImmutableList.of() : playbackInfo.staticMetadata); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId); playbackInfo.bufferedPositionUs = newContentPositionUs; } else if (newContentPositionUs == oldContentPositionUs) { // Period position remains unchanged. int loadingPeriodIndex = timeline.getIndexOfPeriod(playbackInfo.loadingMediaPeriodId.periodUid); if (loadingPeriodIndex == C.INDEX_UNSET || timeline.getPeriod(loadingPeriodIndex, period).windowIndex != timeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex) { // Discard periods after the playing period, if the loading period is discarded or the // playing and loading period are not in the same window. timeline.getPeriodByUid(newPeriodId.periodUid, period); long maskedBufferedPositionUs = newPeriodId.isAd() ? period.getAdDurationUs(newPeriodId.adGroupIndex, newPeriodId.adIndexInAdGroup) : period.durationUs; playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ playbackInfo.positionUs, /* requestedContentPositionUs= */ playbackInfo.positionUs, playbackInfo.discontinuityStartPositionUs, /* totalBufferedDurationUs= */ maskedBufferedPositionUs - playbackInfo.positionUs, playbackInfo.trackGroups, playbackInfo.trackSelectorResult, playbackInfo.staticMetadata); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId); playbackInfo.bufferedPositionUs = maskedBufferedPositionUs; } } else { checkState(!newPeriodId.isAd()); // A forward seek within the playing period (timeline did not change). long maskedTotalBufferedDurationUs = max( 0, playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs)); long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs; if (playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)) { maskedBufferedPositionUs = newContentPositionUs + maskedTotalBufferedDurationUs; } playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ newContentPositionUs, /* requestedContentPositionUs= */ newContentPositionUs, /* discontinuityStartPositionUs= */ newContentPositionUs, maskedTotalBufferedDurationUs, playbackInfo.trackGroups, playbackInfo.trackSelectorResult, playbackInfo.staticMetadata); playbackInfo.bufferedPositionUs = maskedBufferedPositionUs; } return playbackInfo; } @Nullable private Pair<Object, Long> getPeriodPositionUsAfterTimelineChanged( Timeline oldTimeline, Timeline newTimeline) { long currentPositionMs = getContentPosition(); if (oldTimeline.isEmpty() || newTimeline.isEmpty()) { boolean isCleared = !oldTimeline.isEmpty() && newTimeline.isEmpty(); return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, isCleared ? C.INDEX_UNSET : getCurrentWindowIndexInternal(), isCleared ? C.TIME_UNSET : currentPositionMs); } int currentMediaItemIndex = getCurrentMediaItemIndex(); @Nullable Pair<Object, Long> oldPeriodPositionUs = oldTimeline.getPeriodPositionUs( window, period, currentMediaItemIndex, Util.msToUs(currentPositionMs)); Object periodUid = castNonNull(oldPeriodPositionUs).first; if (newTimeline.getIndexOfPeriod(periodUid) != C.INDEX_UNSET) { // The old period position is still available in the new timeline. return oldPeriodPositionUs; } // Period uid not found in new timeline. Try to get subsequent period. @Nullable Object nextPeriodUid = ExoPlayerImplInternal.resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, periodUid, oldTimeline, newTimeline); if (nextPeriodUid != null) { // Reset position to the default position of the window of the subsequent period. newTimeline.getPeriodByUid(nextPeriodUid, period); return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, period.windowIndex, newTimeline.getWindow(period.windowIndex, window).getDefaultPositionMs()); } else { // No subsequent period found and the new timeline is not empty. Use the default position. return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, /* windowIndex= */ C.INDEX_UNSET, /* windowPositionMs= */ C.TIME_UNSET); } } @Nullable private Pair<Object, Long> maskWindowPositionMsOrGetPeriodPositionUs( Timeline timeline, int windowIndex, long windowPositionMs) { if (timeline.isEmpty()) { // If empty we store the initial seek in the masking variables. maskingWindowIndex = windowIndex; maskingWindowPositionMs = windowPositionMs == C.TIME_UNSET ? 0 : windowPositionMs; maskingPeriodIndex = 0; return null; } if (windowIndex == C.INDEX_UNSET || windowIndex >= timeline.getWindowCount()) { // Use default position of timeline if window index still unset or if a previous initial seek // now turns out to be invalid. windowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); windowPositionMs = timeline.getWindow(windowIndex, window).getDefaultPositionMs(); } return timeline.getPeriodPositionUs(window, period, windowIndex, Util.msToUs(windowPositionMs)); } private long periodPositionUsToWindowPositionUs( Timeline timeline, MediaPeriodId periodId, long positionUs) { timeline.getPeriodByUid(periodId.periodUid, period); positionUs += period.getPositionInWindowUs(); return positionUs; } private PlayerMessage createMessageInternal(Target target) { int currentWindowIndex = getCurrentWindowIndexInternal(); return new PlayerMessage( internalPlayer, target, playbackInfo.timeline, currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex, clock, internalPlayer.getPlaybackLooper()); } /** * Builds a {@link MediaMetadata} from the main sources. * * <p>{@link MediaItem} {@link MediaMetadata} is prioritized, with any gaps/missing fields * populated by metadata from static ({@link TrackGroup} {@link Format}) and dynamic ({@link * #onMetadata(Metadata)}) sources. */ private MediaMetadata buildUpdatedMediaMetadata() { Timeline timeline = getCurrentTimeline(); if (timeline.isEmpty()) { return staticAndDynamicMediaMetadata; } MediaItem mediaItem = timeline.getWindow(getCurrentMediaItemIndex(), window).mediaItem; // MediaItem metadata is prioritized over metadata within the media. return staticAndDynamicMediaMetadata.buildUpon().populate(mediaItem.mediaMetadata).build(); } private void removeSurfaceCallbacks() { if (sphericalGLSurfaceView != null) { createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW) .setPayload(null) .send(); sphericalGLSurfaceView.removeVideoSurfaceListener(componentListener); sphericalGLSurfaceView = null; } if (textureView != null) { if (textureView.getSurfaceTextureListener() != componentListener) { Log.w(TAG, "SurfaceTextureListener already unset or replaced."); } else { textureView.setSurfaceTextureListener(null); } textureView = null; } if (surfaceHolder != null) { surfaceHolder.removeCallback(componentListener); surfaceHolder = null; } } private void setSurfaceTextureInternal(SurfaceTexture surfaceTexture) { Surface surface = new Surface(surfaceTexture); setVideoOutputInternal(surface); ownedSurface = surface; } private void setVideoOutputInternal(@Nullable Object videoOutput) { // Note: We don't turn this method into a no-op if the output is being replaced with itself so // as to ensure onRenderedFirstFrame callbacks are still called in this case. List<PlayerMessage> messages = new ArrayList<>(); for (Renderer renderer : renderers) { if (renderer.getTrackType() == TRACK_TYPE_VIDEO) { messages.add( createMessageInternal(renderer) .setType(MSG_SET_VIDEO_OUTPUT) .setPayload(videoOutput) .send()); } } boolean messageDeliveryTimedOut = false; if (this.videoOutput != null && this.videoOutput != videoOutput) { // We're replacing an output. Block to ensure that this output will not be accessed by the // renderers after this method returns. try { for (PlayerMessage message : messages) { message.blockUntilDelivered(detachSurfaceTimeoutMs); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException e) { messageDeliveryTimedOut = true; } if (this.videoOutput == ownedSurface) { // We're replacing a surface that we are responsible for releasing. ownedSurface.release(); ownedSurface = null; } } this.videoOutput = videoOutput; if (messageDeliveryTimedOut) { stop( /* reset= */ false, ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_DETACH_SURFACE), PlaybackException.ERROR_CODE_TIMEOUT)); } } /** * Sets the holder of the surface that will be displayed to the user, but which should * <em>not</em> be the output for video renderers. This case occurs when video frames need to be * rendered to an intermediate surface (which is not the one held by the provided holder). * * @param nonVideoOutputSurfaceHolder The holder of the surface that will eventually be displayed * to the user. */ private void setNonVideoOutputSurfaceHolderInternal(SurfaceHolder nonVideoOutputSurfaceHolder) { // Although we won't use the view's surface directly as the video output, still use the holder // to query the surface size, to be informed in changes to the size via componentListener, and // for equality checking in clearVideoSurfaceHolder. surfaceHolderSurfaceIsVideoOutput = false; surfaceHolder = nonVideoOutputSurfaceHolder; surfaceHolder.addCallback(componentListener); Surface surface = surfaceHolder.getSurface(); if (surface != null && surface.isValid()) { Rect surfaceSize = surfaceHolder.getSurfaceFrame(); maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height()); } else { maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } } private void maybeNotifySurfaceSizeChanged(int width, int height) { if (width != surfaceWidth || height != surfaceHeight) { surfaceWidth = width; surfaceHeight = height; analyticsCollector.onSurfaceSizeChanged(width, height); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onSurfaceSizeChanged(width, height); } } } private void sendVolumeToRenderers() { float scaledVolume = volume * audioFocusManager.getVolumeMultiplier(); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_VOLUME, scaledVolume); } private void notifySkipSilenceEnabledChanged() { analyticsCollector.onSkipSilenceEnabledChanged(skipSilenceEnabled); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onSkipSilenceEnabledChanged(skipSilenceEnabled); } } private void updatePlayWhenReady( boolean playWhenReady, @AudioFocusManager.PlayerCommand int playerCommand, @Player.PlayWhenReadyChangeReason int playWhenReadyChangeReason) { playWhenReady = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY; @PlaybackSuppressionReason int playbackSuppressionReason = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY ? Player.PLAYBACK_SUPPRESSION_REASON_TRANSIENT_AUDIO_FOCUS_LOSS : Player.PLAYBACK_SUPPRESSION_REASON_NONE; setPlayWhenReady(playWhenReady, playbackSuppressionReason, playWhenReadyChangeReason); } private void updateWakeAndWifiLock() { @State int playbackState = getPlaybackState(); switch (playbackState) { case Player.STATE_READY: case Player.STATE_BUFFERING: boolean isSleeping = experimentalIsSleepingForOffload(); wakeLockManager.setStayAwake(getPlayWhenReady() && !isSleeping); // The wifi lock is not released while sleeping to avoid interrupting downloads. wifiLockManager.setStayAwake(getPlayWhenReady()); break; case Player.STATE_ENDED: case Player.STATE_IDLE: wakeLockManager.setStayAwake(false); wifiLockManager.setStayAwake(false); break; default: throw new IllegalStateException(); } } private void verifyApplicationThread() { // The constructor may be executed on a background thread. Wait with accessing the player from // the app thread until the constructor finished executing. constructorFinished.blockUninterruptible(); if (Thread.currentThread() != getApplicationLooper().getThread()) { String message = Util.formatInvariant( "Player is accessed on the wrong thread.\n" + "Current thread: '%s'\n" + "Expected thread: '%s'\n" + "See https://exoplayer.dev/issues/player-accessed-on-wrong-thread", Thread.currentThread().getName(), getApplicationLooper().getThread().getName()); if (throwsWhenUsingWrongThread) { throw new IllegalStateException(message); } Log.w(TAG, message, hasNotifiedFullWrongThreadWarning ? null : new IllegalStateException()); hasNotifiedFullWrongThreadWarning = true; } } private void sendRendererMessage( @C.TrackType int trackType, int messageType, @Nullable Object payload) { for (Renderer renderer : renderers) { if (renderer.getTrackType() == trackType) { createMessageInternal(renderer).setType(messageType).setPayload(payload).send(); } } } /** * Initializes {@link #keepSessionIdAudioTrack} to keep an audio session ID alive. If the audio * session ID is {@link C#AUDIO_SESSION_ID_UNSET} then a new audio session ID is generated. * * <p>Use of this method is only required on API level 21 and earlier. * * @param audioSessionId The audio session ID, or {@link C#AUDIO_SESSION_ID_UNSET} to generate a * new one. * @return The audio session ID. */ private int initializeKeepSessionIdAudioTrack(int audioSessionId) { if (keepSessionIdAudioTrack != null && keepSessionIdAudioTrack.getAudioSessionId() != audioSessionId) { keepSessionIdAudioTrack.release(); keepSessionIdAudioTrack = null; } if (keepSessionIdAudioTrack == null) { int sampleRate = 4000; // Minimum sample rate supported by the platform. int channelConfig = AudioFormat.CHANNEL_OUT_MONO; @C.PcmEncoding int encoding = C.ENCODING_PCM_16BIT; int bufferSize = 2; // Use a two byte buffer, as it is not actually used for playback. keepSessionIdAudioTrack = new AudioTrack( C.STREAM_TYPE_DEFAULT, sampleRate, channelConfig, encoding, bufferSize, AudioTrack.MODE_STATIC, audioSessionId); } return keepSessionIdAudioTrack.getAudioSessionId(); } private void updatePriorityTaskManagerForIsLoadingChange(boolean isLoading) { if (priorityTaskManager != null) { if (isLoading && !isPriorityTaskManagerRegistered) { priorityTaskManager.add(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = true; } else if (!isLoading && isPriorityTaskManagerRegistered) { priorityTaskManager.remove(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = false; } } } private static DeviceInfo createDeviceInfo(StreamVolumeManager streamVolumeManager) { return new DeviceInfo( DeviceInfo.PLAYBACK_TYPE_LOCAL, streamVolumeManager.getMinVolume(), streamVolumeManager.getMaxVolume()); } private static int getPlayWhenReadyChangeReason(boolean playWhenReady, int playerCommand) { return playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY ? PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS : PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST; } private static boolean isPlaying(PlaybackInfo playbackInfo) { return playbackInfo.playbackState == Player.STATE_READY && playbackInfo.playWhenReady && playbackInfo.playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE; } private static final class MediaSourceHolderSnapshot implements MediaSourceInfoHolder { private final Object uid; private Timeline timeline; public MediaSourceHolderSnapshot(Object uid, Timeline timeline) { this.uid = uid; this.timeline = timeline; } @Override public Object getUid() { return uid; } @Override public Timeline getTimeline() { return timeline; } } private final class ComponentListener implements VideoRendererEventListener, AudioRendererEventListener, TextOutput, MetadataOutput, SurfaceHolder.Callback, TextureView.SurfaceTextureListener, SphericalGLSurfaceView.VideoSurfaceListener, AudioFocusManager.PlayerControl, AudioBecomingNoisyManager.EventListener, StreamVolumeManager.Listener, AudioOffloadListener { // VideoRendererEventListener implementation @Override public void onVideoEnabled(DecoderCounters counters) { videoDecoderCounters = counters; analyticsCollector.onVideoEnabled(counters); } @Override public void onVideoDecoderInitialized( String decoderName, long initializedTimestampMs, long initializationDurationMs) { analyticsCollector.onVideoDecoderInitialized( decoderName, initializedTimestampMs, initializationDurationMs); } @Override public void onVideoInputFormatChanged( Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) { videoFormat = format; analyticsCollector.onVideoInputFormatChanged(format, decoderReuseEvaluation); } @Override public void onDroppedFrames(int count, long elapsed) { analyticsCollector.onDroppedFrames(count, elapsed); } @Override public void onVideoSizeChanged(VideoSize videoSize) { ExoPlayerImpl.this.videoSize = videoSize; analyticsCollector.onVideoSizeChanged(videoSize); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onVideoSizeChanged(videoSize); } } @Override public void onRenderedFirstFrame(Object output, long renderTimeMs) { analyticsCollector.onRenderedFirstFrame(output, renderTimeMs); if (videoOutput == output) { // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onRenderedFirstFrame(); } } } @Override public void onVideoDecoderReleased(String decoderName) { analyticsCollector.onVideoDecoderReleased(decoderName); } @Override public void onVideoDisabled(DecoderCounters counters) { analyticsCollector.onVideoDisabled(counters); videoFormat = null; videoDecoderCounters = null; } @Override public void onVideoFrameProcessingOffset(long totalProcessingOffsetUs, int frameCount) { analyticsCollector.onVideoFrameProcessingOffset(totalProcessingOffsetUs, frameCount); } @Override public void onVideoCodecError(Exception videoCodecError) { analyticsCollector.onVideoCodecError(videoCodecError); } // AudioRendererEventListener implementation @Override public void onAudioEnabled(DecoderCounters counters) { audioDecoderCounters = counters; analyticsCollector.onAudioEnabled(counters); } @Override public void onAudioDecoderInitialized( String decoderName, long initializedTimestampMs, long initializationDurationMs) { analyticsCollector.onAudioDecoderInitialized( decoderName, initializedTimestampMs, initializationDurationMs); } @Override public void onAudioInputFormatChanged( Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) { audioFormat = format; analyticsCollector.onAudioInputFormatChanged(format, decoderReuseEvaluation); } @Override public void onAudioPositionAdvancing(long playoutStartSystemTimeMs) { analyticsCollector.onAudioPositionAdvancing(playoutStartSystemTimeMs); } @Override public void onAudioUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) { analyticsCollector.onAudioUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs); } @Override public void onAudioDecoderReleased(String decoderName) { analyticsCollector.onAudioDecoderReleased(decoderName); } @Override public void onAudioDisabled(DecoderCounters counters) { analyticsCollector.onAudioDisabled(counters); audioFormat = null; audioDecoderCounters = null; } @Override public void onSkipSilenceEnabledChanged(boolean skipSilenceEnabled) { if (ExoPlayerImpl.this.skipSilenceEnabled == skipSilenceEnabled) { return; } ExoPlayerImpl.this.skipSilenceEnabled = skipSilenceEnabled; notifySkipSilenceEnabledChanged(); } @Override public void onAudioSinkError(Exception audioSinkError) { analyticsCollector.onAudioSinkError(audioSinkError); } @Override public void onAudioCodecError(Exception audioCodecError) { analyticsCollector.onAudioCodecError(audioCodecError); } // TextOutput implementation @Override public void onCues(List<Cue> cues) { currentCues = cues; analyticsCollector.onCues(cues); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listeners : listenerArraySet) { listeners.onCues(cues); } } // MetadataOutput implementation @Override public void onMetadata(Metadata metadata) { analyticsCollector.onMetadata(metadata); ExoPlayerImpl.this.onMetadata(metadata); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onMetadata(metadata); } } // SurfaceHolder.Callback implementation @Override public void surfaceCreated(SurfaceHolder holder) { if (surfaceHolderSurfaceIsVideoOutput) { setVideoOutputInternal(holder.getSurface()); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { maybeNotifySurfaceSizeChanged(width, height); } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (surfaceHolderSurfaceIsVideoOutput) { setVideoOutputInternal(/* videoOutput= */ null); } maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } // TextureView.SurfaceTextureListener implementation @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { setSurfaceTextureInternal(surfaceTexture); maybeNotifySurfaceSizeChanged(width, height); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { maybeNotifySurfaceSizeChanged(width, height); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { // Do nothing. } // SphericalGLSurfaceView.VideoSurfaceListener @Override public void onVideoSurfaceCreated(Surface surface) { setVideoOutputInternal(surface); } @Override public void onVideoSurfaceDestroyed(Surface surface) { setVideoOutputInternal(/* videoOutput= */ null); } // AudioFocusManager.PlayerControl implementation @Override public void setVolumeMultiplier(float volumeMultiplier) { sendVolumeToRenderers(); } @Override public void executePlayerCommand(@AudioFocusManager.PlayerCommand int playerCommand) { boolean playWhenReady = getPlayWhenReady(); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } // AudioBecomingNoisyManager.EventListener implementation. @Override public void onAudioBecomingNoisy() { updatePlayWhenReady( /* playWhenReady= */ false, AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY, Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY); } // StreamVolumeManager.Listener implementation. @Override public void onStreamTypeChanged(@C.StreamType int streamType) { DeviceInfo deviceInfo = createDeviceInfo(streamVolumeManager); if (!deviceInfo.equals(ExoPlayerImpl.this.deviceInfo)) { ExoPlayerImpl.this.deviceInfo = deviceInfo; analyticsCollector.onDeviceInfoChanged(deviceInfo); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onDeviceInfoChanged(deviceInfo); } } } @Override public void onStreamVolumeChanged(int streamVolume, boolean streamMuted) { analyticsCollector.onDeviceVolumeChanged(streamVolume, streamMuted); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onDeviceVolumeChanged(streamVolume, streamMuted); } } // Player.AudioOffloadListener implementation. @Override public void onExperimentalSleepingForOffloadChanged(boolean sleepingForOffload) { updateWakeAndWifiLock(); } } /** Listeners that are called on the playback thread. */ private static final class FrameMetadataListener implements VideoFrameMetadataListener, CameraMotionListener, PlayerMessage.Target { public static final @MessageType int MSG_SET_VIDEO_FRAME_METADATA_LISTENER = Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER; public static final @MessageType int MSG_SET_CAMERA_MOTION_LISTENER = Renderer.MSG_SET_CAMERA_MOTION_LISTENER; public static final @MessageType int MSG_SET_SPHERICAL_SURFACE_VIEW = Renderer.MSG_CUSTOM_BASE; @Nullable private VideoFrameMetadataListener videoFrameMetadataListener; @Nullable private CameraMotionListener cameraMotionListener; @Nullable private VideoFrameMetadataListener internalVideoFrameMetadataListener; @Nullable private CameraMotionListener internalCameraMotionListener; @Override public void handleMessage(@MessageType int messageType, @Nullable Object message) { switch (messageType) { case MSG_SET_VIDEO_FRAME_METADATA_LISTENER: videoFrameMetadataListener = (VideoFrameMetadataListener) message; break; case MSG_SET_CAMERA_MOTION_LISTENER: cameraMotionListener = (CameraMotionListener) message; break; case MSG_SET_SPHERICAL_SURFACE_VIEW: @Nullable SphericalGLSurfaceView surfaceView = (SphericalGLSurfaceView) message; if (surfaceView == null) { internalVideoFrameMetadataListener = null; internalCameraMotionListener = null; } else { internalVideoFrameMetadataListener = surfaceView.getVideoFrameMetadataListener(); internalCameraMotionListener = surfaceView.getCameraMotionListener(); } break; case Renderer.MSG_SET_AUDIO_ATTRIBUTES: case Renderer.MSG_SET_AUDIO_SESSION_ID: case Renderer.MSG_SET_AUX_EFFECT_INFO: case Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY: case Renderer.MSG_SET_SCALING_MODE: case Renderer.MSG_SET_SKIP_SILENCE_ENABLED: case Renderer.MSG_SET_VIDEO_OUTPUT: case Renderer.MSG_SET_VOLUME: case Renderer.MSG_SET_WAKEUP_LISTENER: default: break; } } // VideoFrameMetadataListener @Override public void onVideoFrameAboutToBeRendered( long presentationTimeUs, long releaseTimeNs, Format format, @Nullable MediaFormat mediaFormat) { if (internalVideoFrameMetadataListener != null) { internalVideoFrameMetadataListener.onVideoFrameAboutToBeRendered( presentationTimeUs, releaseTimeNs, format, mediaFormat); } if (videoFrameMetadataListener != null) { videoFrameMetadataListener.onVideoFrameAboutToBeRendered( presentationTimeUs, releaseTimeNs, format, mediaFormat); } } // CameraMotionListener @Override public void onCameraMotion(long timeUs, float[] rotation) { if (internalCameraMotionListener != null) { internalCameraMotionListener.onCameraMotion(timeUs, rotation); } if (cameraMotionListener != null) { cameraMotionListener.onCameraMotion(timeUs, rotation); } } @Override public void onCameraMotionReset() { if (internalCameraMotionListener != null) { internalCameraMotionListener.onCameraMotionReset(); } if (cameraMotionListener != null) { cameraMotionListener.onCameraMotionReset(); } } } @RequiresApi(31) private static final class Api31 { private Api31() {} @DoNotInline public static PlayerId createPlayerId() { // TODO: Create a MediaMetricsListener and obtain LogSessionId from it. return new PlayerId(LogSessionId.LOG_SESSION_ID_NONE); } } }
libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlayerImpl.java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.media3.exoplayer; import static androidx.media3.common.C.TRACK_TYPE_AUDIO; import static androidx.media3.common.C.TRACK_TYPE_CAMERA_MOTION; import static androidx.media3.common.C.TRACK_TYPE_VIDEO; import static androidx.media3.common.Player.COMMAND_ADJUST_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_CHANGE_MEDIA_ITEMS; import static androidx.media3.common.Player.COMMAND_GET_AUDIO_ATTRIBUTES; import static androidx.media3.common.Player.COMMAND_GET_CURRENT_MEDIA_ITEM; import static androidx.media3.common.Player.COMMAND_GET_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_GET_MEDIA_ITEMS_METADATA; import static androidx.media3.common.Player.COMMAND_GET_TEXT; import static androidx.media3.common.Player.COMMAND_GET_TIMELINE; import static androidx.media3.common.Player.COMMAND_GET_TRACK_INFOS; import static androidx.media3.common.Player.COMMAND_GET_VOLUME; import static androidx.media3.common.Player.COMMAND_PLAY_PAUSE; import static androidx.media3.common.Player.COMMAND_PREPARE; import static androidx.media3.common.Player.COMMAND_SEEK_TO_DEFAULT_POSITION; import static androidx.media3.common.Player.COMMAND_SEEK_TO_MEDIA_ITEM; import static androidx.media3.common.Player.COMMAND_SET_DEVICE_VOLUME; import static androidx.media3.common.Player.COMMAND_SET_MEDIA_ITEMS_METADATA; import static androidx.media3.common.Player.COMMAND_SET_REPEAT_MODE; import static androidx.media3.common.Player.COMMAND_SET_SHUFFLE_MODE; import static androidx.media3.common.Player.COMMAND_SET_SPEED_AND_PITCH; import static androidx.media3.common.Player.COMMAND_SET_TRACK_SELECTION_PARAMETERS; import static androidx.media3.common.Player.COMMAND_SET_VIDEO_SURFACE; import static androidx.media3.common.Player.COMMAND_SET_VOLUME; import static androidx.media3.common.Player.COMMAND_STOP; import static androidx.media3.common.Player.DISCONTINUITY_REASON_AUTO_TRANSITION; import static androidx.media3.common.Player.DISCONTINUITY_REASON_INTERNAL; import static androidx.media3.common.Player.DISCONTINUITY_REASON_REMOVE; import static androidx.media3.common.Player.DISCONTINUITY_REASON_SEEK; import static androidx.media3.common.Player.EVENT_MEDIA_METADATA_CHANGED; import static androidx.media3.common.Player.EVENT_PLAYLIST_METADATA_CHANGED; import static androidx.media3.common.Player.EVENT_TRACK_SELECTION_PARAMETERS_CHANGED; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_AUTO; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT; import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_SEEK; import static androidx.media3.common.Player.PLAYBACK_SUPPRESSION_REASON_NONE; import static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS; import static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST; import static androidx.media3.common.Player.STATE_BUFFERING; import static androidx.media3.common.Player.STATE_ENDED; import static androidx.media3.common.Player.STATE_IDLE; import static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED; import static androidx.media3.common.Player.TIMELINE_CHANGE_REASON_SOURCE_UPDATE; import static androidx.media3.common.util.Assertions.checkNotNull; import static androidx.media3.common.util.Assertions.checkState; import static androidx.media3.common.util.Util.castNonNull; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_ATTRIBUTES; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUDIO_SESSION_ID; import static androidx.media3.exoplayer.Renderer.MSG_SET_AUX_EFFECT_INFO; import static androidx.media3.exoplayer.Renderer.MSG_SET_CAMERA_MOTION_LISTENER; import static androidx.media3.exoplayer.Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY; import static androidx.media3.exoplayer.Renderer.MSG_SET_SCALING_MODE; import static androidx.media3.exoplayer.Renderer.MSG_SET_SKIP_SILENCE_ENABLED; import static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER; import static androidx.media3.exoplayer.Renderer.MSG_SET_VIDEO_OUTPUT; import static androidx.media3.exoplayer.Renderer.MSG_SET_VOLUME; import static java.lang.Math.max; import static java.lang.Math.min; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.media.AudioFormat; import android.media.AudioTrack; import android.media.MediaFormat; import android.media.metrics.LogSessionId; import android.os.Handler; import android.os.Looper; import android.util.Pair; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import androidx.annotation.DoNotInline; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.media3.common.AudioAttributes; import androidx.media3.common.AuxEffectInfo; import androidx.media3.common.C; import androidx.media3.common.DeviceInfo; import androidx.media3.common.Format; import androidx.media3.common.IllegalSeekPositionException; import androidx.media3.common.MediaItem; import androidx.media3.common.MediaLibraryInfo; import androidx.media3.common.MediaMetadata; import androidx.media3.common.Metadata; import androidx.media3.common.PlaybackException; import androidx.media3.common.PlaybackParameters; import androidx.media3.common.Player; import androidx.media3.common.Player.Commands; import androidx.media3.common.Player.DiscontinuityReason; import androidx.media3.common.Player.Events; import androidx.media3.common.Player.Listener; import androidx.media3.common.Player.PlayWhenReadyChangeReason; import androidx.media3.common.Player.PlaybackSuppressionReason; import androidx.media3.common.Player.PositionInfo; import androidx.media3.common.Player.RepeatMode; import androidx.media3.common.Player.State; import androidx.media3.common.Player.TimelineChangeReason; import androidx.media3.common.PriorityTaskManager; import androidx.media3.common.Timeline; import androidx.media3.common.TrackGroup; import androidx.media3.common.TrackGroupArray; import androidx.media3.common.TrackSelectionArray; import androidx.media3.common.TrackSelectionParameters; import androidx.media3.common.TracksInfo; import androidx.media3.common.VideoSize; import androidx.media3.common.text.Cue; import androidx.media3.common.util.Assertions; import androidx.media3.common.util.Clock; import androidx.media3.common.util.ConditionVariable; import androidx.media3.common.util.HandlerWrapper; import androidx.media3.common.util.ListenerSet; import androidx.media3.common.util.Log; import androidx.media3.common.util.Util; import androidx.media3.exoplayer.ExoPlayer.AudioOffloadListener; import androidx.media3.exoplayer.PlayerMessage.Target; import androidx.media3.exoplayer.Renderer.MessageType; import androidx.media3.exoplayer.analytics.AnalyticsCollector; import androidx.media3.exoplayer.analytics.AnalyticsListener; import androidx.media3.exoplayer.analytics.PlayerId; import androidx.media3.exoplayer.audio.AudioRendererEventListener; import androidx.media3.exoplayer.metadata.MetadataOutput; import androidx.media3.exoplayer.source.MediaSource; import androidx.media3.exoplayer.source.MediaSource.MediaPeriodId; import androidx.media3.exoplayer.source.ShuffleOrder; import androidx.media3.exoplayer.text.TextOutput; import androidx.media3.exoplayer.trackselection.ExoTrackSelection; import androidx.media3.exoplayer.trackselection.TrackSelector; import androidx.media3.exoplayer.trackselection.TrackSelectorResult; import androidx.media3.exoplayer.upstream.BandwidthMeter; import androidx.media3.exoplayer.video.VideoDecoderOutputBufferRenderer; import androidx.media3.exoplayer.video.VideoFrameMetadataListener; import androidx.media3.exoplayer.video.VideoRendererEventListener; import androidx.media3.exoplayer.video.spherical.CameraMotionListener; import androidx.media3.exoplayer.video.spherical.SphericalGLSurfaceView; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeoutException; /** A helper class for the {@link SimpleExoPlayer} implementation of {@link ExoPlayer}. */ /* package */ final class ExoPlayerImpl { static { MediaLibraryInfo.registerModule("media3.exoplayer"); } private static final String TAG = "ExoPlayerImpl"; /** * This empty track selector result can only be used for {@link PlaybackInfo#trackSelectorResult} * when the player does not have any track selection made (such as when player is reset, or when * player seeks to an unprepared period). It will not be used as result of any {@link * TrackSelector#selectTracks(RendererCapabilities[], TrackGroupArray, MediaPeriodId, Timeline)} * operation. */ /* package */ final TrackSelectorResult emptyTrackSelectorResult; /* package */ final Commands permanentAvailableCommands; private final ConditionVariable constructorFinished; private final Context applicationContext; private final Player wrappingPlayer; private final Renderer[] renderers; private final TrackSelector trackSelector; private final HandlerWrapper playbackInfoUpdateHandler; private final ExoPlayerImplInternal.PlaybackInfoUpdateListener playbackInfoUpdateListener; private final ExoPlayerImplInternal internalPlayer; private final ListenerSet<Listener> listeners; // TODO(b/187152483): Remove this once all events are dispatched via ListenerSet. private final CopyOnWriteArraySet<Listener> listenerArraySet; private final CopyOnWriteArraySet<AudioOffloadListener> audioOffloadListeners; private final Timeline.Period period; private final Timeline.Window window; private final List<MediaSourceHolderSnapshot> mediaSourceHolderSnapshots; private final boolean useLazyPreparation; private final MediaSource.Factory mediaSourceFactory; private final AnalyticsCollector analyticsCollector; private final Looper applicationLooper; private final BandwidthMeter bandwidthMeter; private final long seekBackIncrementMs; private final long seekForwardIncrementMs; private final Clock clock; private final ComponentListener componentListener; private final FrameMetadataListener frameMetadataListener; private final AudioBecomingNoisyManager audioBecomingNoisyManager; private final AudioFocusManager audioFocusManager; private final StreamVolumeManager streamVolumeManager; private final WakeLockManager wakeLockManager; private final WifiLockManager wifiLockManager; private final long detachSurfaceTimeoutMs; private @RepeatMode int repeatMode; private boolean shuffleModeEnabled; private int pendingOperationAcks; private @DiscontinuityReason int pendingDiscontinuityReason; private boolean pendingDiscontinuity; private @PlayWhenReadyChangeReason int pendingPlayWhenReadyChangeReason; private boolean foregroundMode; private SeekParameters seekParameters; private ShuffleOrder shuffleOrder; private boolean pauseAtEndOfMediaItems; private Commands availableCommands; private MediaMetadata mediaMetadata; private MediaMetadata playlistMetadata; @Nullable private Format videoFormat; @Nullable private Format audioFormat; @Nullable private AudioTrack keepSessionIdAudioTrack; @Nullable private Object videoOutput; @Nullable private Surface ownedSurface; @Nullable private SurfaceHolder surfaceHolder; @Nullable private SphericalGLSurfaceView sphericalGLSurfaceView; private boolean surfaceHolderSurfaceIsVideoOutput; @Nullable private TextureView textureView; private @C.VideoScalingMode int videoScalingMode; private @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy; private int surfaceWidth; private int surfaceHeight; @Nullable private DecoderCounters videoDecoderCounters; @Nullable private DecoderCounters audioDecoderCounters; private int audioSessionId; private AudioAttributes audioAttributes; private float volume; private boolean skipSilenceEnabled; private List<Cue> currentCues; @Nullable private VideoFrameMetadataListener videoFrameMetadataListener; @Nullable private CameraMotionListener cameraMotionListener; private boolean throwsWhenUsingWrongThread; private boolean hasNotifiedFullWrongThreadWarning; @Nullable private PriorityTaskManager priorityTaskManager; private boolean isPriorityTaskManagerRegistered; private boolean playerReleased; private DeviceInfo deviceInfo; private VideoSize videoSize; // MediaMetadata built from static (TrackGroup Format) and dynamic (onMetadata(Metadata)) metadata // sources. private MediaMetadata staticAndDynamicMediaMetadata; // Playback information when there is no pending seek/set source operation. private PlaybackInfo playbackInfo; // Playback information when there is a pending seek/set source operation. private int maskingWindowIndex; private int maskingPeriodIndex; private long maskingWindowPositionMs; @SuppressLint("HandlerLeak") public ExoPlayerImpl(ExoPlayer.Builder builder, Player wrappingPlayer) { constructorFinished = new ConditionVariable(); try { Log.i( TAG, "Init " + Integer.toHexString(System.identityHashCode(this)) + " [" + MediaLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "]"); applicationContext = builder.context.getApplicationContext(); analyticsCollector = builder.analyticsCollectorSupplier.get(); priorityTaskManager = builder.priorityTaskManager; audioAttributes = builder.audioAttributes; videoScalingMode = builder.videoScalingMode; videoChangeFrameRateStrategy = builder.videoChangeFrameRateStrategy; skipSilenceEnabled = builder.skipSilenceEnabled; detachSurfaceTimeoutMs = builder.detachSurfaceTimeoutMs; componentListener = new ComponentListener(); frameMetadataListener = new FrameMetadataListener(); Handler eventHandler = new Handler(builder.looper); renderers = builder .renderersFactorySupplier .get() .createRenderers( eventHandler, componentListener, componentListener, componentListener, componentListener); checkState(renderers.length > 0); this.trackSelector = builder.trackSelectorSupplier.get(); this.mediaSourceFactory = builder.mediaSourceFactorySupplier.get(); this.bandwidthMeter = builder.bandwidthMeterSupplier.get(); this.useLazyPreparation = builder.useLazyPreparation; this.seekParameters = builder.seekParameters; this.seekBackIncrementMs = builder.seekBackIncrementMs; this.seekForwardIncrementMs = builder.seekForwardIncrementMs; this.pauseAtEndOfMediaItems = builder.pauseAtEndOfMediaItems; this.applicationLooper = builder.looper; this.clock = builder.clock; this.wrappingPlayer = wrappingPlayer; listeners = new ListenerSet<>( applicationLooper, clock, (listener, flags) -> listener.onEvents(wrappingPlayer, new Events(flags))); listenerArraySet = new CopyOnWriteArraySet<>(); audioOffloadListeners = new CopyOnWriteArraySet<>(); mediaSourceHolderSnapshots = new ArrayList<>(); shuffleOrder = new ShuffleOrder.DefaultShuffleOrder(/* length= */ 0); emptyTrackSelectorResult = new TrackSelectorResult( new RendererConfiguration[renderers.length], new ExoTrackSelection[renderers.length], TracksInfo.EMPTY, /* info= */ null); period = new Timeline.Period(); window = new Timeline.Window(); permanentAvailableCommands = new Commands.Builder() .addAll( COMMAND_PLAY_PAUSE, COMMAND_PREPARE, COMMAND_STOP, COMMAND_SET_SPEED_AND_PITCH, COMMAND_SET_SHUFFLE_MODE, COMMAND_SET_REPEAT_MODE, COMMAND_GET_CURRENT_MEDIA_ITEM, COMMAND_GET_TIMELINE, COMMAND_GET_MEDIA_ITEMS_METADATA, COMMAND_SET_MEDIA_ITEMS_METADATA, COMMAND_CHANGE_MEDIA_ITEMS, COMMAND_GET_TRACK_INFOS, COMMAND_GET_AUDIO_ATTRIBUTES, COMMAND_GET_VOLUME, COMMAND_GET_DEVICE_VOLUME, COMMAND_SET_VOLUME, COMMAND_SET_DEVICE_VOLUME, COMMAND_ADJUST_DEVICE_VOLUME, COMMAND_SET_VIDEO_SURFACE, COMMAND_GET_TEXT) .addIf( COMMAND_SET_TRACK_SELECTION_PARAMETERS, trackSelector.isSetParametersSupported()) .build(); availableCommands = new Commands.Builder() .addAll(permanentAvailableCommands) .add(COMMAND_SEEK_TO_DEFAULT_POSITION) .add(COMMAND_SEEK_TO_MEDIA_ITEM) .build(); playbackInfoUpdateHandler = clock.createHandler(applicationLooper, /* callback= */ null); playbackInfoUpdateListener = playbackInfoUpdate -> playbackInfoUpdateHandler.post(() -> handlePlaybackInfo(playbackInfoUpdate)); playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult); analyticsCollector.setPlayer(wrappingPlayer, applicationLooper); PlayerId playerId = Util.SDK_INT < 31 ? new PlayerId() : Api31.createPlayerId(); internalPlayer = new ExoPlayerImplInternal( renderers, trackSelector, emptyTrackSelectorResult, builder.loadControlSupplier.get(), bandwidthMeter, repeatMode, shuffleModeEnabled, analyticsCollector, seekParameters, builder.livePlaybackSpeedControl, builder.releaseTimeoutMs, pauseAtEndOfMediaItems, applicationLooper, clock, playbackInfoUpdateListener, playerId); volume = 1; repeatMode = Player.REPEAT_MODE_OFF; mediaMetadata = MediaMetadata.EMPTY; playlistMetadata = MediaMetadata.EMPTY; staticAndDynamicMediaMetadata = MediaMetadata.EMPTY; maskingWindowIndex = C.INDEX_UNSET; if (Util.SDK_INT < 21) { audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET); } else { audioSessionId = Util.generateAudioSessionIdV21(applicationContext); } currentCues = ImmutableList.of(); throwsWhenUsingWrongThread = true; listeners.add(analyticsCollector); bandwidthMeter.addEventListener(new Handler(applicationLooper), analyticsCollector); listeners.add(componentListener); addAudioOffloadListener(componentListener); if (builder.foregroundModeTimeoutMs > 0) { experimentalSetForegroundModeTimeoutMs(builder.foregroundModeTimeoutMs); } audioBecomingNoisyManager = new AudioBecomingNoisyManager(builder.context, eventHandler, componentListener); audioBecomingNoisyManager.setEnabled(builder.handleAudioBecomingNoisy); audioFocusManager = new AudioFocusManager(builder.context, eventHandler, componentListener); audioFocusManager.setAudioAttributes(builder.handleAudioFocus ? audioAttributes : null); streamVolumeManager = new StreamVolumeManager(builder.context, eventHandler, componentListener); streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage)); wakeLockManager = new WakeLockManager(builder.context); wakeLockManager.setEnabled(builder.wakeMode != C.WAKE_MODE_NONE); wifiLockManager = new WifiLockManager(builder.context); wifiLockManager.setEnabled(builder.wakeMode == C.WAKE_MODE_NETWORK); deviceInfo = createDeviceInfo(streamVolumeManager); videoSize = VideoSize.UNKNOWN; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode); sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled); sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_VIDEO_FRAME_METADATA_LISTENER, frameMetadataListener); sendRendererMessage( TRACK_TYPE_CAMERA_MOTION, MSG_SET_CAMERA_MOTION_LISTENER, frameMetadataListener); } finally { constructorFinished.open(); } } /** * Sets a limit on the time a call to {@link #setForegroundMode} can spend. If a call to {@link * #setForegroundMode} takes more than {@code timeoutMs} milliseconds to complete, the player will * raise an error via {@link Player.Listener#onPlayerError}. * * <p>This method is experimental, and will be renamed or removed in a future release. It should * only be called before the player is used. * * @param timeoutMs The time limit in milliseconds. */ public void experimentalSetForegroundModeTimeoutMs(long timeoutMs) { internalPlayer.experimentalSetForegroundModeTimeoutMs(timeoutMs); } public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) { verifyApplicationThread(); internalPlayer.experimentalSetOffloadSchedulingEnabled(offloadSchedulingEnabled); } public boolean experimentalIsSleepingForOffload() { verifyApplicationThread(); return playbackInfo.sleepingForOffload; } public Looper getPlaybackLooper() { // Don't verify application thread. We allow calls to this method from any thread. return internalPlayer.getPlaybackLooper(); } public Looper getApplicationLooper() { // Don't verify application thread. We allow calls to this method from any thread. return applicationLooper; } public Clock getClock() { // Don't verify application thread. We allow calls to this method from any thread. return clock; } public void addAudioOffloadListener(AudioOffloadListener listener) { // Don't verify application thread. We allow calls to this method from any thread. audioOffloadListeners.add(listener); } public void removeAudioOffloadListener(AudioOffloadListener listener) { // Don't verify application thread. We allow calls to this method from any thread. audioOffloadListeners.remove(listener); } public Commands getAvailableCommands() { verifyApplicationThread(); return availableCommands; } public @State int getPlaybackState() { verifyApplicationThread(); return playbackInfo.playbackState; } public @PlaybackSuppressionReason int getPlaybackSuppressionReason() { verifyApplicationThread(); return playbackInfo.playbackSuppressionReason; } @Nullable public ExoPlaybackException getPlayerError() { verifyApplicationThread(); return playbackInfo.playbackError; } /** @deprecated Use {@link #prepare()} instead. */ @Deprecated public void retry() { prepare(); } public void prepare() { verifyApplicationThread(); boolean playWhenReady = getPlayWhenReady(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, Player.STATE_BUFFERING); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); if (playbackInfo.playbackState != Player.STATE_IDLE) { return; } PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlaybackError(null); playbackInfo = playbackInfo.copyWithPlaybackState( playbackInfo.timeline.isEmpty() ? STATE_ENDED : STATE_BUFFERING); // Trigger internal prepare first before updating the playback info and notifying external // listeners to ensure that new operations issued in the listener notifications reach the // player after this prepare. The internal player can't change the playback info immediately // because it uses a callback. pendingOperationAcks++; internalPlayer.prepare(); updatePlaybackInfo( playbackInfo, /* ignored */ TIMELINE_CHANGE_REASON_SOURCE_UPDATE, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } /** * @deprecated Use {@link #setMediaSource(MediaSource)} and {@link ExoPlayer#prepare()} instead. */ @Deprecated public void prepare(MediaSource mediaSource) { verifyApplicationThread(); setMediaSource(mediaSource); prepare(); } /** * @deprecated Use {@link #setMediaSource(MediaSource, boolean)} and {@link ExoPlayer#prepare()} * instead. */ @Deprecated public void prepare(MediaSource mediaSource, boolean resetPosition, boolean resetState) { verifyApplicationThread(); setMediaSource(mediaSource, resetPosition); prepare(); } public void setMediaItems(List<MediaItem> mediaItems, boolean resetPosition) { verifyApplicationThread(); setMediaSources(createMediaSources(mediaItems), resetPosition); } public void setMediaItems(List<MediaItem> mediaItems, int startIndex, long startPositionMs) { verifyApplicationThread(); setMediaSources(createMediaSources(mediaItems), startIndex, startPositionMs); } public void setMediaSource(MediaSource mediaSource) { verifyApplicationThread(); setMediaSources(Collections.singletonList(mediaSource)); } public void setMediaSource(MediaSource mediaSource, long startPositionMs) { verifyApplicationThread(); setMediaSources( Collections.singletonList(mediaSource), /* startWindowIndex= */ 0, startPositionMs); } public void setMediaSource(MediaSource mediaSource, boolean resetPosition) { verifyApplicationThread(); setMediaSources(Collections.singletonList(mediaSource), resetPosition); } public void setMediaSources(List<MediaSource> mediaSources) { verifyApplicationThread(); setMediaSources(mediaSources, /* resetPosition= */ true); } public void setMediaSources(List<MediaSource> mediaSources, boolean resetPosition) { verifyApplicationThread(); setMediaSourcesInternal( mediaSources, /* startWindowIndex= */ C.INDEX_UNSET, /* startPositionMs= */ C.TIME_UNSET, /* resetToDefaultPosition= */ resetPosition); } public void setMediaSources( List<MediaSource> mediaSources, int startWindowIndex, long startPositionMs) { verifyApplicationThread(); setMediaSourcesInternal( mediaSources, startWindowIndex, startPositionMs, /* resetToDefaultPosition= */ false); } public void addMediaItems(int index, List<MediaItem> mediaItems) { verifyApplicationThread(); index = min(index, mediaSourceHolderSnapshots.size()); addMediaSources(index, createMediaSources(mediaItems)); } public void addMediaSource(MediaSource mediaSource) { verifyApplicationThread(); addMediaSources(Collections.singletonList(mediaSource)); } public void addMediaSource(int index, MediaSource mediaSource) { verifyApplicationThread(); addMediaSources(index, Collections.singletonList(mediaSource)); } public void addMediaSources(List<MediaSource> mediaSources) { verifyApplicationThread(); addMediaSources(/* index= */ mediaSourceHolderSnapshots.size(), mediaSources); } public void addMediaSources(int index, List<MediaSource> mediaSources) { verifyApplicationThread(); Assertions.checkArgument(index >= 0); Timeline oldTimeline = getCurrentTimeline(); pendingOperationAcks++; List<MediaSourceList.MediaSourceHolder> holders = addMediaSourceHolders(index, mediaSources); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); internalPlayer.addMediaSources(index, holders, shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void removeMediaItems(int fromIndex, int toIndex) { verifyApplicationThread(); toIndex = min(toIndex, mediaSourceHolderSnapshots.size()); PlaybackInfo newPlaybackInfo = removeMediaItemsInternal(fromIndex, toIndex); boolean positionDiscontinuity = !newPlaybackInfo.periodId.periodUid.equals(playbackInfo.periodId.periodUid); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), /* ignored */ C.INDEX_UNSET); } public void moveMediaItems(int fromIndex, int toIndex, int newFromIndex) { verifyApplicationThread(); Assertions.checkArgument( fromIndex >= 0 && fromIndex <= toIndex && toIndex <= mediaSourceHolderSnapshots.size() && newFromIndex >= 0); Timeline oldTimeline = getCurrentTimeline(); pendingOperationAcks++; newFromIndex = min(newFromIndex, mediaSourceHolderSnapshots.size() - (toIndex - fromIndex)); Util.moveItems(mediaSourceHolderSnapshots, fromIndex, toIndex, newFromIndex); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); internalPlayer.moveMediaSources(fromIndex, toIndex, newFromIndex, shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void setShuffleOrder(ShuffleOrder shuffleOrder) { verifyApplicationThread(); Timeline timeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs( timeline, getCurrentMediaItemIndex(), getCurrentPosition())); pendingOperationAcks++; this.shuffleOrder = shuffleOrder; internalPlayer.setShuffleOrder(shuffleOrder); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public void setPauseAtEndOfMediaItems(boolean pauseAtEndOfMediaItems) { verifyApplicationThread(); if (this.pauseAtEndOfMediaItems == pauseAtEndOfMediaItems) { return; } this.pauseAtEndOfMediaItems = pauseAtEndOfMediaItems; internalPlayer.setPauseAtEndOfWindow(pauseAtEndOfMediaItems); } public boolean getPauseAtEndOfMediaItems() { verifyApplicationThread(); return pauseAtEndOfMediaItems; } public void setPlayWhenReady(boolean playWhenReady) { verifyApplicationThread(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState()); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } public void setPlayWhenReady( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason, @PlayWhenReadyChangeReason int playWhenReadyChangeReason) { if (playbackInfo.playWhenReady == playWhenReady && playbackInfo.playbackSuppressionReason == playbackSuppressionReason) { return; } pendingOperationAcks++; PlaybackInfo playbackInfo = this.playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason); internalPlayer.setPlayWhenReady(playWhenReady, playbackSuppressionReason); updatePlaybackInfo( playbackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, playWhenReadyChangeReason, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public boolean getPlayWhenReady() { verifyApplicationThread(); return playbackInfo.playWhenReady; } public void setRepeatMode(@RepeatMode int repeatMode) { verifyApplicationThread(); if (this.repeatMode != repeatMode) { this.repeatMode = repeatMode; internalPlayer.setRepeatMode(repeatMode); listeners.queueEvent( Player.EVENT_REPEAT_MODE_CHANGED, listener -> listener.onRepeatModeChanged(repeatMode)); updateAvailableCommands(); listeners.flushEvents(); } } public @RepeatMode int getRepeatMode() { verifyApplicationThread(); return repeatMode; } public void setShuffleModeEnabled(boolean shuffleModeEnabled) { verifyApplicationThread(); if (this.shuffleModeEnabled != shuffleModeEnabled) { this.shuffleModeEnabled = shuffleModeEnabled; internalPlayer.setShuffleModeEnabled(shuffleModeEnabled); listeners.queueEvent( Player.EVENT_SHUFFLE_MODE_ENABLED_CHANGED, listener -> listener.onShuffleModeEnabledChanged(shuffleModeEnabled)); updateAvailableCommands(); listeners.flushEvents(); } } public boolean getShuffleModeEnabled() { verifyApplicationThread(); return shuffleModeEnabled; } public boolean isLoading() { verifyApplicationThread(); return playbackInfo.isLoading; } public void seekTo(int mediaItemIndex, long positionMs) { verifyApplicationThread(); analyticsCollector.notifySeekStarted(); Timeline timeline = playbackInfo.timeline; if (mediaItemIndex < 0 || (!timeline.isEmpty() && mediaItemIndex >= timeline.getWindowCount())) { throw new IllegalSeekPositionException(timeline, mediaItemIndex, positionMs); } pendingOperationAcks++; if (isPlayingAd()) { // TODO: Investigate adding support for seeking during ads. This is complicated to do in // general because the midroll ad preceding the seek destination must be played before the // content position can be played, if a different ad is playing at the moment. Log.w(TAG, "seekTo ignored because an ad is playing"); ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate = new ExoPlayerImplInternal.PlaybackInfoUpdate(this.playbackInfo); playbackInfoUpdate.incrementPendingOperationAcks(1); playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate); return; } @Player.State int newPlaybackState = getPlaybackState() == Player.STATE_IDLE ? Player.STATE_IDLE : STATE_BUFFERING; int oldMaskingMediaItemIndex = getCurrentMediaItemIndex(); PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackState(newPlaybackState); newPlaybackInfo = maskTimelineAndPosition( newPlaybackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs(timeline, mediaItemIndex, positionMs)); internalPlayer.seekTo(timeline, mediaItemIndex, Util.msToUs(positionMs)); updatePlaybackInfo( newPlaybackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ true, /* positionDiscontinuity= */ true, /* positionDiscontinuityReason= */ DISCONTINUITY_REASON_SEEK, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), oldMaskingMediaItemIndex); } public long getSeekBackIncrement() { verifyApplicationThread(); return seekBackIncrementMs; } public long getSeekForwardIncrement() { verifyApplicationThread(); return seekForwardIncrementMs; } public long getMaxSeekToPreviousPosition() { verifyApplicationThread(); return C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS; } public void setPlaybackParameters(PlaybackParameters playbackParameters) { verifyApplicationThread(); if (playbackParameters == null) { playbackParameters = PlaybackParameters.DEFAULT; } if (playbackInfo.playbackParameters.equals(playbackParameters)) { return; } PlaybackInfo newPlaybackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters); pendingOperationAcks++; internalPlayer.setPlaybackParameters(playbackParameters); updatePlaybackInfo( newPlaybackInfo, /* ignored */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ false, /* ignored */ DISCONTINUITY_REASON_INTERNAL, /* ignored */ C.TIME_UNSET, /* ignored */ C.INDEX_UNSET); } public PlaybackParameters getPlaybackParameters() { verifyApplicationThread(); return playbackInfo.playbackParameters; } public void setSeekParameters(@Nullable SeekParameters seekParameters) { verifyApplicationThread(); if (seekParameters == null) { seekParameters = SeekParameters.DEFAULT; } if (!this.seekParameters.equals(seekParameters)) { this.seekParameters = seekParameters; internalPlayer.setSeekParameters(seekParameters); } } public SeekParameters getSeekParameters() { verifyApplicationThread(); return seekParameters; } public void setForegroundMode(boolean foregroundMode) { verifyApplicationThread(); if (this.foregroundMode != foregroundMode) { this.foregroundMode = foregroundMode; if (!internalPlayer.setForegroundMode(foregroundMode)) { // One of the renderers timed out releasing its resources. stop( /* reset= */ false, ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_SET_FOREGROUND_MODE), PlaybackException.ERROR_CODE_TIMEOUT)); } } } public void stop() { stop(/* reset= */ false); } public void stop(boolean reset) { verifyApplicationThread(); audioFocusManager.updateAudioFocus(getPlayWhenReady(), Player.STATE_IDLE); stop(reset, /* error= */ null); currentCues = ImmutableList.of(); } /** * Stops the player. * * @param reset Whether the playlist should be cleared and whether the playback position and * playback error should be reset. * @param error An optional {@link ExoPlaybackException} to set. */ public void stop(boolean reset, @Nullable ExoPlaybackException error) { PlaybackInfo playbackInfo; if (reset) { playbackInfo = removeMediaItemsInternal( /* fromIndex= */ 0, /* toIndex= */ mediaSourceHolderSnapshots.size()); playbackInfo = playbackInfo.copyWithPlaybackError(null); } else { playbackInfo = this.playbackInfo.copyWithLoadingMediaPeriodId(this.playbackInfo.periodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; playbackInfo.totalBufferedDurationUs = 0; } playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE); if (error != null) { playbackInfo = playbackInfo.copyWithPlaybackError(error); } pendingOperationAcks++; internalPlayer.stop(); boolean positionDiscontinuity = playbackInfo.timeline.isEmpty() && !this.playbackInfo.timeline.isEmpty(); updatePlaybackInfo( playbackInfo, TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(playbackInfo), /* ignored */ C.INDEX_UNSET); } public void release() { Log.i( TAG, "Release " + Integer.toHexString(System.identityHashCode(this)) + " [" + MediaLibraryInfo.VERSION_SLASHY + "] [" + Util.DEVICE_DEBUG_INFO + "] [" + MediaLibraryInfo.registeredModules() + "]"); verifyApplicationThread(); if (Util.SDK_INT < 21 && keepSessionIdAudioTrack != null) { keepSessionIdAudioTrack.release(); keepSessionIdAudioTrack = null; } audioBecomingNoisyManager.setEnabled(false); streamVolumeManager.release(); wakeLockManager.setStayAwake(false); wifiLockManager.setStayAwake(false); audioFocusManager.release(); if (!internalPlayer.release()) { // One of the renderers timed out releasing its resources. listeners.sendEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerError( ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_RELEASE), PlaybackException.ERROR_CODE_TIMEOUT))); } listeners.release(); playbackInfoUpdateHandler.removeCallbacksAndMessages(null); bandwidthMeter.removeEventListener(analyticsCollector); playbackInfo = playbackInfo.copyWithPlaybackState(Player.STATE_IDLE); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(playbackInfo.periodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; playbackInfo.totalBufferedDurationUs = 0; analyticsCollector.release(); removeSurfaceCallbacks(); if (ownedSurface != null) { ownedSurface.release(); ownedSurface = null; } if (isPriorityTaskManagerRegistered) { checkNotNull(priorityTaskManager).remove(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = false; } currentCues = ImmutableList.of(); playerReleased = true; } public PlayerMessage createMessage(Target target) { verifyApplicationThread(); return createMessageInternal(target); } public int getCurrentPeriodIndex() { verifyApplicationThread(); if (playbackInfo.timeline.isEmpty()) { return maskingPeriodIndex; } else { return playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid); } } public int getCurrentMediaItemIndex() { verifyApplicationThread(); int currentWindowIndex = getCurrentWindowIndexInternal(); return currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex; } public long getDuration() { verifyApplicationThread(); if (isPlayingAd()) { MediaPeriodId periodId = playbackInfo.periodId; playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period); long adDurationUs = period.getAdDurationUs(periodId.adGroupIndex, periodId.adIndexInAdGroup); return Util.usToMs(adDurationUs); } return getContentDuration(); } private long getContentDuration() { Timeline timeline = getCurrentTimeline(); return timeline.isEmpty() ? C.TIME_UNSET : timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs(); } public long getCurrentPosition() { verifyApplicationThread(); return Util.usToMs(getCurrentPositionUsInternal(playbackInfo)); } public long getBufferedPosition() { verifyApplicationThread(); if (isPlayingAd()) { return playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId) ? Util.usToMs(playbackInfo.bufferedPositionUs) : getDuration(); } return getContentBufferedPosition(); } public long getTotalBufferedDuration() { verifyApplicationThread(); return Util.usToMs(playbackInfo.totalBufferedDurationUs); } public boolean isPlayingAd() { verifyApplicationThread(); return playbackInfo.periodId.isAd(); } public int getCurrentAdGroupIndex() { verifyApplicationThread(); return isPlayingAd() ? playbackInfo.periodId.adGroupIndex : C.INDEX_UNSET; } public int getCurrentAdIndexInAdGroup() { verifyApplicationThread(); return isPlayingAd() ? playbackInfo.periodId.adIndexInAdGroup : C.INDEX_UNSET; } public long getContentPosition() { verifyApplicationThread(); if (isPlayingAd()) { playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period); return playbackInfo.requestedContentPositionUs == C.TIME_UNSET ? playbackInfo .timeline .getWindow(getCurrentMediaItemIndex(), window) .getDefaultPositionMs() : period.getPositionInWindowMs() + Util.usToMs(playbackInfo.requestedContentPositionUs); } else { return getCurrentPosition(); } } public long getContentBufferedPosition() { verifyApplicationThread(); if (playbackInfo.timeline.isEmpty()) { return maskingWindowPositionMs; } if (playbackInfo.loadingMediaPeriodId.windowSequenceNumber != playbackInfo.periodId.windowSequenceNumber) { return playbackInfo.timeline.getWindow(getCurrentMediaItemIndex(), window).getDurationMs(); } long contentBufferedPositionUs = playbackInfo.bufferedPositionUs; if (playbackInfo.loadingMediaPeriodId.isAd()) { Timeline.Period loadingPeriod = playbackInfo.timeline.getPeriodByUid(playbackInfo.loadingMediaPeriodId.periodUid, period); contentBufferedPositionUs = loadingPeriod.getAdGroupTimeUs(playbackInfo.loadingMediaPeriodId.adGroupIndex); if (contentBufferedPositionUs == C.TIME_END_OF_SOURCE) { contentBufferedPositionUs = loadingPeriod.durationUs; } } return Util.usToMs( periodPositionUsToWindowPositionUs( playbackInfo.timeline, playbackInfo.loadingMediaPeriodId, contentBufferedPositionUs)); } public int getRendererCount() { verifyApplicationThread(); return renderers.length; } public @C.TrackType int getRendererType(int index) { verifyApplicationThread(); return renderers[index].getTrackType(); } public Renderer getRenderer(int index) { verifyApplicationThread(); return renderers[index]; } public TrackSelector getTrackSelector() { verifyApplicationThread(); return trackSelector; } public TrackGroupArray getCurrentTrackGroups() { verifyApplicationThread(); return playbackInfo.trackGroups; } public TrackSelectionArray getCurrentTrackSelections() { verifyApplicationThread(); return new TrackSelectionArray(playbackInfo.trackSelectorResult.selections); } public TracksInfo getCurrentTracksInfo() { verifyApplicationThread(); return playbackInfo.trackSelectorResult.tracksInfo; } public TrackSelectionParameters getTrackSelectionParameters() { verifyApplicationThread(); return trackSelector.getParameters(); } public void setTrackSelectionParameters(TrackSelectionParameters parameters) { verifyApplicationThread(); if (!trackSelector.isSetParametersSupported() || parameters.equals(trackSelector.getParameters())) { return; } trackSelector.setParameters(parameters); listeners.queueEvent( EVENT_TRACK_SELECTION_PARAMETERS_CHANGED, listener -> listener.onTrackSelectionParametersChanged(parameters)); } public MediaMetadata getMediaMetadata() { verifyApplicationThread(); return mediaMetadata; } private void onMetadata(Metadata metadata) { staticAndDynamicMediaMetadata = staticAndDynamicMediaMetadata.buildUpon().populateFromMetadata(metadata).build(); MediaMetadata newMediaMetadata = buildUpdatedMediaMetadata(); if (newMediaMetadata.equals(mediaMetadata)) { return; } mediaMetadata = newMediaMetadata; listeners.sendEvent( EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(mediaMetadata)); } public MediaMetadata getPlaylistMetadata() { verifyApplicationThread(); return playlistMetadata; } public void setPlaylistMetadata(MediaMetadata playlistMetadata) { verifyApplicationThread(); checkNotNull(playlistMetadata); if (playlistMetadata.equals(this.playlistMetadata)) { return; } this.playlistMetadata = playlistMetadata; listeners.sendEvent( EVENT_PLAYLIST_METADATA_CHANGED, listener -> listener.onPlaylistMetadataChanged(this.playlistMetadata)); } public Timeline getCurrentTimeline() { verifyApplicationThread(); return playbackInfo.timeline; } public void setVideoScalingMode(@C.VideoScalingMode int videoScalingMode) { verifyApplicationThread(); this.videoScalingMode = videoScalingMode; sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_SCALING_MODE, videoScalingMode); } public @C.VideoScalingMode int getVideoScalingMode() { return videoScalingMode; } public void setVideoChangeFrameRateStrategy( @C.VideoChangeFrameRateStrategy int videoChangeFrameRateStrategy) { verifyApplicationThread(); if (this.videoChangeFrameRateStrategy == videoChangeFrameRateStrategy) { return; } this.videoChangeFrameRateStrategy = videoChangeFrameRateStrategy; sendRendererMessage( TRACK_TYPE_VIDEO, MSG_SET_CHANGE_FRAME_RATE_STRATEGY, videoChangeFrameRateStrategy); } public @C.VideoChangeFrameRateStrategy int getVideoChangeFrameRateStrategy() { return videoChangeFrameRateStrategy; } public VideoSize getVideoSize() { return videoSize; } public void clearVideoSurface() { verifyApplicationThread(); removeSurfaceCallbacks(); setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } public void clearVideoSurface(@Nullable Surface surface) { verifyApplicationThread(); if (surface != null && surface == videoOutput) { clearVideoSurface(); } } public void setVideoSurface(@Nullable Surface surface) { verifyApplicationThread(); removeSurfaceCallbacks(); setVideoOutputInternal(surface); int newSurfaceSize = surface == null ? 0 : C.LENGTH_UNSET; maybeNotifySurfaceSizeChanged(/* width= */ newSurfaceSize, /* height= */ newSurfaceSize); } public void setVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { verifyApplicationThread(); if (surfaceHolder == null) { clearVideoSurface(); } else { removeSurfaceCallbacks(); this.surfaceHolderSurfaceIsVideoOutput = true; this.surfaceHolder = surfaceHolder; surfaceHolder.addCallback(componentListener); Surface surface = surfaceHolder.getSurface(); if (surface != null && surface.isValid()) { setVideoOutputInternal(surface); Rect surfaceSize = surfaceHolder.getSurfaceFrame(); maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height()); } else { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } } } public void clearVideoSurfaceHolder(@Nullable SurfaceHolder surfaceHolder) { verifyApplicationThread(); if (surfaceHolder != null && surfaceHolder == this.surfaceHolder) { clearVideoSurface(); } } public void setVideoSurfaceView(@Nullable SurfaceView surfaceView) { verifyApplicationThread(); if (surfaceView instanceof VideoDecoderOutputBufferRenderer) { removeSurfaceCallbacks(); setVideoOutputInternal(surfaceView); setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder()); } else if (surfaceView instanceof SphericalGLSurfaceView) { removeSurfaceCallbacks(); sphericalGLSurfaceView = (SphericalGLSurfaceView) surfaceView; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW) .setPayload(sphericalGLSurfaceView) .send(); sphericalGLSurfaceView.addVideoSurfaceListener(componentListener); setVideoOutputInternal(sphericalGLSurfaceView.getVideoSurface()); setNonVideoOutputSurfaceHolderInternal(surfaceView.getHolder()); } else { setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder()); } } public void clearVideoSurfaceView(@Nullable SurfaceView surfaceView) { verifyApplicationThread(); clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder()); } public void setVideoTextureView(@Nullable TextureView textureView) { verifyApplicationThread(); if (textureView == null) { clearVideoSurface(); } else { removeSurfaceCallbacks(); this.textureView = textureView; if (textureView.getSurfaceTextureListener() != null) { Log.w(TAG, "Replacing existing SurfaceTextureListener."); } textureView.setSurfaceTextureListener(componentListener); @Nullable SurfaceTexture surfaceTexture = textureView.isAvailable() ? textureView.getSurfaceTexture() : null; if (surfaceTexture == null) { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } else { setSurfaceTextureInternal(surfaceTexture); maybeNotifySurfaceSizeChanged(textureView.getWidth(), textureView.getHeight()); } } } public void clearVideoTextureView(@Nullable TextureView textureView) { verifyApplicationThread(); if (textureView != null && textureView == this.textureView) { clearVideoSurface(); } } public void setAudioAttributes(AudioAttributes audioAttributes, boolean handleAudioFocus) { verifyApplicationThread(); if (playerReleased) { return; } if (!Util.areEqual(this.audioAttributes, audioAttributes)) { this.audioAttributes = audioAttributes; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_ATTRIBUTES, audioAttributes); streamVolumeManager.setStreamType(Util.getStreamTypeForAudioUsage(audioAttributes.usage)); analyticsCollector.onAudioAttributesChanged(audioAttributes); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onAudioAttributesChanged(audioAttributes); } } audioFocusManager.setAudioAttributes(handleAudioFocus ? audioAttributes : null); boolean playWhenReady = getPlayWhenReady(); @AudioFocusManager.PlayerCommand int playerCommand = audioFocusManager.updateAudioFocus(playWhenReady, getPlaybackState()); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } public AudioAttributes getAudioAttributes() { return audioAttributes; } public void setAudioSessionId(int audioSessionId) { verifyApplicationThread(); if (this.audioSessionId == audioSessionId) { return; } if (audioSessionId == C.AUDIO_SESSION_ID_UNSET) { if (Util.SDK_INT < 21) { audioSessionId = initializeKeepSessionIdAudioTrack(C.AUDIO_SESSION_ID_UNSET); } else { audioSessionId = Util.generateAudioSessionIdV21(applicationContext); } } else if (Util.SDK_INT < 21) { // We need to re-initialize keepSessionIdAudioTrack to make sure the session is kept alive for // as long as the player is using it. initializeKeepSessionIdAudioTrack(audioSessionId); } this.audioSessionId = audioSessionId; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); sendRendererMessage(TRACK_TYPE_VIDEO, MSG_SET_AUDIO_SESSION_ID, audioSessionId); analyticsCollector.onAudioSessionIdChanged(audioSessionId); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onAudioSessionIdChanged(audioSessionId); } } public int getAudioSessionId() { return audioSessionId; } public void setAuxEffectInfo(AuxEffectInfo auxEffectInfo) { verifyApplicationThread(); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_AUX_EFFECT_INFO, auxEffectInfo); } public void clearAuxEffectInfo() { setAuxEffectInfo(new AuxEffectInfo(AuxEffectInfo.NO_AUX_EFFECT_ID, /* sendLevel= */ 0f)); } public void setVolume(float volume) { verifyApplicationThread(); volume = Util.constrainValue(volume, /* min= */ 0, /* max= */ 1); if (this.volume == volume) { return; } this.volume = volume; sendVolumeToRenderers(); analyticsCollector.onVolumeChanged(volume); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onVolumeChanged(volume); } } public float getVolume() { return volume; } public boolean getSkipSilenceEnabled() { return skipSilenceEnabled; } public void setSkipSilenceEnabled(boolean skipSilenceEnabled) { verifyApplicationThread(); if (this.skipSilenceEnabled == skipSilenceEnabled) { return; } this.skipSilenceEnabled = skipSilenceEnabled; sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_SKIP_SILENCE_ENABLED, skipSilenceEnabled); notifySkipSilenceEnabledChanged(); } public AnalyticsCollector getAnalyticsCollector() { return analyticsCollector; } public void addAnalyticsListener(AnalyticsListener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); analyticsCollector.addListener(listener); } public void removeAnalyticsListener(AnalyticsListener listener) { // Don't verify application thread. We allow calls to this method from any thread. analyticsCollector.removeListener(listener); } public void setHandleAudioBecomingNoisy(boolean handleAudioBecomingNoisy) { verifyApplicationThread(); if (playerReleased) { return; } audioBecomingNoisyManager.setEnabled(handleAudioBecomingNoisy); } public void setPriorityTaskManager(@Nullable PriorityTaskManager priorityTaskManager) { verifyApplicationThread(); if (Util.areEqual(this.priorityTaskManager, priorityTaskManager)) { return; } if (isPriorityTaskManagerRegistered) { checkNotNull(this.priorityTaskManager).remove(C.PRIORITY_PLAYBACK); } if (priorityTaskManager != null && isLoading()) { priorityTaskManager.add(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = true; } else { isPriorityTaskManagerRegistered = false; } this.priorityTaskManager = priorityTaskManager; } @Nullable public Format getVideoFormat() { return videoFormat; } @Nullable public Format getAudioFormat() { return audioFormat; } @Nullable public DecoderCounters getVideoDecoderCounters() { return videoDecoderCounters; } @Nullable public DecoderCounters getAudioDecoderCounters() { return audioDecoderCounters; } public void setVideoFrameMetadataListener(VideoFrameMetadataListener listener) { verifyApplicationThread(); videoFrameMetadataListener = listener; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER) .setPayload(listener) .send(); } public void clearVideoFrameMetadataListener(VideoFrameMetadataListener listener) { verifyApplicationThread(); if (videoFrameMetadataListener != listener) { return; } createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_VIDEO_FRAME_METADATA_LISTENER) .setPayload(null) .send(); } public void setCameraMotionListener(CameraMotionListener listener) { verifyApplicationThread(); cameraMotionListener = listener; createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER) .setPayload(listener) .send(); } public void clearCameraMotionListener(CameraMotionListener listener) { verifyApplicationThread(); if (cameraMotionListener != listener) { return; } createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_CAMERA_MOTION_LISTENER) .setPayload(null) .send(); } public List<Cue> getCurrentCues() { verifyApplicationThread(); return currentCues; } public void addListener(Listener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); listeners.add(listener); listenerArraySet.add(listener); } public void removeListener(Listener listener) { // Don't verify application thread. We allow calls to this method from any thread. checkNotNull(listener); listeners.remove(listener); listenerArraySet.remove(listener); } public void setHandleWakeLock(boolean handleWakeLock) { setWakeMode(handleWakeLock ? C.WAKE_MODE_LOCAL : C.WAKE_MODE_NONE); } public void setWakeMode(@C.WakeMode int wakeMode) { verifyApplicationThread(); switch (wakeMode) { case C.WAKE_MODE_NONE: wakeLockManager.setEnabled(false); wifiLockManager.setEnabled(false); break; case C.WAKE_MODE_LOCAL: wakeLockManager.setEnabled(true); wifiLockManager.setEnabled(false); break; case C.WAKE_MODE_NETWORK: wakeLockManager.setEnabled(true); wifiLockManager.setEnabled(true); break; default: break; } } public DeviceInfo getDeviceInfo() { verifyApplicationThread(); return deviceInfo; } public int getDeviceVolume() { verifyApplicationThread(); return streamVolumeManager.getVolume(); } public boolean isDeviceMuted() { verifyApplicationThread(); return streamVolumeManager.isMuted(); } public void setDeviceVolume(int volume) { verifyApplicationThread(); streamVolumeManager.setVolume(volume); } public void increaseDeviceVolume() { verifyApplicationThread(); streamVolumeManager.increaseVolume(); } public void decreaseDeviceVolume() { verifyApplicationThread(); streamVolumeManager.decreaseVolume(); } public void setDeviceMuted(boolean muted) { verifyApplicationThread(); streamVolumeManager.setMuted(muted); } /* package */ void setThrowsWhenUsingWrongThread(boolean throwsWhenUsingWrongThread) { this.throwsWhenUsingWrongThread = throwsWhenUsingWrongThread; } private int getCurrentWindowIndexInternal() { if (playbackInfo.timeline.isEmpty()) { return maskingWindowIndex; } else { return playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period) .windowIndex; } } private long getCurrentPositionUsInternal(PlaybackInfo playbackInfo) { if (playbackInfo.timeline.isEmpty()) { return Util.msToUs(maskingWindowPositionMs); } else if (playbackInfo.periodId.isAd()) { return playbackInfo.positionUs; } else { return periodPositionUsToWindowPositionUs( playbackInfo.timeline, playbackInfo.periodId, playbackInfo.positionUs); } } private List<MediaSource> createMediaSources(List<MediaItem> mediaItems) { List<MediaSource> mediaSources = new ArrayList<>(); for (int i = 0; i < mediaItems.size(); i++) { mediaSources.add(mediaSourceFactory.createMediaSource(mediaItems.get(i))); } return mediaSources; } private void handlePlaybackInfo(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfoUpdate) { pendingOperationAcks -= playbackInfoUpdate.operationAcks; if (playbackInfoUpdate.positionDiscontinuity) { pendingDiscontinuityReason = playbackInfoUpdate.discontinuityReason; pendingDiscontinuity = true; } if (playbackInfoUpdate.hasPlayWhenReadyChangeReason) { pendingPlayWhenReadyChangeReason = playbackInfoUpdate.playWhenReadyChangeReason; } if (pendingOperationAcks == 0) { Timeline newTimeline = playbackInfoUpdate.playbackInfo.timeline; if (!this.playbackInfo.timeline.isEmpty() && newTimeline.isEmpty()) { // Update the masking variables, which are used when the timeline becomes empty because a // ConcatenatingMediaSource has been cleared. maskingWindowIndex = C.INDEX_UNSET; maskingWindowPositionMs = 0; maskingPeriodIndex = 0; } if (!newTimeline.isEmpty()) { List<Timeline> timelines = ((PlaylistTimeline) newTimeline).getChildTimelines(); checkState(timelines.size() == mediaSourceHolderSnapshots.size()); for (int i = 0; i < timelines.size(); i++) { mediaSourceHolderSnapshots.get(i).timeline = timelines.get(i); } } boolean positionDiscontinuity = false; long discontinuityWindowStartPositionUs = C.TIME_UNSET; if (pendingDiscontinuity) { positionDiscontinuity = !playbackInfoUpdate.playbackInfo.periodId.equals(playbackInfo.periodId) || playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs != playbackInfo.positionUs; if (positionDiscontinuity) { discontinuityWindowStartPositionUs = newTimeline.isEmpty() || playbackInfoUpdate.playbackInfo.periodId.isAd() ? playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs : periodPositionUsToWindowPositionUs( newTimeline, playbackInfoUpdate.playbackInfo.periodId, playbackInfoUpdate.playbackInfo.discontinuityStartPositionUs); } } pendingDiscontinuity = false; updatePlaybackInfo( playbackInfoUpdate.playbackInfo, TIMELINE_CHANGE_REASON_SOURCE_UPDATE, pendingPlayWhenReadyChangeReason, /* seekProcessed= */ false, positionDiscontinuity, pendingDiscontinuityReason, discontinuityWindowStartPositionUs, /* ignored */ C.INDEX_UNSET); } } // Calling deprecated listeners. @SuppressWarnings("deprecation") private void updatePlaybackInfo( PlaybackInfo playbackInfo, @TimelineChangeReason int timelineChangeReason, @PlayWhenReadyChangeReason int playWhenReadyChangeReason, boolean seekProcessed, boolean positionDiscontinuity, @DiscontinuityReason int positionDiscontinuityReason, long discontinuityWindowStartPositionUs, int oldMaskingMediaItemIndex) { // Assign playback info immediately such that all getters return the right values, but keep // snapshot of previous and new state so that listener invocations are triggered correctly. PlaybackInfo previousPlaybackInfo = this.playbackInfo; PlaybackInfo newPlaybackInfo = playbackInfo; this.playbackInfo = playbackInfo; Pair<Boolean, Integer> mediaItemTransitionInfo = evaluateMediaItemTransitionReason( newPlaybackInfo, previousPlaybackInfo, positionDiscontinuity, positionDiscontinuityReason, !previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)); boolean mediaItemTransitioned = mediaItemTransitionInfo.first; int mediaItemTransitionReason = mediaItemTransitionInfo.second; MediaMetadata newMediaMetadata = mediaMetadata; @Nullable MediaItem mediaItem = null; if (mediaItemTransitioned) { if (!newPlaybackInfo.timeline.isEmpty()) { int windowIndex = newPlaybackInfo.timeline.getPeriodByUid(newPlaybackInfo.periodId.periodUid, period) .windowIndex; mediaItem = newPlaybackInfo.timeline.getWindow(windowIndex, window).mediaItem; } staticAndDynamicMediaMetadata = MediaMetadata.EMPTY; } if (mediaItemTransitioned || !previousPlaybackInfo.staticMetadata.equals(newPlaybackInfo.staticMetadata)) { staticAndDynamicMediaMetadata = staticAndDynamicMediaMetadata .buildUpon() .populateFromMetadata(newPlaybackInfo.staticMetadata) .build(); newMediaMetadata = buildUpdatedMediaMetadata(); } boolean metadataChanged = !newMediaMetadata.equals(mediaMetadata); mediaMetadata = newMediaMetadata; if (!previousPlaybackInfo.timeline.equals(newPlaybackInfo.timeline)) { listeners.queueEvent( Player.EVENT_TIMELINE_CHANGED, listener -> listener.onTimelineChanged(newPlaybackInfo.timeline, timelineChangeReason)); } if (positionDiscontinuity) { PositionInfo previousPositionInfo = getPreviousPositionInfo( positionDiscontinuityReason, previousPlaybackInfo, oldMaskingMediaItemIndex); PositionInfo positionInfo = getPositionInfo(discontinuityWindowStartPositionUs); listeners.queueEvent( Player.EVENT_POSITION_DISCONTINUITY, listener -> { listener.onPositionDiscontinuity(positionDiscontinuityReason); listener.onPositionDiscontinuity( previousPositionInfo, positionInfo, positionDiscontinuityReason); }); } if (mediaItemTransitioned) { @Nullable final MediaItem finalMediaItem = mediaItem; listeners.queueEvent( Player.EVENT_MEDIA_ITEM_TRANSITION, listener -> listener.onMediaItemTransition(finalMediaItem, mediaItemTransitionReason)); } if (previousPlaybackInfo.playbackError != newPlaybackInfo.playbackError) { listeners.queueEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerErrorChanged(newPlaybackInfo.playbackError)); if (newPlaybackInfo.playbackError != null) { listeners.queueEvent( Player.EVENT_PLAYER_ERROR, listener -> listener.onPlayerError(newPlaybackInfo.playbackError)); } } if (previousPlaybackInfo.trackSelectorResult != newPlaybackInfo.trackSelectorResult) { trackSelector.onSelectionActivated(newPlaybackInfo.trackSelectorResult.info); TrackSelectionArray newSelection = new TrackSelectionArray(newPlaybackInfo.trackSelectorResult.selections); listeners.queueEvent( Player.EVENT_TRACKS_CHANGED, listener -> listener.onTracksChanged(newPlaybackInfo.trackGroups, newSelection)); listeners.queueEvent( Player.EVENT_TRACKS_CHANGED, listener -> listener.onTracksInfoChanged(newPlaybackInfo.trackSelectorResult.tracksInfo)); } if (metadataChanged) { final MediaMetadata finalMediaMetadata = mediaMetadata; listeners.queueEvent( EVENT_MEDIA_METADATA_CHANGED, listener -> listener.onMediaMetadataChanged(finalMediaMetadata)); } if (previousPlaybackInfo.isLoading != newPlaybackInfo.isLoading) { listeners.queueEvent( Player.EVENT_IS_LOADING_CHANGED, listener -> { listener.onLoadingChanged(newPlaybackInfo.isLoading); listener.onIsLoadingChanged(newPlaybackInfo.isLoading); }); } if (previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState || previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady) { listeners.queueEvent( /* eventFlag= */ C.INDEX_UNSET, listener -> listener.onPlayerStateChanged( newPlaybackInfo.playWhenReady, newPlaybackInfo.playbackState)); } if (previousPlaybackInfo.playbackState != newPlaybackInfo.playbackState) { listeners.queueEvent( Player.EVENT_PLAYBACK_STATE_CHANGED, listener -> listener.onPlaybackStateChanged(newPlaybackInfo.playbackState)); } if (previousPlaybackInfo.playWhenReady != newPlaybackInfo.playWhenReady) { listeners.queueEvent( Player.EVENT_PLAY_WHEN_READY_CHANGED, listener -> listener.onPlayWhenReadyChanged( newPlaybackInfo.playWhenReady, playWhenReadyChangeReason)); } if (previousPlaybackInfo.playbackSuppressionReason != newPlaybackInfo.playbackSuppressionReason) { listeners.queueEvent( Player.EVENT_PLAYBACK_SUPPRESSION_REASON_CHANGED, listener -> listener.onPlaybackSuppressionReasonChanged( newPlaybackInfo.playbackSuppressionReason)); } if (isPlaying(previousPlaybackInfo) != isPlaying(newPlaybackInfo)) { listeners.queueEvent( Player.EVENT_IS_PLAYING_CHANGED, listener -> listener.onIsPlayingChanged(isPlaying(newPlaybackInfo))); } if (!previousPlaybackInfo.playbackParameters.equals(newPlaybackInfo.playbackParameters)) { listeners.queueEvent( Player.EVENT_PLAYBACK_PARAMETERS_CHANGED, listener -> listener.onPlaybackParametersChanged(newPlaybackInfo.playbackParameters)); } if (seekProcessed) { listeners.queueEvent(/* eventFlag= */ C.INDEX_UNSET, Listener::onSeekProcessed); } updateAvailableCommands(); listeners.flushEvents(); if (previousPlaybackInfo.offloadSchedulingEnabled != newPlaybackInfo.offloadSchedulingEnabled) { for (AudioOffloadListener listener : audioOffloadListeners) { listener.onExperimentalOffloadSchedulingEnabledChanged( newPlaybackInfo.offloadSchedulingEnabled); } } if (previousPlaybackInfo.sleepingForOffload != newPlaybackInfo.sleepingForOffload) { for (AudioOffloadListener listener : audioOffloadListeners) { listener.onExperimentalSleepingForOffloadChanged(newPlaybackInfo.sleepingForOffload); } } } private PositionInfo getPreviousPositionInfo( @DiscontinuityReason int positionDiscontinuityReason, PlaybackInfo oldPlaybackInfo, int oldMaskingMediaItemIndex) { @Nullable Object oldWindowUid = null; @Nullable Object oldPeriodUid = null; int oldMediaItemIndex = oldMaskingMediaItemIndex; int oldPeriodIndex = C.INDEX_UNSET; @Nullable MediaItem oldMediaItem = null; Timeline.Period oldPeriod = new Timeline.Period(); if (!oldPlaybackInfo.timeline.isEmpty()) { oldPeriodUid = oldPlaybackInfo.periodId.periodUid; oldPlaybackInfo.timeline.getPeriodByUid(oldPeriodUid, oldPeriod); oldMediaItemIndex = oldPeriod.windowIndex; oldPeriodIndex = oldPlaybackInfo.timeline.getIndexOfPeriod(oldPeriodUid); oldWindowUid = oldPlaybackInfo.timeline.getWindow(oldMediaItemIndex, window).uid; oldMediaItem = window.mediaItem; } long oldPositionUs; long oldContentPositionUs; if (positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) { if (oldPlaybackInfo.periodId.isAd()) { // The old position is the end of the previous ad. oldPositionUs = oldPeriod.getAdDurationUs( oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup); // The ad cue point is stored in the old requested content position. oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo); } else if (oldPlaybackInfo.periodId.nextAdGroupIndex != C.INDEX_UNSET) { // The old position is the end of a clipped content before an ad group. Use the exact ad // cue point as the transition position. oldPositionUs = getRequestedContentPositionUs(playbackInfo); oldContentPositionUs = oldPositionUs; } else { // The old position is the end of a Timeline period. Use the exact duration. oldPositionUs = oldPeriod.positionInWindowUs + oldPeriod.durationUs; oldContentPositionUs = oldPositionUs; } } else if (oldPlaybackInfo.periodId.isAd()) { oldPositionUs = oldPlaybackInfo.positionUs; oldContentPositionUs = getRequestedContentPositionUs(oldPlaybackInfo); } else { oldPositionUs = oldPeriod.positionInWindowUs + oldPlaybackInfo.positionUs; oldContentPositionUs = oldPositionUs; } return new PositionInfo( oldWindowUid, oldMediaItemIndex, oldMediaItem, oldPeriodUid, oldPeriodIndex, Util.usToMs(oldPositionUs), Util.usToMs(oldContentPositionUs), oldPlaybackInfo.periodId.adGroupIndex, oldPlaybackInfo.periodId.adIndexInAdGroup); } private PositionInfo getPositionInfo(long discontinuityWindowStartPositionUs) { @Nullable Object newWindowUid = null; @Nullable Object newPeriodUid = null; int newMediaItemIndex = getCurrentMediaItemIndex(); int newPeriodIndex = C.INDEX_UNSET; @Nullable MediaItem newMediaItem = null; if (!playbackInfo.timeline.isEmpty()) { newPeriodUid = playbackInfo.periodId.periodUid; playbackInfo.timeline.getPeriodByUid(newPeriodUid, period); newPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(newPeriodUid); newWindowUid = playbackInfo.timeline.getWindow(newMediaItemIndex, window).uid; newMediaItem = window.mediaItem; } long positionMs = Util.usToMs(discontinuityWindowStartPositionUs); return new PositionInfo( newWindowUid, newMediaItemIndex, newMediaItem, newPeriodUid, newPeriodIndex, positionMs, /* contentPositionMs= */ playbackInfo.periodId.isAd() ? Util.usToMs(getRequestedContentPositionUs(playbackInfo)) : positionMs, playbackInfo.periodId.adGroupIndex, playbackInfo.periodId.adIndexInAdGroup); } private static long getRequestedContentPositionUs(PlaybackInfo playbackInfo) { Timeline.Window window = new Timeline.Window(); Timeline.Period period = new Timeline.Period(); playbackInfo.timeline.getPeriodByUid(playbackInfo.periodId.periodUid, period); return playbackInfo.requestedContentPositionUs == C.TIME_UNSET ? playbackInfo.timeline.getWindow(period.windowIndex, window).getDefaultPositionUs() : period.getPositionInWindowUs() + playbackInfo.requestedContentPositionUs; } private Pair<Boolean, Integer> evaluateMediaItemTransitionReason( PlaybackInfo playbackInfo, PlaybackInfo oldPlaybackInfo, boolean positionDiscontinuity, @DiscontinuityReason int positionDiscontinuityReason, boolean timelineChanged) { Timeline oldTimeline = oldPlaybackInfo.timeline; Timeline newTimeline = playbackInfo.timeline; if (newTimeline.isEmpty() && oldTimeline.isEmpty()) { return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET); } else if (newTimeline.isEmpty() != oldTimeline.isEmpty()) { return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED); } int oldWindowIndex = oldTimeline.getPeriodByUid(oldPlaybackInfo.periodId.periodUid, period).windowIndex; Object oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid; int newWindowIndex = newTimeline.getPeriodByUid(playbackInfo.periodId.periodUid, period).windowIndex; Object newWindowUid = newTimeline.getWindow(newWindowIndex, window).uid; if (!oldWindowUid.equals(newWindowUid)) { @Player.MediaItemTransitionReason int transitionReason; if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_AUTO; } else if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_SEEK) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_SEEK; } else if (timelineChanged) { transitionReason = MEDIA_ITEM_TRANSITION_REASON_PLAYLIST_CHANGED; } else { // A change in window uid must be justified by one of the reasons above. throw new IllegalStateException(); } return new Pair<>(/* isTransitioning */ true, transitionReason); } else if (positionDiscontinuity && positionDiscontinuityReason == DISCONTINUITY_REASON_AUTO_TRANSITION && oldPlaybackInfo.periodId.windowSequenceNumber < playbackInfo.periodId.windowSequenceNumber) { return new Pair<>(/* isTransitioning */ true, MEDIA_ITEM_TRANSITION_REASON_REPEAT); } return new Pair<>(/* isTransitioning */ false, /* mediaItemTransitionReason */ C.INDEX_UNSET); } private void updateAvailableCommands() { Commands previousAvailableCommands = availableCommands; availableCommands = Util.getAvailableCommands(wrappingPlayer, permanentAvailableCommands); if (!availableCommands.equals(previousAvailableCommands)) { listeners.queueEvent( Player.EVENT_AVAILABLE_COMMANDS_CHANGED, listener -> listener.onAvailableCommandsChanged(availableCommands)); } } private void setMediaSourcesInternal( List<MediaSource> mediaSources, int startWindowIndex, long startPositionMs, boolean resetToDefaultPosition) { int currentWindowIndex = getCurrentWindowIndexInternal(); long currentPositionMs = getCurrentPosition(); pendingOperationAcks++; if (!mediaSourceHolderSnapshots.isEmpty()) { removeMediaSourceHolders( /* fromIndex= */ 0, /* toIndexExclusive= */ mediaSourceHolderSnapshots.size()); } List<MediaSourceList.MediaSourceHolder> holders = addMediaSourceHolders(/* index= */ 0, mediaSources); Timeline timeline = createMaskingTimeline(); if (!timeline.isEmpty() && startWindowIndex >= timeline.getWindowCount()) { throw new IllegalSeekPositionException(timeline, startWindowIndex, startPositionMs); } // Evaluate the actual start position. if (resetToDefaultPosition) { startWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); startPositionMs = C.TIME_UNSET; } else if (startWindowIndex == C.INDEX_UNSET) { startWindowIndex = currentWindowIndex; startPositionMs = currentPositionMs; } PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, timeline, maskWindowPositionMsOrGetPeriodPositionUs(timeline, startWindowIndex, startPositionMs)); // Mask the playback state. int maskingPlaybackState = newPlaybackInfo.playbackState; if (startWindowIndex != C.INDEX_UNSET && newPlaybackInfo.playbackState != STATE_IDLE) { // Position reset to startWindowIndex (results in pending initial seek). if (timeline.isEmpty() || startWindowIndex >= timeline.getWindowCount()) { // Setting an empty timeline or invalid seek transitions to ended. maskingPlaybackState = STATE_ENDED; } else { maskingPlaybackState = STATE_BUFFERING; } } newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(maskingPlaybackState); internalPlayer.setMediaSources( holders, startWindowIndex, Util.msToUs(startPositionMs), shuffleOrder); boolean positionDiscontinuity = !playbackInfo.periodId.periodUid.equals(newPlaybackInfo.periodId.periodUid) && !playbackInfo.timeline.isEmpty(); updatePlaybackInfo( newPlaybackInfo, /* timelineChangeReason= */ TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED, /* ignored */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST, /* seekProcessed= */ false, /* positionDiscontinuity= */ positionDiscontinuity, DISCONTINUITY_REASON_REMOVE, /* discontinuityWindowStartPositionUs= */ getCurrentPositionUsInternal(newPlaybackInfo), /* ignored */ C.INDEX_UNSET); } private List<MediaSourceList.MediaSourceHolder> addMediaSourceHolders( int index, List<MediaSource> mediaSources) { List<MediaSourceList.MediaSourceHolder> holders = new ArrayList<>(); for (int i = 0; i < mediaSources.size(); i++) { MediaSourceList.MediaSourceHolder holder = new MediaSourceList.MediaSourceHolder(mediaSources.get(i), useLazyPreparation); holders.add(holder); mediaSourceHolderSnapshots.add( i + index, new MediaSourceHolderSnapshot(holder.uid, holder.mediaSource.getTimeline())); } shuffleOrder = shuffleOrder.cloneAndInsert( /* insertionIndex= */ index, /* insertionCount= */ holders.size()); return holders; } private PlaybackInfo removeMediaItemsInternal(int fromIndex, int toIndex) { Assertions.checkArgument( fromIndex >= 0 && toIndex >= fromIndex && toIndex <= mediaSourceHolderSnapshots.size()); int currentIndex = getCurrentMediaItemIndex(); Timeline oldTimeline = getCurrentTimeline(); int currentMediaSourceCount = mediaSourceHolderSnapshots.size(); pendingOperationAcks++; removeMediaSourceHolders(fromIndex, /* toIndexExclusive= */ toIndex); Timeline newTimeline = createMaskingTimeline(); PlaybackInfo newPlaybackInfo = maskTimelineAndPosition( playbackInfo, newTimeline, getPeriodPositionUsAfterTimelineChanged(oldTimeline, newTimeline)); // Player transitions to STATE_ENDED if the current index is part of the removed tail. final boolean transitionsToEnded = newPlaybackInfo.playbackState != STATE_IDLE && newPlaybackInfo.playbackState != STATE_ENDED && fromIndex < toIndex && toIndex == currentMediaSourceCount && currentIndex >= newPlaybackInfo.timeline.getWindowCount(); if (transitionsToEnded) { newPlaybackInfo = newPlaybackInfo.copyWithPlaybackState(STATE_ENDED); } internalPlayer.removeMediaSources(fromIndex, toIndex, shuffleOrder); return newPlaybackInfo; } private void removeMediaSourceHolders(int fromIndex, int toIndexExclusive) { for (int i = toIndexExclusive - 1; i >= fromIndex; i--) { mediaSourceHolderSnapshots.remove(i); } shuffleOrder = shuffleOrder.cloneAndRemove(fromIndex, toIndexExclusive); } private Timeline createMaskingTimeline() { return new PlaylistTimeline(mediaSourceHolderSnapshots, shuffleOrder); } private PlaybackInfo maskTimelineAndPosition( PlaybackInfo playbackInfo, Timeline timeline, @Nullable Pair<Object, Long> periodPositionUs) { Assertions.checkArgument(timeline.isEmpty() || periodPositionUs != null); Timeline oldTimeline = playbackInfo.timeline; // Mask the timeline. playbackInfo = playbackInfo.copyWithTimeline(timeline); if (timeline.isEmpty()) { // Reset periodId and loadingPeriodId. MediaPeriodId dummyMediaPeriodId = PlaybackInfo.getDummyPeriodForEmptyTimeline(); long positionUs = Util.msToUs(maskingWindowPositionMs); playbackInfo = playbackInfo.copyWithNewPosition( dummyMediaPeriodId, positionUs, /* requestedContentPositionUs= */ positionUs, /* discontinuityStartPositionUs= */ positionUs, /* totalBufferedDurationUs= */ 0, TrackGroupArray.EMPTY, emptyTrackSelectorResult, /* staticMetadata= */ ImmutableList.of()); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(dummyMediaPeriodId); playbackInfo.bufferedPositionUs = playbackInfo.positionUs; return playbackInfo; } Object oldPeriodUid = playbackInfo.periodId.periodUid; boolean playingPeriodChanged = !oldPeriodUid.equals(castNonNull(periodPositionUs).first); MediaPeriodId newPeriodId = playingPeriodChanged ? new MediaPeriodId(periodPositionUs.first) : playbackInfo.periodId; long newContentPositionUs = periodPositionUs.second; long oldContentPositionUs = Util.msToUs(getContentPosition()); if (!oldTimeline.isEmpty()) { oldContentPositionUs -= oldTimeline.getPeriodByUid(oldPeriodUid, period).getPositionInWindowUs(); } if (playingPeriodChanged || newContentPositionUs < oldContentPositionUs) { checkState(!newPeriodId.isAd()); // The playing period changes or a backwards seek within the playing period occurs. playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ newContentPositionUs, /* requestedContentPositionUs= */ newContentPositionUs, /* discontinuityStartPositionUs= */ newContentPositionUs, /* totalBufferedDurationUs= */ 0, playingPeriodChanged ? TrackGroupArray.EMPTY : playbackInfo.trackGroups, playingPeriodChanged ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult, playingPeriodChanged ? ImmutableList.of() : playbackInfo.staticMetadata); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId); playbackInfo.bufferedPositionUs = newContentPositionUs; } else if (newContentPositionUs == oldContentPositionUs) { // Period position remains unchanged. int loadingPeriodIndex = timeline.getIndexOfPeriod(playbackInfo.loadingMediaPeriodId.periodUid); if (loadingPeriodIndex == C.INDEX_UNSET || timeline.getPeriod(loadingPeriodIndex, period).windowIndex != timeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex) { // Discard periods after the playing period, if the loading period is discarded or the // playing and loading period are not in the same window. timeline.getPeriodByUid(newPeriodId.periodUid, period); long maskedBufferedPositionUs = newPeriodId.isAd() ? period.getAdDurationUs(newPeriodId.adGroupIndex, newPeriodId.adIndexInAdGroup) : period.durationUs; playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ playbackInfo.positionUs, /* requestedContentPositionUs= */ playbackInfo.positionUs, playbackInfo.discontinuityStartPositionUs, /* totalBufferedDurationUs= */ maskedBufferedPositionUs - playbackInfo.positionUs, playbackInfo.trackGroups, playbackInfo.trackSelectorResult, playbackInfo.staticMetadata); playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(newPeriodId); playbackInfo.bufferedPositionUs = maskedBufferedPositionUs; } } else { checkState(!newPeriodId.isAd()); // A forward seek within the playing period (timeline did not change). long maskedTotalBufferedDurationUs = max( 0, playbackInfo.totalBufferedDurationUs - (newContentPositionUs - oldContentPositionUs)); long maskedBufferedPositionUs = playbackInfo.bufferedPositionUs; if (playbackInfo.loadingMediaPeriodId.equals(playbackInfo.periodId)) { maskedBufferedPositionUs = newContentPositionUs + maskedTotalBufferedDurationUs; } playbackInfo = playbackInfo.copyWithNewPosition( newPeriodId, /* positionUs= */ newContentPositionUs, /* requestedContentPositionUs= */ newContentPositionUs, /* discontinuityStartPositionUs= */ newContentPositionUs, maskedTotalBufferedDurationUs, playbackInfo.trackGroups, playbackInfo.trackSelectorResult, playbackInfo.staticMetadata); playbackInfo.bufferedPositionUs = maskedBufferedPositionUs; } return playbackInfo; } @Nullable private Pair<Object, Long> getPeriodPositionUsAfterTimelineChanged( Timeline oldTimeline, Timeline newTimeline) { long currentPositionMs = getContentPosition(); if (oldTimeline.isEmpty() || newTimeline.isEmpty()) { boolean isCleared = !oldTimeline.isEmpty() && newTimeline.isEmpty(); return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, isCleared ? C.INDEX_UNSET : getCurrentWindowIndexInternal(), isCleared ? C.TIME_UNSET : currentPositionMs); } int currentMediaItemIndex = getCurrentMediaItemIndex(); @Nullable Pair<Object, Long> oldPeriodPositionUs = oldTimeline.getPeriodPositionUs( window, period, currentMediaItemIndex, Util.msToUs(currentPositionMs)); Object periodUid = castNonNull(oldPeriodPositionUs).first; if (newTimeline.getIndexOfPeriod(periodUid) != C.INDEX_UNSET) { // The old period position is still available in the new timeline. return oldPeriodPositionUs; } // Period uid not found in new timeline. Try to get subsequent period. @Nullable Object nextPeriodUid = ExoPlayerImplInternal.resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, periodUid, oldTimeline, newTimeline); if (nextPeriodUid != null) { // Reset position to the default position of the window of the subsequent period. newTimeline.getPeriodByUid(nextPeriodUid, period); return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, period.windowIndex, newTimeline.getWindow(period.windowIndex, window).getDefaultPositionMs()); } else { // No subsequent period found and the new timeline is not empty. Use the default position. return maskWindowPositionMsOrGetPeriodPositionUs( newTimeline, /* windowIndex= */ C.INDEX_UNSET, /* windowPositionMs= */ C.TIME_UNSET); } } @Nullable private Pair<Object, Long> maskWindowPositionMsOrGetPeriodPositionUs( Timeline timeline, int windowIndex, long windowPositionMs) { if (timeline.isEmpty()) { // If empty we store the initial seek in the masking variables. maskingWindowIndex = windowIndex; maskingWindowPositionMs = windowPositionMs == C.TIME_UNSET ? 0 : windowPositionMs; maskingPeriodIndex = 0; return null; } if (windowIndex == C.INDEX_UNSET || windowIndex >= timeline.getWindowCount()) { // Use default position of timeline if window index still unset or if a previous initial seek // now turns out to be invalid. windowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); windowPositionMs = timeline.getWindow(windowIndex, window).getDefaultPositionMs(); } return timeline.getPeriodPositionUs(window, period, windowIndex, Util.msToUs(windowPositionMs)); } private long periodPositionUsToWindowPositionUs( Timeline timeline, MediaPeriodId periodId, long positionUs) { timeline.getPeriodByUid(periodId.periodUid, period); positionUs += period.getPositionInWindowUs(); return positionUs; } private PlayerMessage createMessageInternal(Target target) { int currentWindowIndex = getCurrentWindowIndexInternal(); return new PlayerMessage( internalPlayer, target, playbackInfo.timeline, currentWindowIndex == C.INDEX_UNSET ? 0 : currentWindowIndex, clock, internalPlayer.getPlaybackLooper()); } /** * Builds a {@link MediaMetadata} from the main sources. * * <p>{@link MediaItem} {@link MediaMetadata} is prioritized, with any gaps/missing fields * populated by metadata from static ({@link TrackGroup} {@link Format}) and dynamic ({@link * #onMetadata(Metadata)}) sources. */ private MediaMetadata buildUpdatedMediaMetadata() { Timeline timeline = getCurrentTimeline(); if (timeline.isEmpty()) { return staticAndDynamicMediaMetadata; } MediaItem mediaItem = timeline.getWindow(getCurrentMediaItemIndex(), window).mediaItem; // MediaItem metadata is prioritized over metadata within the media. return staticAndDynamicMediaMetadata.buildUpon().populate(mediaItem.mediaMetadata).build(); } private void removeSurfaceCallbacks() { if (sphericalGLSurfaceView != null) { createMessageInternal(frameMetadataListener) .setType(FrameMetadataListener.MSG_SET_SPHERICAL_SURFACE_VIEW) .setPayload(null) .send(); sphericalGLSurfaceView.removeVideoSurfaceListener(componentListener); sphericalGLSurfaceView = null; } if (textureView != null) { if (textureView.getSurfaceTextureListener() != componentListener) { Log.w(TAG, "SurfaceTextureListener already unset or replaced."); } else { textureView.setSurfaceTextureListener(null); } textureView = null; } if (surfaceHolder != null) { surfaceHolder.removeCallback(componentListener); surfaceHolder = null; } } private void setSurfaceTextureInternal(SurfaceTexture surfaceTexture) { Surface surface = new Surface(surfaceTexture); setVideoOutputInternal(surface); ownedSurface = surface; } private void setVideoOutputInternal(@Nullable Object videoOutput) { // Note: We don't turn this method into a no-op if the output is being replaced with itself so // as to ensure onRenderedFirstFrame callbacks are still called in this case. List<PlayerMessage> messages = new ArrayList<>(); for (Renderer renderer : renderers) { if (renderer.getTrackType() == TRACK_TYPE_VIDEO) { messages.add( createMessageInternal(renderer) .setType(MSG_SET_VIDEO_OUTPUT) .setPayload(videoOutput) .send()); } } boolean messageDeliveryTimedOut = false; if (this.videoOutput != null && this.videoOutput != videoOutput) { // We're replacing an output. Block to ensure that this output will not be accessed by the // renderers after this method returns. try { for (PlayerMessage message : messages) { message.blockUntilDelivered(detachSurfaceTimeoutMs); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException e) { messageDeliveryTimedOut = true; } if (this.videoOutput == ownedSurface) { // We're replacing a surface that we are responsible for releasing. ownedSurface.release(); ownedSurface = null; } } this.videoOutput = videoOutput; if (messageDeliveryTimedOut) { stop( /* reset= */ false, ExoPlaybackException.createForUnexpected( new ExoTimeoutException(ExoTimeoutException.TIMEOUT_OPERATION_DETACH_SURFACE), PlaybackException.ERROR_CODE_TIMEOUT)); } } /** * Sets the holder of the surface that will be displayed to the user, but which should * <em>not</em> be the output for video renderers. This case occurs when video frames need to be * rendered to an intermediate surface (which is not the one held by the provided holder). * * @param nonVideoOutputSurfaceHolder The holder of the surface that will eventually be displayed * to the user. */ private void setNonVideoOutputSurfaceHolderInternal(SurfaceHolder nonVideoOutputSurfaceHolder) { // Although we won't use the view's surface directly as the video output, still use the holder // to query the surface size, to be informed in changes to the size via componentListener, and // for equality checking in clearVideoSurfaceHolder. surfaceHolderSurfaceIsVideoOutput = false; surfaceHolder = nonVideoOutputSurfaceHolder; surfaceHolder.addCallback(componentListener); Surface surface = surfaceHolder.getSurface(); if (surface != null && surface.isValid()) { Rect surfaceSize = surfaceHolder.getSurfaceFrame(); maybeNotifySurfaceSizeChanged(surfaceSize.width(), surfaceSize.height()); } else { maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } } private void maybeNotifySurfaceSizeChanged(int width, int height) { if (width != surfaceWidth || height != surfaceHeight) { surfaceWidth = width; surfaceHeight = height; analyticsCollector.onSurfaceSizeChanged(width, height); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onSurfaceSizeChanged(width, height); } } } private void sendVolumeToRenderers() { float scaledVolume = volume * audioFocusManager.getVolumeMultiplier(); sendRendererMessage(TRACK_TYPE_AUDIO, MSG_SET_VOLUME, scaledVolume); } private void notifySkipSilenceEnabledChanged() { analyticsCollector.onSkipSilenceEnabledChanged(skipSilenceEnabled); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onSkipSilenceEnabledChanged(skipSilenceEnabled); } } private void updatePlayWhenReady( boolean playWhenReady, @AudioFocusManager.PlayerCommand int playerCommand, @Player.PlayWhenReadyChangeReason int playWhenReadyChangeReason) { playWhenReady = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY; @PlaybackSuppressionReason int playbackSuppressionReason = playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY ? Player.PLAYBACK_SUPPRESSION_REASON_TRANSIENT_AUDIO_FOCUS_LOSS : Player.PLAYBACK_SUPPRESSION_REASON_NONE; setPlayWhenReady(playWhenReady, playbackSuppressionReason, playWhenReadyChangeReason); } private void updateWakeAndWifiLock() { @State int playbackState = getPlaybackState(); switch (playbackState) { case Player.STATE_READY: case Player.STATE_BUFFERING: boolean isSleeping = experimentalIsSleepingForOffload(); wakeLockManager.setStayAwake(getPlayWhenReady() && !isSleeping); // The wifi lock is not released while sleeping to avoid interrupting downloads. wifiLockManager.setStayAwake(getPlayWhenReady()); break; case Player.STATE_ENDED: case Player.STATE_IDLE: wakeLockManager.setStayAwake(false); wifiLockManager.setStayAwake(false); break; default: throw new IllegalStateException(); } } private void verifyApplicationThread() { // The constructor may be executed on a background thread. Wait with accessing the player from // the app thread until the constructor finished executing. constructorFinished.blockUninterruptible(); if (Thread.currentThread() != getApplicationLooper().getThread()) { String message = Util.formatInvariant( "Player is accessed on the wrong thread.\n" + "Current thread: '%s'\n" + "Expected thread: '%s'\n" + "See https://exoplayer.dev/issues/player-accessed-on-wrong-thread", Thread.currentThread().getName(), getApplicationLooper().getThread().getName()); if (throwsWhenUsingWrongThread) { throw new IllegalStateException(message); } Log.w(TAG, message, hasNotifiedFullWrongThreadWarning ? null : new IllegalStateException()); hasNotifiedFullWrongThreadWarning = true; } } private void sendRendererMessage( @C.TrackType int trackType, int messageType, @Nullable Object payload) { for (Renderer renderer : renderers) { if (renderer.getTrackType() == trackType) { createMessageInternal(renderer).setType(messageType).setPayload(payload).send(); } } } /** * Initializes {@link #keepSessionIdAudioTrack} to keep an audio session ID alive. If the audio * session ID is {@link C#AUDIO_SESSION_ID_UNSET} then a new audio session ID is generated. * * <p>Use of this method is only required on API level 21 and earlier. * * @param audioSessionId The audio session ID, or {@link C#AUDIO_SESSION_ID_UNSET} to generate a * new one. * @return The audio session ID. */ private int initializeKeepSessionIdAudioTrack(int audioSessionId) { if (keepSessionIdAudioTrack != null && keepSessionIdAudioTrack.getAudioSessionId() != audioSessionId) { keepSessionIdAudioTrack.release(); keepSessionIdAudioTrack = null; } if (keepSessionIdAudioTrack == null) { int sampleRate = 4000; // Minimum sample rate supported by the platform. int channelConfig = AudioFormat.CHANNEL_OUT_MONO; @C.PcmEncoding int encoding = C.ENCODING_PCM_16BIT; int bufferSize = 2; // Use a two byte buffer, as it is not actually used for playback. keepSessionIdAudioTrack = new AudioTrack( C.STREAM_TYPE_DEFAULT, sampleRate, channelConfig, encoding, bufferSize, AudioTrack.MODE_STATIC, audioSessionId); } return keepSessionIdAudioTrack.getAudioSessionId(); } private static DeviceInfo createDeviceInfo(StreamVolumeManager streamVolumeManager) { return new DeviceInfo( DeviceInfo.PLAYBACK_TYPE_LOCAL, streamVolumeManager.getMinVolume(), streamVolumeManager.getMaxVolume()); } private static int getPlayWhenReadyChangeReason(boolean playWhenReady, int playerCommand) { return playWhenReady && playerCommand != AudioFocusManager.PLAYER_COMMAND_PLAY_WHEN_READY ? PLAY_WHEN_READY_CHANGE_REASON_AUDIO_FOCUS_LOSS : PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST; } private static boolean isPlaying(PlaybackInfo playbackInfo) { return playbackInfo.playbackState == Player.STATE_READY && playbackInfo.playWhenReady && playbackInfo.playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE; } private static final class MediaSourceHolderSnapshot implements MediaSourceInfoHolder { private final Object uid; private Timeline timeline; public MediaSourceHolderSnapshot(Object uid, Timeline timeline) { this.uid = uid; this.timeline = timeline; } @Override public Object getUid() { return uid; } @Override public Timeline getTimeline() { return timeline; } } private final class ComponentListener implements Player.Listener, VideoRendererEventListener, AudioRendererEventListener, TextOutput, MetadataOutput, SurfaceHolder.Callback, TextureView.SurfaceTextureListener, SphericalGLSurfaceView.VideoSurfaceListener, AudioFocusManager.PlayerControl, AudioBecomingNoisyManager.EventListener, StreamVolumeManager.Listener, AudioOffloadListener { // VideoRendererEventListener implementation @Override public void onVideoEnabled(DecoderCounters counters) { videoDecoderCounters = counters; analyticsCollector.onVideoEnabled(counters); } @Override public void onVideoDecoderInitialized( String decoderName, long initializedTimestampMs, long initializationDurationMs) { analyticsCollector.onVideoDecoderInitialized( decoderName, initializedTimestampMs, initializationDurationMs); } @Override public void onVideoInputFormatChanged( Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) { videoFormat = format; analyticsCollector.onVideoInputFormatChanged(format, decoderReuseEvaluation); } @Override public void onDroppedFrames(int count, long elapsed) { analyticsCollector.onDroppedFrames(count, elapsed); } @Override public void onVideoSizeChanged(VideoSize videoSize) { ExoPlayerImpl.this.videoSize = videoSize; analyticsCollector.onVideoSizeChanged(videoSize); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onVideoSizeChanged(videoSize); } } @Override public void onRenderedFirstFrame(Object output, long renderTimeMs) { analyticsCollector.onRenderedFirstFrame(output, renderTimeMs); if (videoOutput == output) { // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onRenderedFirstFrame(); } } } @Override public void onVideoDecoderReleased(String decoderName) { analyticsCollector.onVideoDecoderReleased(decoderName); } @Override public void onVideoDisabled(DecoderCounters counters) { analyticsCollector.onVideoDisabled(counters); videoFormat = null; videoDecoderCounters = null; } @Override public void onVideoFrameProcessingOffset(long totalProcessingOffsetUs, int frameCount) { analyticsCollector.onVideoFrameProcessingOffset(totalProcessingOffsetUs, frameCount); } @Override public void onVideoCodecError(Exception videoCodecError) { analyticsCollector.onVideoCodecError(videoCodecError); } // AudioRendererEventListener implementation @Override public void onAudioEnabled(DecoderCounters counters) { audioDecoderCounters = counters; analyticsCollector.onAudioEnabled(counters); } @Override public void onAudioDecoderInitialized( String decoderName, long initializedTimestampMs, long initializationDurationMs) { analyticsCollector.onAudioDecoderInitialized( decoderName, initializedTimestampMs, initializationDurationMs); } @Override public void onAudioInputFormatChanged( Format format, @Nullable DecoderReuseEvaluation decoderReuseEvaluation) { audioFormat = format; analyticsCollector.onAudioInputFormatChanged(format, decoderReuseEvaluation); } @Override public void onAudioPositionAdvancing(long playoutStartSystemTimeMs) { analyticsCollector.onAudioPositionAdvancing(playoutStartSystemTimeMs); } @Override public void onAudioUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) { analyticsCollector.onAudioUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs); } @Override public void onAudioDecoderReleased(String decoderName) { analyticsCollector.onAudioDecoderReleased(decoderName); } @Override public void onAudioDisabled(DecoderCounters counters) { analyticsCollector.onAudioDisabled(counters); audioFormat = null; audioDecoderCounters = null; } @Override public void onSkipSilenceEnabledChanged(boolean skipSilenceEnabled) { if (ExoPlayerImpl.this.skipSilenceEnabled == skipSilenceEnabled) { return; } ExoPlayerImpl.this.skipSilenceEnabled = skipSilenceEnabled; notifySkipSilenceEnabledChanged(); } @Override public void onAudioSinkError(Exception audioSinkError) { analyticsCollector.onAudioSinkError(audioSinkError); } @Override public void onAudioCodecError(Exception audioCodecError) { analyticsCollector.onAudioCodecError(audioCodecError); } // TextOutput implementation @Override public void onCues(List<Cue> cues) { currentCues = cues; analyticsCollector.onCues(cues); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listeners : listenerArraySet) { listeners.onCues(cues); } } // MetadataOutput implementation @Override public void onMetadata(Metadata metadata) { analyticsCollector.onMetadata(metadata); ExoPlayerImpl.this.onMetadata(metadata); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onMetadata(metadata); } } // SurfaceHolder.Callback implementation @Override public void surfaceCreated(SurfaceHolder holder) { if (surfaceHolderSurfaceIsVideoOutput) { setVideoOutputInternal(holder.getSurface()); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { maybeNotifySurfaceSizeChanged(width, height); } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (surfaceHolderSurfaceIsVideoOutput) { setVideoOutputInternal(/* videoOutput= */ null); } maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); } // TextureView.SurfaceTextureListener implementation @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { setSurfaceTextureInternal(surfaceTexture); maybeNotifySurfaceSizeChanged(width, height); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { maybeNotifySurfaceSizeChanged(width, height); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) { setVideoOutputInternal(/* videoOutput= */ null); maybeNotifySurfaceSizeChanged(/* width= */ 0, /* height= */ 0); return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) { // Do nothing. } // SphericalGLSurfaceView.VideoSurfaceListener @Override public void onVideoSurfaceCreated(Surface surface) { setVideoOutputInternal(surface); } @Override public void onVideoSurfaceDestroyed(Surface surface) { setVideoOutputInternal(/* videoOutput= */ null); } // AudioFocusManager.PlayerControl implementation @Override public void setVolumeMultiplier(float volumeMultiplier) { sendVolumeToRenderers(); } @Override public void executePlayerCommand(@AudioFocusManager.PlayerCommand int playerCommand) { boolean playWhenReady = getPlayWhenReady(); updatePlayWhenReady( playWhenReady, playerCommand, getPlayWhenReadyChangeReason(playWhenReady, playerCommand)); } // AudioBecomingNoisyManager.EventListener implementation. @Override public void onAudioBecomingNoisy() { updatePlayWhenReady( /* playWhenReady= */ false, AudioFocusManager.PLAYER_COMMAND_DO_NOT_PLAY, Player.PLAY_WHEN_READY_CHANGE_REASON_AUDIO_BECOMING_NOISY); } // StreamVolumeManager.Listener implementation. @Override public void onStreamTypeChanged(@C.StreamType int streamType) { DeviceInfo deviceInfo = createDeviceInfo(streamVolumeManager); if (!deviceInfo.equals(ExoPlayerImpl.this.deviceInfo)) { ExoPlayerImpl.this.deviceInfo = deviceInfo; analyticsCollector.onDeviceInfoChanged(deviceInfo); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onDeviceInfoChanged(deviceInfo); } } } @Override public void onStreamVolumeChanged(int streamVolume, boolean streamMuted) { analyticsCollector.onDeviceVolumeChanged(streamVolume, streamMuted); // TODO(internal b/187152483): Events should be dispatched via ListenerSet for (Listener listener : listenerArraySet) { listener.onDeviceVolumeChanged(streamVolume, streamMuted); } } // Player.Listener implementation. @Override public void onIsLoadingChanged(boolean isLoading) { if (priorityTaskManager != null) { if (isLoading && !isPriorityTaskManagerRegistered) { priorityTaskManager.add(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = true; } else if (!isLoading && isPriorityTaskManagerRegistered) { priorityTaskManager.remove(C.PRIORITY_PLAYBACK); isPriorityTaskManagerRegistered = false; } } } @Override public void onPlaybackStateChanged(@State int playbackState) { updateWakeAndWifiLock(); } @Override public void onPlayWhenReadyChanged( boolean playWhenReady, @PlayWhenReadyChangeReason int reason) { updateWakeAndWifiLock(); } // Player.AudioOffloadListener implementation. @Override public void onExperimentalSleepingForOffloadChanged(boolean sleepingForOffload) { updateWakeAndWifiLock(); } } /** Listeners that are called on the playback thread. */ private static final class FrameMetadataListener implements VideoFrameMetadataListener, CameraMotionListener, PlayerMessage.Target { public static final @MessageType int MSG_SET_VIDEO_FRAME_METADATA_LISTENER = Renderer.MSG_SET_VIDEO_FRAME_METADATA_LISTENER; public static final @MessageType int MSG_SET_CAMERA_MOTION_LISTENER = Renderer.MSG_SET_CAMERA_MOTION_LISTENER; public static final @MessageType int MSG_SET_SPHERICAL_SURFACE_VIEW = Renderer.MSG_CUSTOM_BASE; @Nullable private VideoFrameMetadataListener videoFrameMetadataListener; @Nullable private CameraMotionListener cameraMotionListener; @Nullable private VideoFrameMetadataListener internalVideoFrameMetadataListener; @Nullable private CameraMotionListener internalCameraMotionListener; @Override public void handleMessage(@MessageType int messageType, @Nullable Object message) { switch (messageType) { case MSG_SET_VIDEO_FRAME_METADATA_LISTENER: videoFrameMetadataListener = (VideoFrameMetadataListener) message; break; case MSG_SET_CAMERA_MOTION_LISTENER: cameraMotionListener = (CameraMotionListener) message; break; case MSG_SET_SPHERICAL_SURFACE_VIEW: @Nullable SphericalGLSurfaceView surfaceView = (SphericalGLSurfaceView) message; if (surfaceView == null) { internalVideoFrameMetadataListener = null; internalCameraMotionListener = null; } else { internalVideoFrameMetadataListener = surfaceView.getVideoFrameMetadataListener(); internalCameraMotionListener = surfaceView.getCameraMotionListener(); } break; case Renderer.MSG_SET_AUDIO_ATTRIBUTES: case Renderer.MSG_SET_AUDIO_SESSION_ID: case Renderer.MSG_SET_AUX_EFFECT_INFO: case Renderer.MSG_SET_CHANGE_FRAME_RATE_STRATEGY: case Renderer.MSG_SET_SCALING_MODE: case Renderer.MSG_SET_SKIP_SILENCE_ENABLED: case Renderer.MSG_SET_VIDEO_OUTPUT: case Renderer.MSG_SET_VOLUME: case Renderer.MSG_SET_WAKEUP_LISTENER: default: break; } } // VideoFrameMetadataListener @Override public void onVideoFrameAboutToBeRendered( long presentationTimeUs, long releaseTimeNs, Format format, @Nullable MediaFormat mediaFormat) { if (internalVideoFrameMetadataListener != null) { internalVideoFrameMetadataListener.onVideoFrameAboutToBeRendered( presentationTimeUs, releaseTimeNs, format, mediaFormat); } if (videoFrameMetadataListener != null) { videoFrameMetadataListener.onVideoFrameAboutToBeRendered( presentationTimeUs, releaseTimeNs, format, mediaFormat); } } // CameraMotionListener @Override public void onCameraMotion(long timeUs, float[] rotation) { if (internalCameraMotionListener != null) { internalCameraMotionListener.onCameraMotion(timeUs, rotation); } if (cameraMotionListener != null) { cameraMotionListener.onCameraMotion(timeUs, rotation); } } @Override public void onCameraMotionReset() { if (internalCameraMotionListener != null) { internalCameraMotionListener.onCameraMotionReset(); } if (cameraMotionListener != null) { cameraMotionListener.onCameraMotionReset(); } } } @RequiresApi(31) private static final class Api31 { private Api31() {} @DoNotInline public static PlayerId createPlayerId() { // TODO: Create a MediaMetricsListener and obtain LogSessionId from it. return new PlayerId(LogSessionId.LOG_SESSION_ID_NONE); } } }
Remove self-listening from ExoPlayerImpl SimpleExoPlayer used to register a listener on ExoPlayerImpl for the old EventListener callbacks. Now both classes are merged, this is no longer needed and should be removed in favor of calling methods directly. #minor-release PiperOrigin-RevId: 427187875
libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlayerImpl.java
Remove self-listening from ExoPlayerImpl
Java
apache-2.0
918c251891109e8877f569f1ef23d437d6bb30d0
0
scholzj/barnabas,scholzj/barnabas,ppatierno/kaas,ppatierno/kaas
/* * 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.common; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.WatcherException; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.Meter; import io.strimzi.api.kafka.model.Spec; import io.strimzi.api.kafka.model.status.Condition; import io.strimzi.api.kafka.model.status.ConditionBuilder; import io.strimzi.api.kafka.model.status.Status; import io.strimzi.operator.cluster.model.InvalidResourceException; import io.strimzi.operator.cluster.model.StatusDiff; import io.strimzi.operator.common.model.Labels; import io.strimzi.operator.common.model.NamespaceAndName; import io.strimzi.operator.common.model.ResourceVisitor; import io.strimzi.operator.common.model.ValidationVisitor; import io.strimzi.operator.common.operator.resource.AbstractWatchableStatusedResourceOperator; import io.strimzi.operator.common.operator.resource.ReconcileResult; import io.strimzi.operator.common.operator.resource.StatusUtils; import io.strimzi.operator.common.operator.resource.TimeoutException; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.core.shareddata.Lock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Map; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import static io.strimzi.operator.common.Util.async; /** * A base implementation of {@link Operator}. * * <ul> * <li>uses the Fabric8 kubernetes API and implements * {@link #reconcile(Reconciliation)} by delegating to abstract {@link #createOrUpdate(Reconciliation, CustomResource)} * and {@link #delete(Reconciliation)} methods for subclasses to implement. * * <li>add support for operator-side {@linkplain #validate(CustomResource) validation}. * This can be used to automatically log warnings about source resources which used deprecated part of the CR API. *ą * </ul> * @param <T> The Java representation of the Kubernetes resource, e.g. {@code Kafka} or {@code KafkaConnect} * @param <O> The "Resource Operator" for the source resource type. Typically this will be some instantiation of * {@link io.strimzi.operator.common.operator.resource.CrdOperator}. */ public abstract class AbstractOperator< T extends CustomResource<P, S>, P extends Spec, S extends Status, O extends AbstractWatchableStatusedResourceOperator<?, T, ?, ?>> implements Operator { private static final Logger log = LogManager.getLogger(AbstractOperator.class); private static final long PROGRESS_WARNING = 60_000L; protected static final int LOCK_TIMEOUT_MS = 10000; public static final String METRICS_PREFIX = "strimzi."; protected final Vertx vertx; protected final O resourceOperator; private final String kind; private final Optional<LabelSelector> selector; protected final MetricsProvider metrics; private final Counter periodicReconciliationsCounter; private final Counter reconciliationsCounter; private final Counter failedReconciliationsCounter; private final Counter successfulReconciliationsCounter; private final Counter lockedReconciliationsCounter; private final AtomicInteger pausedResourceCounter; private final AtomicInteger resourceCounter; private final Timer reconciliationsTimer; private final Map<Tags, AtomicInteger> resourcesStateCounter; public AbstractOperator(Vertx vertx, String kind, O resourceOperator, MetricsProvider metrics, Labels selectorLabels) { this.vertx = vertx; this.kind = kind; this.resourceOperator = resourceOperator; this.selector = (selectorLabels == null || selectorLabels.toMap().isEmpty()) ? Optional.empty() : Optional.of(new LabelSelector(null, selectorLabels.toMap())); this.metrics = metrics; // Setup metrics Tags metricTags = Tags.of(Tag.of("kind", kind())); periodicReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.periodical", "Number of periodical reconciliations done by the operator", metricTags); reconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations", "Number of reconciliations done by the operator for individual resources", metricTags); pausedResourceCounter = metrics.gauge(METRICS_PREFIX + "resources.paused", "Number of custom resources the operator sees but does not reconcile due to paused reconciliations", metricTags); failedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.failed", "Number of reconciliations done by the operator for individual resources which failed", metricTags); successfulReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.successful", "Number of reconciliations done by the operator for individual resources which were successful", metricTags); lockedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.locked", "Number of reconciliations skipped because another reconciliation for the same resource was still running", metricTags); resourceCounter = metrics.gauge(METRICS_PREFIX + "resources", "Number of custom resources the operator sees", metricTags); reconciliationsTimer = metrics.timer(METRICS_PREFIX + "reconciliations.duration", "The time the reconciliation takes to complete", metricTags); resourcesStateCounter = new ConcurrentHashMap<>(); } @Override public String kind() { return kind; } /** * Gets the name of the lock to be used for operating on the given {@code namespace} and * cluster {@code name} * * @param namespace The namespace containing the cluster * @param name The name of the cluster */ private String getLockName(String namespace, String name) { return "lock::" + namespace + "::" + kind() + "::" + name; } /** * Asynchronously creates or updates the given {@code resource}. * This method can be called when the given {@code resource} has been created, * or updated and also at some regular interval while the resource continues to exist in Kubernetes. * The calling of this method does not imply that anything has actually changed. * @param reconciliation Uniquely identifies the reconciliation itself. * @param resource The resource to be created, or updated. * @return A Future which is completed once the reconciliation of the given resource instance is complete. */ protected abstract Future<S> createOrUpdate(Reconciliation reconciliation, T resource); /** * Asynchronously deletes the resource identified by {@code reconciliation}. * Operators which only create other Kubernetes resources in order to honour their source resource can rely * on Kubernetes Garbage Collection to handle deletion. * Such operators should return a Future which completes with {@code false}. * Operators which handle deletion themselves should return a Future which completes with {@code true}. * @param reconciliation * @return */ protected abstract Future<Boolean> delete(Reconciliation reconciliation); /** * Reconcile assembly resources in the given namespace having the given {@code name}. * Reconciliation works by getting the assembly resource (e.g. {@code KafkaUser}) * in the given namespace with the given name and * comparing with the corresponding resource. * @param reconciliation The reconciliation. * @return A Future which is completed with the result of the reconciliation. */ @Override @SuppressWarnings("unchecked") public final Future<Void> reconcile(Reconciliation reconciliation) { String namespace = reconciliation.namespace(); String name = reconciliation.name(); reconciliationsCounter.increment(); Timer.Sample reconciliationTimerSample = Timer.start(metrics.meterRegistry()); Future<Void> handler = withLock(reconciliation, LOCK_TIMEOUT_MS, () -> { T cr = resourceOperator.get(namespace, name); if (cr != null) { if (!Util.matchesSelector(selector(), cr)) { // When the labels matching the selector are removed from the custom resource, a DELETE event is // triggered by the watch even through the custom resource might not match the watch labels anymore // and might not be really deleted. We have to filter these situations out and ignore the // reconciliation because such resource might be already operated by another instance (where the // same change triggered ADDED event). log.debug("{}: {} {} in namespace {} does not match label selector {} and will be ignored", reconciliation, kind(), name, namespace, selector().get().getMatchLabels()); return Future.succeededFuture(); } Promise<Void> createOrUpdate = Promise.promise(); if (Annotations.isReconciliationPausedWithAnnotation(cr)) { S status = createStatus(); Set<Condition> conditions = validate(cr); conditions.add(StatusUtils.getPausedCondition()); status.setConditions(new ArrayList<>(conditions)); status.setObservedGeneration(cr.getStatus() != null ? cr.getStatus().getObservedGeneration() : 0); updateStatus(reconciliation, status).onComplete(statusResult -> { if (statusResult.succeeded()) { createOrUpdate.complete(); } else { createOrUpdate.fail(statusResult.cause()); } }); getPausedResourceCounter().getAndIncrement(); log.debug("{}: Reconciliation of {} {} is paused", reconciliation, kind, name); return createOrUpdate.future(); } else if (cr.getSpec() == null) { InvalidResourceException exception = new InvalidResourceException("Spec cannot be null"); S status = createStatus(); Condition errorCondition = new ConditionBuilder() .withLastTransitionTime(StatusUtils.iso8601Now()) .withType("NotReady") .withStatus("True") .withReason(exception.getClass().getSimpleName()) .withMessage(exception.getMessage()) .build(); status.setObservedGeneration(cr.getMetadata().getGeneration()); status.addCondition(errorCondition); log.error("{}: {} spec cannot be null", reconciliation, cr.getMetadata().getName()); updateStatus(reconciliation, status).onComplete(notUsed -> { createOrUpdate.fail(exception); }); return createOrUpdate.future(); } Set<Condition> unknownAndDeprecatedConditions = validate(cr); log.info("{}: {} {} will be checked for creation or modification", reconciliation, kind, name); createOrUpdate(reconciliation, cr) .onComplete(res -> { if (res.succeeded()) { S status = res.result(); addWarningsToStatus(status, unknownAndDeprecatedConditions); updateStatus(reconciliation, status).onComplete(statusResult -> { if (statusResult.succeeded()) { createOrUpdate.complete(); } else { createOrUpdate.fail(statusResult.cause()); } }); } else { if (res.cause() instanceof ReconciliationException) { ReconciliationException e = (ReconciliationException) res.cause(); Status status = e.getStatus(); addWarningsToStatus(status, unknownAndDeprecatedConditions); log.error("{}: createOrUpdate failed", reconciliation, e.getCause()); updateStatus(reconciliation, (S) status).onComplete(statusResult -> { createOrUpdate.fail(e.getCause()); }); } else { log.error("{}: createOrUpdate failed", reconciliation, res.cause()); createOrUpdate.fail(res.cause()); } } }); return createOrUpdate.future(); } else { log.info("{}: {} {} should be deleted", reconciliation, kind, name); return delete(reconciliation).map(deleteResult -> { if (deleteResult) { log.info("{}: {} {} deleted", reconciliation, kind, name); } else { log.info("{}: Assembly {} or some parts of it will be deleted by garbage collection", reconciliation, name); } return (Void) null; }).recover(deleteResult -> { log.error("{}: Deletion of {} {} failed", reconciliation, kind, name, deleteResult); return Future.failedFuture(deleteResult); }); } }); Promise<Void> result = Promise.promise(); handler.onComplete(reconcileResult -> { handleResult(reconciliation, reconcileResult, reconciliationTimerSample); result.handle(reconcileResult); }); return result.future(); } protected void addWarningsToStatus(Status status, Set<Condition> unknownAndDeprecatedConditions) { if (status != null) { status.addConditions(unknownAndDeprecatedConditions); } } /** * Updates the Status field of the Kafka CR. It diffs the desired status against the current status and calls * the update only when there is any difference in non-timestamp fields. * * @param reconciliation the reconciliation identified * @param desiredStatus The KafkaStatus which should be set * * @return */ Future<Void> updateStatus(Reconciliation reconciliation, S desiredStatus) { if (desiredStatus == null) { log.debug("{}: Desired status is null - status will not be updated", reconciliation); return Future.succeededFuture(); } String namespace = reconciliation.namespace(); String name = reconciliation.name(); return resourceOperator.getAsync(namespace, name) .compose(res -> { if (res != null) { S currentStatus = res.getStatus(); StatusDiff sDiff = new StatusDiff(currentStatus, desiredStatus); if (!sDiff.isEmpty()) { res.setStatus(desiredStatus); return resourceOperator.updateStatusAsync(res) .compose(notUsed -> { log.debug("{}: Completed status update", reconciliation); return Future.succeededFuture(); }, error -> { log.error("{}: Failed to update status", reconciliation, error); return Future.failedFuture(error); }); } else { log.debug("{}: Status did not change", reconciliation); return Future.succeededFuture(); } } else { log.error("{}: Current {} resource not found", reconciliation, reconciliation.kind()); return Future.failedFuture("Current " + reconciliation.kind() + " resource with name " + name + " not found"); } }, error -> { log.error("{}: Failed to get the current {} resource and its status", reconciliation, reconciliation.kind(), error); return Future.failedFuture(error); }); } protected abstract S createStatus(); /** * The exception by which Futures returned by {@link #withLock(Reconciliation, long, Callable)} are failed when * the lock cannot be acquired within the timeout. */ static class UnableToAcquireLockException extends TimeoutException { } /** * Acquire the lock for the resource implied by the {@code reconciliation} * and call the given {@code callable} with the lock held. * Once the callable returns (or if it throws) release the lock and complete the returned Future. * If the lock cannot be acquired the given {@code callable} is not called and the returned Future is completed with {@link UnableToAcquireLockException}. * @param reconciliation * @param callable * @param <T> * @return */ protected final <T> Future<T> withLock(Reconciliation reconciliation, long lockTimeoutMs, Callable<Future<T>> callable) { Promise<T> handler = Promise.promise(); String namespace = reconciliation.namespace(); String name = reconciliation.name(); final String lockName = getLockName(namespace, name); log.debug("{}: Try to acquire lock {}", reconciliation, lockName); vertx.sharedData().getLockWithTimeout(lockName, lockTimeoutMs, res -> { if (res.succeeded()) { log.debug("{}: Lock {} acquired", reconciliation, lockName); Lock lock = res.result(); long timerId = vertx.setPeriodic(PROGRESS_WARNING, timer -> { log.info("{}: Reconciliation is in progress", reconciliation); }); try { callable.call().onComplete(callableRes -> { if (callableRes.succeeded()) { handler.complete(callableRes.result()); } else { handler.fail(callableRes.cause()); } vertx.cancelTimer(timerId); lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); }); } catch (Throwable ex) { vertx.cancelTimer(timerId); lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); log.error("{}: Reconciliation failed", reconciliation, ex); handler.fail(ex); } } else { log.debug("{}: Failed to acquire lock {} within {}ms.", reconciliation, lockName, lockTimeoutMs); handler.fail(new UnableToAcquireLockException()); } }); return handler.future(); } /** * Validate the Custom Resource. * This should log at the WARN level (rather than throwing) * if the resource can safely be reconciled (e.g. it merely using deprecated API). * @param resource The custom resource * @throws InvalidResourceException if the resource cannot be safely reconciled. * @return set of conditions */ /*test*/ public Set<Condition> validate(T resource) { if (resource != null) { Set<Condition> warningConditions = new LinkedHashSet<>(0); ResourceVisitor.visit(resource, new ValidationVisitor(resource, log, warningConditions)); return warningConditions; } return Collections.emptySet(); } public Future<Set<NamespaceAndName>> allResourceNames(String namespace) { return resourceOperator.listAsync(namespace, selector()) .map(resourceList -> resourceList.stream() .map(resource -> new NamespaceAndName(resource.getMetadata().getNamespace(), resource.getMetadata().getName())) .collect(Collectors.toSet())); } /** * A selector to narrow the scope of the {@linkplain #createWatch(String, Consumer) watch} * and {@linkplain #allResourceNames(String) query}. * @return A selector. */ public Optional<LabelSelector> selector() { return selector; } /** * Create Kubernetes watch. * * @param namespace Namespace where to watch for users. * @param onClose Callback called when the watch is closed. * * @return A future which completes when the watcher has been created. */ public Future<Watch> createWatch(String namespace, Consumer<WatcherException> onClose) { return async(vertx, () -> resourceOperator.watch(namespace, selector(), new OperatorWatcher<>(this, namespace, onClose))); } public Consumer<WatcherException> recreateWatch(String namespace) { Consumer<WatcherException> kubernetesClientExceptionConsumer = new Consumer<WatcherException>() { @Override public void accept(WatcherException e) { if (e != null) { log.error("Watcher closed with exception in namespace {}", namespace, e); createWatch(namespace, this); } else { log.info("Watcher closed in namespace {}", namespace); } } }; return kubernetesClientExceptionConsumer; } /** * Log the reconciliation outcome. */ private void handleResult(Reconciliation reconciliation, AsyncResult<Void> result, Timer.Sample reconciliationTimerSample) { if (result.succeeded()) { updateResourceState(reconciliation, true); successfulReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.info("{}: reconciled", reconciliation); } else { Throwable cause = result.cause(); if (cause instanceof InvalidConfigParameterException) { updateResourceState(reconciliation, false); failedReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.warn("{}: Failed to reconcile {}", reconciliation, cause.getMessage()); } else if (cause instanceof UnableToAcquireLockException) { lockedReconciliationsCounter.increment(); } else { updateResourceState(reconciliation, false); failedReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.warn("{}: Failed to reconcile", reconciliation, cause); } } } public Counter getPeriodicReconciliationsCounter() { return periodicReconciliationsCounter; } public AtomicInteger getResourceCounter() { return resourceCounter; } public AtomicInteger getPausedResourceCounter() { return pausedResourceCounter; } /** * Updates the resource state metric for the provided reconciliation which brings kind, name and namespace * of the custom resource. * * @param reconciliation reconciliation to use to update the resource state metric * @param ready if reconcile was successful and the resource is ready */ private void updateResourceState(Reconciliation reconciliation, boolean ready) { Tags metricTags = Tags.of( Tag.of("kind", reconciliation.kind()), Tag.of("name", reconciliation.name()), Tag.of("resource-namespace", reconciliation.namespace())); T cr = resourceOperator.get(reconciliation.namespace(), reconciliation.name()); if (cr != null) { resourcesStateCounter.computeIfAbsent(metricTags, tags -> metrics.gauge(METRICS_PREFIX + "resource.state", "Current state of the resource: 1 ready, 0 fail", tags) ); resourcesStateCounter.get(metricTags).set(ready ? 1 : 0); log.debug("{}: Updated metric " + METRICS_PREFIX + "resource.state{} = {}", reconciliation, metricTags, ready ? 1 : 0); } else { Optional<Meter> gauge = metrics.meterRegistry().getMeters() .stream() .filter(meter -> meter.getId().getName().equals(METRICS_PREFIX + "resource.state") && meter.getId().getTags().equals(metricTags.stream().collect(Collectors.toList())) ).findFirst(); if (gauge.isPresent()) { metrics.meterRegistry().remove(gauge.get().getId()); resourcesStateCounter.remove(metricTags); log.debug("{}: Removed metric " + METRICS_PREFIX + "resource.state{}", reconciliation, metricTags); } } } /** * In some cases, when the ClusterRoleBinding reconciliation fails with RBAC error and the desired object is null, * we want to ignore the error and return success. This is used to let Strimzi work without some Cluster-wide RBAC * rights when the features they are needed for are not used by the user. * * @param reconcileFuture The original reconciliation future * @param desired The desired state of the resource. * @return A future which completes when the resource was reconciled. */ public Future<ReconcileResult<ClusterRoleBinding>> withIgnoreRbacError(Future<ReconcileResult<ClusterRoleBinding>> reconcileFuture, ClusterRoleBinding desired) { return reconcileFuture.compose( rr -> Future.succeededFuture(), e -> { if (desired == null && e.getMessage() != null && e.getMessage().contains("Message: Forbidden!")) { log.debug("Ignoring forbidden access to ClusterRoleBindings resource which does not seem to be required."); return Future.succeededFuture(); } return Future.failedFuture(e.getMessage()); } ); } }
operator-common/src/main/java/io/strimzi/operator/common/AbstractOperator.java
/* * 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.common; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.WatcherException; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.Meter; import io.strimzi.api.kafka.model.Spec; import io.strimzi.api.kafka.model.status.Condition; import io.strimzi.api.kafka.model.status.ConditionBuilder; import io.strimzi.api.kafka.model.status.Status; import io.strimzi.operator.cluster.model.InvalidResourceException; import io.strimzi.operator.cluster.model.StatusDiff; import io.strimzi.operator.common.model.Labels; import io.strimzi.operator.common.model.NamespaceAndName; import io.strimzi.operator.common.model.ResourceVisitor; import io.strimzi.operator.common.model.ValidationVisitor; import io.strimzi.operator.common.operator.resource.AbstractWatchableStatusedResourceOperator; import io.strimzi.operator.common.operator.resource.ReconcileResult; import io.strimzi.operator.common.operator.resource.StatusUtils; import io.strimzi.operator.common.operator.resource.TimeoutException; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.core.shareddata.Lock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Map; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import static io.strimzi.operator.common.Util.async; /** * A base implementation of {@link Operator}. * * <ul> * <li>uses the Fabric8 kubernetes API and implements * {@link #reconcile(Reconciliation)} by delegating to abstract {@link #createOrUpdate(Reconciliation, CustomResource)} * and {@link #delete(Reconciliation)} methods for subclasses to implement. * * <li>add support for operator-side {@linkplain #validate(CustomResource) validation}. * This can be used to automatically log warnings about source resources which used deprecated part of the CR API. *ą * </ul> * @param <T> The Java representation of the Kubernetes resource, e.g. {@code Kafka} or {@code KafkaConnect} * @param <O> The "Resource Operator" for the source resource type. Typically this will be some instantiation of * {@link io.strimzi.operator.common.operator.resource.CrdOperator}. */ public abstract class AbstractOperator< T extends CustomResource<P, S>, P extends Spec, S extends Status, O extends AbstractWatchableStatusedResourceOperator<?, T, ?, ?>> implements Operator { private static final Logger log = LogManager.getLogger(AbstractOperator.class); protected static final int LOCK_TIMEOUT_MS = 10000; public static final String METRICS_PREFIX = "strimzi."; protected final Vertx vertx; protected final O resourceOperator; private final String kind; private final Optional<LabelSelector> selector; protected final MetricsProvider metrics; private final Counter periodicReconciliationsCounter; private final Counter reconciliationsCounter; private final Counter failedReconciliationsCounter; private final Counter successfulReconciliationsCounter; private final Counter lockedReconciliationsCounter; private final AtomicInteger pausedResourceCounter; private final AtomicInteger resourceCounter; private final Timer reconciliationsTimer; private final Map<Tags, AtomicInteger> resourcesStateCounter; public AbstractOperator(Vertx vertx, String kind, O resourceOperator, MetricsProvider metrics, Labels selectorLabels) { this.vertx = vertx; this.kind = kind; this.resourceOperator = resourceOperator; this.selector = (selectorLabels == null || selectorLabels.toMap().isEmpty()) ? Optional.empty() : Optional.of(new LabelSelector(null, selectorLabels.toMap())); this.metrics = metrics; // Setup metrics Tags metricTags = Tags.of(Tag.of("kind", kind())); periodicReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.periodical", "Number of periodical reconciliations done by the operator", metricTags); reconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations", "Number of reconciliations done by the operator for individual resources", metricTags); pausedResourceCounter = metrics.gauge(METRICS_PREFIX + "resources.paused", "Number of custom resources the operator sees but does not reconcile due to paused reconciliations", metricTags); failedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.failed", "Number of reconciliations done by the operator for individual resources which failed", metricTags); successfulReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.successful", "Number of reconciliations done by the operator for individual resources which were successful", metricTags); lockedReconciliationsCounter = metrics.counter(METRICS_PREFIX + "reconciliations.locked", "Number of reconciliations skipped because another reconciliation for the same resource was still running", metricTags); resourceCounter = metrics.gauge(METRICS_PREFIX + "resources", "Number of custom resources the operator sees", metricTags); reconciliationsTimer = metrics.timer(METRICS_PREFIX + "reconciliations.duration", "The time the reconciliation takes to complete", metricTags); resourcesStateCounter = new ConcurrentHashMap<>(); } @Override public String kind() { return kind; } /** * Gets the name of the lock to be used for operating on the given {@code namespace} and * cluster {@code name} * * @param namespace The namespace containing the cluster * @param name The name of the cluster */ private String getLockName(String namespace, String name) { return "lock::" + namespace + "::" + kind() + "::" + name; } /** * Asynchronously creates or updates the given {@code resource}. * This method can be called when the given {@code resource} has been created, * or updated and also at some regular interval while the resource continues to exist in Kubernetes. * The calling of this method does not imply that anything has actually changed. * @param reconciliation Uniquely identifies the reconciliation itself. * @param resource The resource to be created, or updated. * @return A Future which is completed once the reconciliation of the given resource instance is complete. */ protected abstract Future<S> createOrUpdate(Reconciliation reconciliation, T resource); /** * Asynchronously deletes the resource identified by {@code reconciliation}. * Operators which only create other Kubernetes resources in order to honour their source resource can rely * on Kubernetes Garbage Collection to handle deletion. * Such operators should return a Future which completes with {@code false}. * Operators which handle deletion themselves should return a Future which completes with {@code true}. * @param reconciliation * @return */ protected abstract Future<Boolean> delete(Reconciliation reconciliation); /** * Reconcile assembly resources in the given namespace having the given {@code name}. * Reconciliation works by getting the assembly resource (e.g. {@code KafkaUser}) * in the given namespace with the given name and * comparing with the corresponding resource. * @param reconciliation The reconciliation. * @return A Future which is completed with the result of the reconciliation. */ @Override @SuppressWarnings("unchecked") public final Future<Void> reconcile(Reconciliation reconciliation) { String namespace = reconciliation.namespace(); String name = reconciliation.name(); reconciliationsCounter.increment(); Timer.Sample reconciliationTimerSample = Timer.start(metrics.meterRegistry()); Future<Void> handler = withLock(reconciliation, LOCK_TIMEOUT_MS, () -> { T cr = resourceOperator.get(namespace, name); if (cr != null) { if (!Util.matchesSelector(selector(), cr)) { // When the labels matching the selector are removed from the custom resource, a DELETE event is // triggered by the watch even through the custom resource might not match the watch labels anymore // and might not be really deleted. We have to filter these situations out and ignore the // reconciliation because such resource might be already operated by another instance (where the // same change triggered ADDED event). log.debug("{}: {} {} in namespace {} does not match label selector {} and will be ignored", reconciliation, kind(), name, namespace, selector().get().getMatchLabels()); return Future.succeededFuture(); } Promise<Void> createOrUpdate = Promise.promise(); if (Annotations.isReconciliationPausedWithAnnotation(cr)) { S status = createStatus(); Set<Condition> conditions = validate(cr); conditions.add(StatusUtils.getPausedCondition()); status.setConditions(new ArrayList<>(conditions)); status.setObservedGeneration(cr.getStatus() != null ? cr.getStatus().getObservedGeneration() : 0); updateStatus(reconciliation, status).onComplete(statusResult -> { if (statusResult.succeeded()) { createOrUpdate.complete(); } else { createOrUpdate.fail(statusResult.cause()); } }); getPausedResourceCounter().getAndIncrement(); log.debug("{}: Reconciliation of {} {} is paused", reconciliation, kind, name); return createOrUpdate.future(); } else if (cr.getSpec() == null) { InvalidResourceException exception = new InvalidResourceException("Spec cannot be null"); S status = createStatus(); Condition errorCondition = new ConditionBuilder() .withLastTransitionTime(StatusUtils.iso8601Now()) .withType("NotReady") .withStatus("True") .withReason(exception.getClass().getSimpleName()) .withMessage(exception.getMessage()) .build(); status.setObservedGeneration(cr.getMetadata().getGeneration()); status.addCondition(errorCondition); log.error("{}: {} spec cannot be null", reconciliation, cr.getMetadata().getName()); updateStatus(reconciliation, status).onComplete(notUsed -> { createOrUpdate.fail(exception); }); return createOrUpdate.future(); } Set<Condition> unknownAndDeprecatedConditions = validate(cr); log.info("{}: {} {} will be checked for creation or modification", reconciliation, kind, name); createOrUpdate(reconciliation, cr) .onComplete(res -> { if (res.succeeded()) { S status = res.result(); addWarningsToStatus(status, unknownAndDeprecatedConditions); updateStatus(reconciliation, status).onComplete(statusResult -> { if (statusResult.succeeded()) { createOrUpdate.complete(); } else { createOrUpdate.fail(statusResult.cause()); } }); } else { if (res.cause() instanceof ReconciliationException) { ReconciliationException e = (ReconciliationException) res.cause(); Status status = e.getStatus(); addWarningsToStatus(status, unknownAndDeprecatedConditions); log.error("{}: createOrUpdate failed", reconciliation, e.getCause()); updateStatus(reconciliation, (S) status).onComplete(statusResult -> { createOrUpdate.fail(e.getCause()); }); } else { log.error("{}: createOrUpdate failed", reconciliation, res.cause()); createOrUpdate.fail(res.cause()); } } }); return createOrUpdate.future(); } else { log.info("{}: {} {} should be deleted", reconciliation, kind, name); return delete(reconciliation).map(deleteResult -> { if (deleteResult) { log.info("{}: {} {} deleted", reconciliation, kind, name); } else { log.info("{}: Assembly {} or some parts of it will be deleted by garbage collection", reconciliation, name); } return (Void) null; }).recover(deleteResult -> { log.error("{}: Deletion of {} {} failed", reconciliation, kind, name, deleteResult); return Future.failedFuture(deleteResult); }); } }); Promise<Void> result = Promise.promise(); handler.onComplete(reconcileResult -> { handleResult(reconciliation, reconcileResult, reconciliationTimerSample); result.handle(reconcileResult); }); return result.future(); } protected void addWarningsToStatus(Status status, Set<Condition> unknownAndDeprecatedConditions) { if (status != null) { status.addConditions(unknownAndDeprecatedConditions); } } /** * Updates the Status field of the Kafka CR. It diffs the desired status against the current status and calls * the update only when there is any difference in non-timestamp fields. * * @param reconciliation the reconciliation identified * @param desiredStatus The KafkaStatus which should be set * * @return */ Future<Void> updateStatus(Reconciliation reconciliation, S desiredStatus) { if (desiredStatus == null) { log.debug("{}: Desired status is null - status will not be updated", reconciliation); return Future.succeededFuture(); } String namespace = reconciliation.namespace(); String name = reconciliation.name(); return resourceOperator.getAsync(namespace, name) .compose(res -> { if (res != null) { S currentStatus = res.getStatus(); StatusDiff sDiff = new StatusDiff(currentStatus, desiredStatus); if (!sDiff.isEmpty()) { res.setStatus(desiredStatus); return resourceOperator.updateStatusAsync(res) .compose(notUsed -> { log.debug("{}: Completed status update", reconciliation); return Future.succeededFuture(); }, error -> { log.error("{}: Failed to update status", reconciliation, error); return Future.failedFuture(error); }); } else { log.debug("{}: Status did not change", reconciliation); return Future.succeededFuture(); } } else { log.error("{}: Current {} resource not found", reconciliation, reconciliation.kind()); return Future.failedFuture("Current " + reconciliation.kind() + " resource with name " + name + " not found"); } }, error -> { log.error("{}: Failed to get the current {} resource and its status", reconciliation, reconciliation.kind(), error); return Future.failedFuture(error); }); } protected abstract S createStatus(); /** * The exception by which Futures returned by {@link #withLock(Reconciliation, long, Callable)} are failed when * the lock cannot be acquired within the timeout. */ static class UnableToAcquireLockException extends TimeoutException { } /** * Acquire the lock for the resource implied by the {@code reconciliation} * and call the given {@code callable} with the lock held. * Once the callable returns (or if it throws) release the lock and complete the returned Future. * If the lock cannot be acquired the given {@code callable} is not called and the returned Future is completed with {@link UnableToAcquireLockException}. * @param reconciliation * @param callable * @param <T> * @return */ protected final <T> Future<T> withLock(Reconciliation reconciliation, long lockTimeoutMs, Callable<Future<T>> callable) { Promise<T> handler = Promise.promise(); String namespace = reconciliation.namespace(); String name = reconciliation.name(); final String lockName = getLockName(namespace, name); log.debug("{}: Try to acquire lock {}", reconciliation, lockName); vertx.sharedData().getLockWithTimeout(lockName, lockTimeoutMs, res -> { if (res.succeeded()) { log.debug("{}: Lock {} acquired", reconciliation, lockName); Lock lock = res.result(); try { callable.call().onComplete(callableRes -> { if (callableRes.succeeded()) { handler.complete(callableRes.result()); } else { handler.fail(callableRes.cause()); } lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); }); } catch (Throwable ex) { lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); log.error("{}: Reconciliation failed", reconciliation, ex); handler.fail(ex); } } else { log.warn("{}: Failed to acquire lock {} within {}ms.", reconciliation, lockName, lockTimeoutMs); handler.fail(new UnableToAcquireLockException()); } }); return handler.future(); } /** * Validate the Custom Resource. * This should log at the WARN level (rather than throwing) * if the resource can safely be reconciled (e.g. it merely using deprecated API). * @param resource The custom resource * @throws InvalidResourceException if the resource cannot be safely reconciled. * @return set of conditions */ /*test*/ public Set<Condition> validate(T resource) { if (resource != null) { Set<Condition> warningConditions = new LinkedHashSet<>(0); ResourceVisitor.visit(resource, new ValidationVisitor(resource, log, warningConditions)); return warningConditions; } return Collections.emptySet(); } public Future<Set<NamespaceAndName>> allResourceNames(String namespace) { return resourceOperator.listAsync(namespace, selector()) .map(resourceList -> resourceList.stream() .map(resource -> new NamespaceAndName(resource.getMetadata().getNamespace(), resource.getMetadata().getName())) .collect(Collectors.toSet())); } /** * A selector to narrow the scope of the {@linkplain #createWatch(String, Consumer) watch} * and {@linkplain #allResourceNames(String) query}. * @return A selector. */ public Optional<LabelSelector> selector() { return selector; } /** * Create Kubernetes watch. * * @param namespace Namespace where to watch for users. * @param onClose Callback called when the watch is closed. * * @return A future which completes when the watcher has been created. */ public Future<Watch> createWatch(String namespace, Consumer<WatcherException> onClose) { return async(vertx, () -> resourceOperator.watch(namespace, selector(), new OperatorWatcher<>(this, namespace, onClose))); } public Consumer<WatcherException> recreateWatch(String namespace) { Consumer<WatcherException> kubernetesClientExceptionConsumer = new Consumer<WatcherException>() { @Override public void accept(WatcherException e) { if (e != null) { log.error("Watcher closed with exception in namespace {}", namespace, e); createWatch(namespace, this); } else { log.info("Watcher closed in namespace {}", namespace); } } }; return kubernetesClientExceptionConsumer; } /** * Log the reconciliation outcome. */ private void handleResult(Reconciliation reconciliation, AsyncResult<Void> result, Timer.Sample reconciliationTimerSample) { if (result.succeeded()) { updateResourceState(reconciliation, true); successfulReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.info("{}: reconciled", reconciliation); } else { Throwable cause = result.cause(); if (cause instanceof InvalidConfigParameterException) { updateResourceState(reconciliation, false); failedReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.warn("{}: Failed to reconcile {}", reconciliation, cause.getMessage()); } else if (cause instanceof UnableToAcquireLockException) { lockedReconciliationsCounter.increment(); } else { updateResourceState(reconciliation, false); failedReconciliationsCounter.increment(); reconciliationTimerSample.stop(reconciliationsTimer); log.warn("{}: Failed to reconcile", reconciliation, cause); } } } public Counter getPeriodicReconciliationsCounter() { return periodicReconciliationsCounter; } public AtomicInteger getResourceCounter() { return resourceCounter; } public AtomicInteger getPausedResourceCounter() { return pausedResourceCounter; } /** * Updates the resource state metric for the provided reconciliation which brings kind, name and namespace * of the custom resource. * * @param reconciliation reconciliation to use to update the resource state metric * @param ready if reconcile was successful and the resource is ready */ private void updateResourceState(Reconciliation reconciliation, boolean ready) { Tags metricTags = Tags.of( Tag.of("kind", reconciliation.kind()), Tag.of("name", reconciliation.name()), Tag.of("resource-namespace", reconciliation.namespace())); T cr = resourceOperator.get(reconciliation.namespace(), reconciliation.name()); if (cr != null) { resourcesStateCounter.computeIfAbsent(metricTags, tags -> metrics.gauge(METRICS_PREFIX + "resource.state", "Current state of the resource: 1 ready, 0 fail", tags) ); resourcesStateCounter.get(metricTags).set(ready ? 1 : 0); log.debug("{}: Updated metric " + METRICS_PREFIX + "resource.state{} = {}", reconciliation, metricTags, ready ? 1 : 0); } else { Optional<Meter> gauge = metrics.meterRegistry().getMeters() .stream() .filter(meter -> meter.getId().getName().equals(METRICS_PREFIX + "resource.state") && meter.getId().getTags().equals(metricTags.stream().collect(Collectors.toList())) ).findFirst(); if (gauge.isPresent()) { metrics.meterRegistry().remove(gauge.get().getId()); resourcesStateCounter.remove(metricTags); log.debug("{}: Removed metric " + METRICS_PREFIX + "resource.state{}", reconciliation, metricTags); } } } /** * In some cases, when the ClusterRoleBinding reconciliation fails with RBAC error and the desired object is null, * we want to ignore the error and return success. This is used to let Strimzi work without some Cluster-wide RBAC * rights when the features they are needed for are not used by the user. * * @param reconcileFuture The original reconciliation future * @param desired The desired state of the resource. * @return A future which completes when the resource was reconciled. */ public Future<ReconcileResult<ClusterRoleBinding>> withIgnoreRbacError(Future<ReconcileResult<ClusterRoleBinding>> reconcileFuture, ClusterRoleBinding desired) { return reconcileFuture.compose( rr -> Future.succeededFuture(), e -> { if (desired == null && e.getMessage() != null && e.getMessage().contains("Message: Forbidden!")) { log.debug("Ignoring forbidden access to ClusterRoleBindings resource which does not seem to be required."); return Future.succeededFuture(); } return Future.failedFuture(e.getMessage()); } ); } }
Remove confusing failed to acquire lock warning (#4521) Signed-off-by: Jakub Scholz <[email protected]>
operator-common/src/main/java/io/strimzi/operator/common/AbstractOperator.java
Remove confusing failed to acquire lock warning (#4521)
Java
apache-2.0
5d845092c787bb9c2ecfaa227893a15e1800df46
0
AArhin/head,AArhin/head,vorburger/mifos-head,AArhin/head,maduhu/head,jpodeszwik/mifos,maduhu/mifos-head,vorburger/mifos-head,maduhu/mifos-head,maduhu/head,maduhu/mifos-head,maduhu/head,maduhu/mifos-head,jpodeszwik/mifos,maduhu/head,vorburger/mifos-head,jpodeszwik/mifos,jpodeszwik/mifos,maduhu/head,AArhin/head,AArhin/head,vorburger/mifos-head,maduhu/mifos-head
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.ui.core.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings( { "PMD.SystemPrintln", "PMD.SingularField" }) @Controller public class GenericController extends AbstractController { @Override @RequestMapping(value={"/accessDenied.ftl","/pageNotFound.ftl","/ping.ftl","/cheetah.css.ftl","/gazelle.css.ftl","/adminHome.ftl","/maincss.css","/screen.css","/maincss.css.ftl","/screen.css.ftl","/admin.ftl","/viewProductCategories.ftl","/viewLoanProducts.ftl","/viewFunds.ftl","/defineLabels.ftl","/defineLookupOptions.ftl","/viewChecklists.ftl","/viewEditCheckLists.ftl","/viewEditSavingsProduct.ftl","/viewEditLoanProduct.ftl","/viewOffices.ftl","/viewHolidays.ftl","/viewSystemUsers.ftl","/viewAdditionalFields.ftl","/viewReportsTemplates.ftl","/viewReportsCategory.ftl","/manageRolesAndPermissions.ftl","/defineAdditionalFields.ftl","/defineNewCategory.ftl","/defineNewChecklist.ftl","/defineNewHolidays.ftl","/defineNewOffice.ftl","/defineNewSystemUser.ftl","/defineSavingsProduct.ftl","/redoLoansDisbursal.ftl"}) protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> model = new HashMap<String, Object>(); model.put("request", request); Map<String, Object> status = new HashMap<String, Object>(); List<String> errorMessages = new ArrayList<String>(); status.put("errorMessages", errorMessages); ModelAndView modelAndView = new ModelAndView(getPageToDisplay(request), "model", model); modelAndView.addObject("status", status); return modelAndView; } public String getPageToDisplay(HttpServletRequest request) { return request.getRequestURI().replaceFirst("/mifos.*/","").replace(".ftl", ""); } }
userInterface/src/main/java/org/mifos/ui/core/controller/GenericController.java
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.ui.core.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings( { "PMD.SystemPrintln", "PMD.SingularField" }) @Controller public class GenericController extends AbstractController { @Override @RequestMapping(value={"/accessDenied.ftl","/pageNotFound.ftl","/ping.ftl","/cheetah.css.ftl","/gazelle.css.ftl","/adminHome.ftl","/maincss.css","/screen.css","/maincss.css.ftl","/screen.css.ftl","/admin.ftl","/viewProductMix.ftl","/viewProductCategories.ftl","/viewLoanProducts.ftl","/viewFunds.ftl","/defineLabels.ftl","/defineLookupOptions.ftl","/viewChecklists.ftl","/viewEditCheckLists.ftl","/viewEditSavingsProduct.ftl","/viewEditLoanProduct.ftl","/viewOffices.ftl","/viewHolidays.ftl","/viewSystemUsers.ftl","/viewAdditionalFields.ftl","/viewReportsTemplates.ftl","/viewReportsCategory.ftl","/manageRolesAndPermissions.ftl","/defineAdditionalFields.ftl","/defineNewCategory.ftl","/defineNewChecklist.ftl","/defineNewHolidays.ftl","/defineNewOffice.ftl","/defineNewSystemUser.ftl","/defineSavingsProduct.ftl","/redoLoansDisbursal.ftl"}) protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> model = new HashMap<String, Object>(); model.put("request", request); Map<String, Object> status = new HashMap<String, Object>(); List<String> errorMessages = new ArrayList<String>(); status.put("errorMessages", errorMessages); ModelAndView modelAndView = new ModelAndView(getPageToDisplay(request), "model", model); modelAndView.addObject("status", status); return modelAndView; } public String getPageToDisplay(HttpServletRequest request) { return request.getRequestURI().replaceFirst("/mifos.*/","").replace(".ftl", ""); } }
removing viewProductMix.ftl mapping in GenericController
userInterface/src/main/java/org/mifos/ui/core/controller/GenericController.java
removing viewProductMix.ftl mapping in GenericController
Java
apache-2.0
518dbc14e17feb3a338b530a9217548760fd7dd9
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.index.geneproduct; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository; import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument; import uk.ac.ebi.quickgo.index.common.SolrCrudRepoWriter; import uk.ac.ebi.quickgo.index.common.listener.LogJobListener; import uk.ac.ebi.quickgo.index.common.listener.LogStepListener; import uk.ac.ebi.quickgo.geneproduct.common.RepoConfig; import uk.ac.ebi.quickgo.index.common.listener.SkipLoggerListener; import java.util.Arrays; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecutionListener; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepListener; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.FlatFileParseException; import org.springframework.batch.item.file.LineMapper; import org.springframework.batch.item.file.MultiResourceItemReader; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.batch.item.file.transform.LineTokenizer; import org.springframework.batch.item.support.CompositeItemProcessor; import org.springframework.batch.item.validator.ValidatingItemProcessor; import org.springframework.batch.item.validator.ValidationException; import org.springframework.batch.item.validator.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; /** * Sets up batch jobs for gene product indexing. */ @Configuration @EnableBatchProcessing @Import({RepoConfig.class}) public class GeneProductConfig { static final String GENE_PRODUCT_INDEXING_STEP_NAME = "geneProductIndex"; private static final String COLUMN_DELIMITER = "\t"; private static final String INTER_VALUE_DELIMITER = "\\|"; private static final String INTRA_VALUE_DELIMITER = "="; @Autowired private JobBuilderFactory jobBuilders; @Autowired private StepBuilderFactory stepBuilders; @Value("${indexing.geneproduct.source}") private Resource[] resources; @Value("${indexing.geneproduct.chunk.size:500}") private int chunkSize; @Value("${indexing.geneproduct.header.lines:17}") private int headerLines; @Value("${indexing.geneproduct.skip.limit:100}") private int skipLimit; @Autowired private GeneProductRepository repository; @Bean public Job geneProductJob() { return jobBuilders.get("geneProductJob") .start(readGeneProductData()) .listener(logJobListener()) .build(); } private Step readGeneProductData() { return stepBuilders.get(GENE_PRODUCT_INDEXING_STEP_NAME) .<GeneProduct, GeneProductDocument>chunk(chunkSize) .faultTolerant() .skipLimit(skipLimit) .skip(FlatFileParseException.class) .skip(ValidationException.class) .<GeneProduct>reader(multiFileReader()) .processor(compositeProcessor(gpValidator(), docConverter())) .writer(geneProductRepositoryWriter()) .listener(logStepListener()) .listener(skipLogListener()) .build(); } private MultiResourceItemReader<GeneProduct> multiFileReader() { MultiResourceItemReader<GeneProduct> reader = new MultiResourceItemReader<>(); reader.setResources(resources); reader.setDelegate(singleFileReader()); return reader; } private FlatFileItemReader<GeneProduct> singleFileReader() { FlatFileItemReader<GeneProduct> reader = new FlatFileItemReader<>(); reader.setLineMapper(lineMapper()); reader.setLinesToSkip(headerLines); return reader; } private LineMapper<GeneProduct> lineMapper() { DefaultLineMapper<GeneProduct> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(lineTokenizer()); lineMapper.setFieldSetMapper(fieldSetMapper()); return lineMapper; } private LineTokenizer lineTokenizer() { return new DelimitedLineTokenizer(COLUMN_DELIMITER); } private FieldSetMapper<GeneProduct> fieldSetMapper() { return new StringToGeneProductMapper(); } private ItemProcessor<GeneProduct, GeneProductDocument> docConverter() { return new GeneProductDocumentConverter(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER); } private ItemProcessor<GeneProduct, GeneProduct> gpValidator() { Validator<GeneProduct> geneProductValidator = new GeneProductValidator(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER); return new ValidatingItemProcessor<>(geneProductValidator); } private ItemProcessor<GeneProduct, GeneProductDocument> compositeProcessor(ItemProcessor<GeneProduct, ?>... processors) { CompositeItemProcessor<GeneProduct, GeneProductDocument> compositeProcessor = new CompositeItemProcessor<>(); compositeProcessor.setDelegates(Arrays.asList(processors)); return compositeProcessor; } private ItemWriter<GeneProductDocument> geneProductRepositoryWriter() { return new SolrCrudRepoWriter<>(repository); } private JobExecutionListener logJobListener() { return new LogJobListener(); } private StepListener logStepListener() { return new LogStepListener(); } private StepListener skipLogListener() { return new SkipLoggerListener(); } }
indexing/src/main/java/uk/ac/ebi/quickgo/index/geneproduct/GeneProductConfig.java
package uk.ac.ebi.quickgo.index.geneproduct; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository; import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument; import uk.ac.ebi.quickgo.index.common.DocumentReaderException; import uk.ac.ebi.quickgo.index.common.SolrCrudRepoWriter; import uk.ac.ebi.quickgo.index.common.listener.LogJobListener; import uk.ac.ebi.quickgo.index.common.listener.LogStepListener; import uk.ac.ebi.quickgo.geneproduct.common.RepoConfig; import java.util.Arrays; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.FlatFileParseException; import org.springframework.batch.item.file.LineMapper; import org.springframework.batch.item.file.MultiResourceItemReader; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.batch.item.file.transform.LineTokenizer; import org.springframework.batch.item.support.CompositeItemProcessor; import org.springframework.batch.item.validator.ValidatingItemProcessor; import org.springframework.batch.item.validator.ValidationException; import org.springframework.batch.item.validator.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.Resource; /** * Sets up batch jobs for gene product indexing. */ @Configuration @EnableBatchProcessing @Import({RepoConfig.class}) public class GeneProductConfig { static final String GENE_PRODUCT_INDEXING_STEP_NAME = "geneProductIndex"; private static final String COLUMN_DELIMITER = "\t"; private static final String INTER_VALUE_DELIMITER = "\\|"; private static final String INTRA_VALUE_DELIMITER = "="; @Autowired private JobBuilderFactory jobBuilders; @Autowired private StepBuilderFactory stepBuilders; @Value("${indexing.geneproduct.source}") private Resource[] resources; @Value("${indexing.geneproduct.chunk.size:500}") private int chunkSize; @Value("${indexing.geneproduct.header.lines:17}") private int headerLines; @Value("${indexing.geneproduct.skip.limit:100}") private int skipLimit; @Autowired private GeneProductRepository repository; @Bean public Job geneProductJob() { return jobBuilders.get("geneProductJob") .listener(logJobListener()) .flow(readGeneProductData()) .end() .build(); } private Step readGeneProductData() { return stepBuilders.get(GENE_PRODUCT_INDEXING_STEP_NAME) .<GeneProduct, GeneProductDocument>chunk(chunkSize) .faultTolerant() .skipLimit(skipLimit) .skip(FlatFileParseException.class) .skip(ValidationException.class) .<GeneProduct>reader(multiFileReader()) .processor(compositeProcessor(gpValidator(), docConverter())) .writer(geneProductRepositoryWriter()) .listener(logStepListener()) .build(); } private MultiResourceItemReader<GeneProduct> multiFileReader() { MultiResourceItemReader<GeneProduct> reader = new MultiResourceItemReader<>(); reader.setResources(resources); reader.setDelegate(singleFileReader()); return reader; } private FlatFileItemReader<GeneProduct> singleFileReader() { FlatFileItemReader<GeneProduct> reader = new FlatFileItemReader<>(); reader.setLineMapper(lineMapper()); reader.setLinesToSkip(headerLines); return reader; } private LineMapper<GeneProduct> lineMapper() { DefaultLineMapper<GeneProduct> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(lineTokenizer()); lineMapper.setFieldSetMapper(fieldSetMapper()); return lineMapper; } private LineTokenizer lineTokenizer() { return new DelimitedLineTokenizer(COLUMN_DELIMITER); } private FieldSetMapper<GeneProduct> fieldSetMapper() { return new StringToGeneProductMapper(); } private ItemProcessor<GeneProduct, GeneProductDocument> docConverter() { return new GeneProductDocumentConverter(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER); } private ItemProcessor<GeneProduct, GeneProduct> gpValidator() { Validator<GeneProduct> geneProductValidator = new GeneProductValidator(INTER_VALUE_DELIMITER, INTRA_VALUE_DELIMITER); return new ValidatingItemProcessor<>(geneProductValidator); } private ItemProcessor<GeneProduct, GeneProductDocument> compositeProcessor(ItemProcessor<GeneProduct, ?>... processors) { CompositeItemProcessor<GeneProduct, GeneProductDocument> compositeProcessor = new CompositeItemProcessor<>(); compositeProcessor.setDelegates(Arrays.asList(processors)); return compositeProcessor; } private ItemWriter<GeneProductDocument> geneProductRepositoryWriter() { return new SolrCrudRepoWriter<>(repository); } private LogJobListener logJobListener() { return new LogJobListener(); } private LogStepListener logStepListener() { return new LogStepListener(); } }
Add step listener to the step.
indexing/src/main/java/uk/ac/ebi/quickgo/index/geneproduct/GeneProductConfig.java
Add step listener to the step.
Java
apache-2.0
e6a80aed3776535e684081ec7d50c728a78d0674
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/** * Licensed to Neo Technology under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Neo Technology 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.neo4j.windows.test; import com.sun.jersey.api.client.ClientHandlerException; import org.junit.Test; import org.neo4j.server.rest.JaxRsResponse; import org.neo4j.server.rest.RestRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; public class TheTest { @Test public void Test() throws Throwable { Result install = run("msiexec /i target\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet INSTALL_DIR=\"C:\\det är dåligt. mycket mycket dåligt. gör inte såhär.\""); install.checkResults(); checkDataRest(); Result uninstall = run("msiexec /x target\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet"); uninstall.checkResults(); try { checkDataRest(); fail("Server is still listening to port 7474 even after uninstall"); } catch (ClientHandlerException e) { } } private void checkDataRest() throws Exception { JaxRsResponse r = RestRequest.req().get("http://localhost:7474/db/data/"); assertThat(r.getStatus(), equalTo(200)); } private Result run(String cmd) throws IOException, InterruptedException { System.out.println(cmd); StringBuilder builder = new StringBuilder(); Process installer = Runtime.getRuntime().exec(cmd); BufferedReader bri = new BufferedReader(new InputStreamReader(installer.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(installer.getErrorStream())); String line; while ((line = bri.readLine()) != null) { builder.append(line); builder.append("\r\n"); } bri.close(); while ((line = bre.readLine()) != null) { builder.append(line); builder.append("\r\n"); } bre.close(); installer.waitFor(); return new Result(installer.exitValue(), builder.toString(), cmd); } private class Result { private final int result; private final String message; private Result(int result, String message, String cmd) { this.result = result; String userDir = System.getProperty("user.dir"); this.message = "Path: " + userDir + "\r\n" + "Cmd: " + cmd + "\r\n" + message; } public int getResult() { return result; } public String getMessage() { return message; } public void checkResults() { assertEquals(message, getResult(), 0); } } }
packaging/win-test/src/test/java/org/neo4j/windows/test/TheTest.java
/** * Licensed to Neo Technology under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Neo Technology 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.neo4j.windows.test; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.neo4j.server.rest.RestRequest; import org.neo4j.server.rest.JaxRsResponse; import com.sun.jersey.api.client.ClientHandlerException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.*; import static org.hamcrest.Matchers.equalTo; public class TheTest { @Test public void Test() throws Throwable { Result install = run("msiexec /i target\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet"); install.checkResults(); JaxRsResponse r = RestRequest.req().get("http://localhost:7474/db/data/"); assertThat(r.getStatus(), equalTo(200)); Result uninstall = run("msiexec /x target\\neo4j-community-setup-1.6-SNAPSHOT.msi /quiet"); uninstall.checkResults(); try { r = RestRequest.req().get("http://localhost:7474/db/data/"); int status = r.getStatus(); fail("Server is still listening to port 7474 even after uninstall"); } catch (ClientHandlerException e) { } } private Result run(String cmd) throws IOException, InterruptedException { System.out.println(cmd); StringBuilder builder = new StringBuilder(); Process installer = Runtime.getRuntime().exec(cmd); BufferedReader bri = new BufferedReader(new InputStreamReader(installer.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(installer.getErrorStream())); String line; while ((line = bri.readLine()) != null) { builder.append(line); builder.append("\r\n"); } bri.close(); while ((line = bre.readLine()) != null) { builder.append(line); builder.append("\r\n"); } bre.close(); installer.waitFor(); return new Result(installer.exitValue(), builder.toString(), cmd); } private class Result { private final int result; private final String message; private Result(int result, String message, String cmd) { this.result = result; String userDir = System.getProperty("user.dir"); this.message = "Path: " + userDir + "\r\n" + "Cmd: " + cmd + "\r\n" + message; } public int getResult() { return result; } public String getMessage() { return message; } public void checkResults() { assertEquals(message, getResult(), 0); } } }
Added tests to install the server on a path with strange characters and space in it
packaging/win-test/src/test/java/org/neo4j/windows/test/TheTest.java
Added tests to install the server on a path with strange characters and space in it
Java
apache-2.0
89f4bf9d11d94943d357ee72613a7b098166b5de
0
cnldw/APITools
package com.itlaborer.utils; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import net.dongliu.requests.RawResponse; import net.dongliu.requests.Requests; /** * * 工具类 * * @author liu * */ public class ApiUtils { private static Logger logger = Logger.getLogger(ApiUtils.class.getName()); public ApiUtils() { } // MD5字符串算法 public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { logger.error("异常", e); return null; } } // HTTP GET 忽略证书安全 public static RawResponse HttpGet(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.get(url).verify(false).headers(header).cookies(cookies).params(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP POST 忽略证书安全 public static RawResponse HttpPost(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.post(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP HEAD 忽略证书安全 public static RawResponse HttpHead(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.head(url).verify(false).headers(header).cookies(cookies).params(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP PUT 忽略证书安全 public static RawResponse HttpPut(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.put(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP PATCH 忽略证书安全 public static RawResponse HttpPatch(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.patch(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP DELETE 忽略证书安全 public static RawResponse HttpDelete(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.delete(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // 设置程序窗口居中 public static void SetCenter(Shell shell) { int screenH = Toolkit.getDefaultToolkit().getScreenSize().height; int screenW = Toolkit.getDefaultToolkit().getScreenSize().width; int shellH = shell.getBounds().height; int shellW = shell.getBounds().width; if (shellH > screenH) { shellH = screenH; } if (shellW > screenW) { shellW = screenW; } shell.setLocation(((screenW - shellW) / 2), ((screenH - shellH) / 2)); } // 设置程序窗口居中于父窗口 public static void SetCenterinParent(Shell parentshell, Shell shell) { int screenH = Toolkit.getDefaultToolkit().getScreenSize().height; int screenW = Toolkit.getDefaultToolkit().getScreenSize().width; int shellH = shell.getBounds().height; int shellW = shell.getBounds().width; // 如果窗口大小超过屏幕大小,调整为屏幕大小 if (shellH > screenH) { shellH = screenH; } if (shellW > screenW) { shellW = screenW; } int targetx = parentshell.getLocation().x + parentshell.getBounds().width / 2 - shell.getBounds().width / 2; int targety = parentshell.getLocation().y + parentshell.getBounds().height / 2 - shell.getBounds().height / 2; if (targetx + shellW > screenW) { targetx = screenW - shellW; } if (targety + shellH > screenH) { targety = screenH - shellH; } shell.setLocation(targetx, targety); } // 读取文件到String字符串 public static String ReadFromFile(File file, String encoding) { InputStreamReader reader = null; StringWriter writer = new StringWriter(); try { if (encoding == null || "".equals(encoding.trim())) { reader = new InputStreamReader(new FileInputStream(file), encoding); } else { reader = new InputStreamReader(new FileInputStream(file)); } char[] buffer = new char[4096]; int n = 0; while (-1 != (n = reader.read(buffer))) { writer.write(buffer, 0, n); } } catch (Exception e) { logger.error("异常", e); return null; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { logger.error("异常", e); } } return writer.toString(); } // String保存到文件方法 public static boolean SaveToFile(File file, String content) { FileWriter fwriter = null; try { fwriter = new FileWriter(file); fwriter.write(content); fwriter.flush(); fwriter.close(); return true; } catch (Exception ex) { logger.error("捕获异常", ex); return false; } } // 文件复制方法 public static long CopyFile(File f1, File f2) throws Exception { long time = new Date().getTime(); int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); byte[] buffer = new byte[length]; while (true) { int ins = in.read(buffer); if (ins == -1) { in.close(); out.flush(); out.close(); return new Date().getTime() - time; } else out.write(buffer, 0, ins); } } // String编码转换方法 public static String GetUTF8StringFromGBKString(String gbkStr) { try { return new String(GetUTF8BytesFromGBKString(gbkStr), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new InternalError(); } } // GBK字符串转换到UTF-8 public static byte[] GetUTF8BytesFromGBKString(String gbkStr) { int n = gbkStr.length(); byte[] utfBytes = new byte[3 * n]; int k = 0; for (int i = 0; i < n; i++) { int m = gbkStr.charAt(i); if (m < 128 && m >= 0) { utfBytes[k++] = (byte) m; continue; } utfBytes[k++] = (byte) (0xe0 | (m >> 12)); utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f)); utfBytes[k++] = (byte) (0x80 | (m & 0x3f)); } if (k < utfBytes.length) { byte[] tmp = new byte[k]; System.arraycopy(utfBytes, 0, tmp, 0, k); return tmp; } return utfBytes; } // 删除文件夹的方法 public static boolean DeleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = DeleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } // 字符串转unicode public static String string2Unicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); String unicodestring = Integer.toHexString(c); // 英文的话,要补全四位 if (unicodestring.length() == 2) { unicodestring = "00" + unicodestring; } // 转换为unicode unicode.append("\\u" + unicodestring); } return unicode.toString(); } // 字符串转unicode-只转换中日韩 public static String stringzh2Unicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); // 转换为unicode if (isChinese(c)) { unicode.append("\\u" + Integer.toHexString(c)); } else { unicode.append(c); } } return unicode.toString(); } // unicode串解码 public static String unicode2String(String str) { Charset set = Charset.forName("UTF-16"); Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})"); Matcher m = p.matcher(str); int start = 0; int start2 = 0; StringBuffer sb = new StringBuffer(); while (m.find(start)) { start2 = m.start(); if (start2 > start) { String seg = str.substring(start, start2); sb.append(seg); } String code = m.group(1); int i = Integer.valueOf(code, 16); byte[] bb = new byte[4]; bb[0] = (byte) ((i >> 8) & 0xFF); bb[1] = (byte) (i & 0xFF); ByteBuffer b = ByteBuffer.wrap(bb); sb.append(String.valueOf(set.decode(b)).trim()); start = m.end(); } start2 = str.length(); if (start2 > start) { String seg = str.substring(start, start2); sb.append(seg); } return sb.toString(); } // 判断字符是否是中日韩字符 private static final boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false; } // 给不支持右键菜单的StyledText添加右键菜单 public static void StyledTextAddContextMenu(StyledText styledText) { Menu popupMenu = new Menu(styledText); MenuItem cut = new MenuItem(popupMenu, SWT.NONE); cut.setText("剪切"); MenuItem copy = new MenuItem(popupMenu, SWT.NONE); copy.setText("复制"); MenuItem paste = new MenuItem(popupMenu, SWT.NONE); paste.setText("粘贴"); MenuItem allSelect = new MenuItem(popupMenu, SWT.NONE); allSelect.setText("全选"); MenuItem clear = new MenuItem(popupMenu, SWT.NONE); clear.setText("清空"); MenuItem warp = new MenuItem(popupMenu, SWT.NONE); warp.setText("自动换行"); styledText.setMenu(popupMenu); // 判断初始自动换行状态 if (styledText.getWordWrap()) { warp.setText("关闭自动换行"); } else { warp.setText("打开自动换行"); } styledText.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.stateMask == SWT.CTRL && e.keyCode == 'a') { styledText.selectAll(); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }); // 剪切菜单的点击事件 cut.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getSelectionCount() == 0) { return; } Clipboard clipboard = new Clipboard(styledText.getDisplay()); String plainText = styledText.getSelectionText(); TextTransfer textTransfer = TextTransfer.getInstance(); clipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer }); clipboard.dispose(); // 将已经剪切走的部分删除,并将插入符移动到剪切位置 int caretOffset = styledText.getSelection().x; styledText.setText(new StringBuffer(styledText.getText()) .replace(styledText.getSelection().x, styledText.getSelection().y, "").toString()); styledText.setCaretOffset(caretOffset); } }); // 粘贴菜单的点击事件 paste.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Clipboard clipboard = new Clipboard(styledText.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); // 获取剪切板上的文本 String cliptext = (clipboard.getContents(textTransfer) != null ? clipboard.getContents(textTransfer).toString() : ""); clipboard.dispose(); int caretOffset = styledText.getSelection().x; styledText.setText(new StringBuffer(styledText.getText()) .replace(styledText.getSelection().x, styledText.getSelection().y, cliptext).toString()); styledText.setCaretOffset(caretOffset + cliptext.length()); } }); // 复制上下文菜单的点击事件 copy.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getSelectionCount() == 0) { return; } Clipboard clipboard = new Clipboard(styledText.getDisplay()); String plainText = styledText.getSelectionText(); TextTransfer textTransfer = TextTransfer.getInstance(); clipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer }); clipboard.dispose(); } }); // 全选上下文菜单的点击事件 allSelect.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { styledText.selectAll(); } }); // 清空上下文菜单的点击事件 clear.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { styledText.setText(""); } }); // 更改是否自动换行 warp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getWordWrap()) { styledText.setWordWrap(false); warp.setText("打开自动换行"); } else { styledText.setWordWrap(true); warp.setText("关闭自动换行"); } } }); } public static void DropTargetSupport(Shell shell) { DropTarget dropTarget = new DropTarget(shell, DND.DROP_NONE); Transfer[] transfer = new Transfer[] { FileTransfer.getInstance() }; dropTarget.setTransfer(transfer); // 拖拽监听 dropTarget.addDropListener(new DropTargetListener() { @Override public void dragEnter(DropTargetEvent event) { } @Override public void dragLeave(DropTargetEvent event) { } @Override public void dragOperationChanged(DropTargetEvent event) { } @Override public void dragOver(DropTargetEvent event) { } // 获取拖放进来的文件,暂无用途 @Override public void drop(DropTargetEvent event) { String[] files = (String[]) event.data; for (int i = 0; i < files.length; i++) { @SuppressWarnings("unused") File file = new File(files[i]); } } @Override public void dropAccept(DropTargetEvent event) { } }); } }
src/com/itlaborer/utils/ApiUtils.java
package com.itlaborer.utils; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import net.dongliu.requests.RawResponse; import net.dongliu.requests.Requests; /** * * 工具类 * * @author liu * */ public class ApiUtils { private static Logger logger = Logger.getLogger(ApiUtils.class.getName()); public ApiUtils() { } // MD5字符串算法 public final static String MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { logger.error("异常", e); return null; } } // HTTP GET 忽略证书安全 public static RawResponse HttpGet(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.get(url).verify(false).headers(header).cookies(cookies).params(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP POST 忽略证书安全 public static RawResponse HttpPost(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.post(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP HEAD 忽略证书安全 public static RawResponse HttpHead(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.head(url).verify(false).headers(header).cookies(cookies).params(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP PUT 忽略证书安全 public static RawResponse HttpPut(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.put(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP PATCH 忽略证书安全 public static RawResponse HttpPatch(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.patch(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // HTTP DELETE 忽略证书安全 public static RawResponse HttpDelete(String url, HashMap<String, String> parameter, LinkedHashMap<String, String> header, LinkedHashMap<String, String> cookies, Charset requestCharset) throws Exception { RawResponse resp = Requests.delete(url).verify(false).headers(header).cookies(cookies).forms(parameter) .requestCharset(requestCharset).send(); return resp; } // 设置程序窗口居中 public static void SetCenter(Shell shell) { int screenH = Toolkit.getDefaultToolkit().getScreenSize().height; int screenW = Toolkit.getDefaultToolkit().getScreenSize().width; int shellH = shell.getBounds().height; int shellW = shell.getBounds().width; if (shellH > screenH) { shellH = screenH; } if (shellW > screenW) { shellW = screenW; } shell.setLocation(((screenW - shellW) / 2), ((screenH - shellH) / 2)); } // 设置程序窗口居中于父窗口 public static void SetCenterinParent(Shell parentshell, Shell shell) { int screenH = Toolkit.getDefaultToolkit().getScreenSize().height; int screenW = Toolkit.getDefaultToolkit().getScreenSize().width; int shellH = shell.getBounds().height; int shellW = shell.getBounds().width; // 如果窗口大小超过屏幕大小,调整为屏幕大小 if (shellH > screenH) { shellH = screenH; } if (shellW > screenW) { shellW = screenW; } int targetx = parentshell.getLocation().x + parentshell.getBounds().width / 2 - shell.getBounds().width / 2; int targety = parentshell.getLocation().y + parentshell.getBounds().height / 2 - shell.getBounds().height / 2; if (targetx + shellW > screenW) { targetx = screenW - shellW; } if (targety + shellH > screenH) { targety = screenH - shellH; } shell.setLocation(targetx, targety); } // 读取文件到String字符串 public static String ReadFromFile(File file, String encoding) { InputStreamReader reader = null; StringWriter writer = new StringWriter(); try { if (encoding == null || "".equals(encoding.trim())) { reader = new InputStreamReader(new FileInputStream(file), encoding); } else { reader = new InputStreamReader(new FileInputStream(file)); } char[] buffer = new char[4096]; int n = 0; while (-1 != (n = reader.read(buffer))) { writer.write(buffer, 0, n); } } catch (Exception e) { logger.error("异常", e); return null; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { logger.error("异常", e); } } return writer.toString(); } // String保存到文件方法 public static boolean SaveToFile(File file, String content) { FileWriter fwriter = null; try { fwriter = new FileWriter(file); fwriter.write(content); fwriter.flush(); fwriter.close(); return true; } catch (Exception ex) { logger.error("捕获异常", ex); return false; } } // 文件复制方法 public static long CopyFile(File f1, File f2) throws Exception { long time = new Date().getTime(); int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); byte[] buffer = new byte[length]; while (true) { int ins = in.read(buffer); if (ins == -1) { in.close(); out.flush(); out.close(); return new Date().getTime() - time; } else out.write(buffer, 0, ins); } } // String编码转换方法 public static String GetUTF8StringFromGBKString(String gbkStr) { try { return new String(GetUTF8BytesFromGBKString(gbkStr), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new InternalError(); } } // GBK字符串转换到UTF-8 public static byte[] GetUTF8BytesFromGBKString(String gbkStr) { int n = gbkStr.length(); byte[] utfBytes = new byte[3 * n]; int k = 0; for (int i = 0; i < n; i++) { int m = gbkStr.charAt(i); if (m < 128 && m >= 0) { utfBytes[k++] = (byte) m; continue; } utfBytes[k++] = (byte) (0xe0 | (m >> 12)); utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f)); utfBytes[k++] = (byte) (0x80 | (m & 0x3f)); } if (k < utfBytes.length) { byte[] tmp = new byte[k]; System.arraycopy(utfBytes, 0, tmp, 0, k); return tmp; } return utfBytes; } // 删除文件夹的方法 public static boolean DeleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = DeleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } // 字符串转unicode public static String string2Unicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); String unicodestring = Integer.toHexString(c); // 英文的话,要补全四位 if (unicodestring.length() == 2) { unicodestring = "00" + unicodestring; } // 转换为unicode unicode.append("\\u" + unicodestring); } return unicode.toString(); } // 字符串转unicode-只转换中日韩 public static String stringzh2Unicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); // 转换为unicode if (isChinese(c)) { unicode.append("\\u" + Integer.toHexString(c)); } else { unicode.append(c); } } return unicode.toString(); } // unicode串解码 public static String unicode2String(String str) { Charset set = Charset.forName("UTF-16"); Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})"); Matcher m = p.matcher(str); int start = 0; int start2 = 0; StringBuffer sb = new StringBuffer(); while (m.find(start)) { start2 = m.start(); if (start2 > start) { String seg = str.substring(start, start2); sb.append(seg); } String code = m.group(1); int i = Integer.valueOf(code, 16); byte[] bb = new byte[4]; bb[0] = (byte) ((i >> 8) & 0xFF); bb[1] = (byte) (i & 0xFF); ByteBuffer b = ByteBuffer.wrap(bb); sb.append(String.valueOf(set.decode(b)).trim()); start = m.end(); } start2 = str.length(); if (start2 > start) { String seg = str.substring(start, start2); sb.append(seg); } return sb.toString(); } // 判断字符是否是中日韩字符 private static final boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { return true; } return false; } // 给不支持右键菜单的StyledText添加右键菜单 public static void StyledTextAddContextMenu(StyledText styledText) { Menu popupMenu = new Menu(styledText); MenuItem cut = new MenuItem(popupMenu, SWT.NONE); cut.setText("剪切"); MenuItem copy = new MenuItem(popupMenu, SWT.NONE); copy.setText("复制"); MenuItem paste = new MenuItem(popupMenu, SWT.NONE); paste.setText("粘贴"); MenuItem allSelect = new MenuItem(popupMenu, SWT.NONE); allSelect.setText("全选"); MenuItem clear = new MenuItem(popupMenu, SWT.NONE); clear.setText("清空"); MenuItem warp = new MenuItem(popupMenu, SWT.NONE); warp.setText("自动换行"); styledText.setMenu(popupMenu); // 判断初始自动换行状态 if (styledText.getWordWrap()) { warp.setText("关闭自动换行"); } else { warp.setText("打开自动换行"); } styledText.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.stateMask == SWT.CTRL && e.keyCode == 'a') { styledText.selectAll(); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }); // 剪切菜单的点击事件 cut.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getSelectionCount() == 0) { return; } Clipboard clipboard = new Clipboard(styledText.getDisplay()); String plainText = styledText.getSelectionText(); TextTransfer textTransfer = TextTransfer.getInstance(); clipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer }); clipboard.dispose(); // 将已经剪切走的部分删除,并将插入符移动到剪切位置 int caretOffset = styledText.getSelection().x; styledText.setText(new StringBuffer(styledText.getText()) .replace(styledText.getSelection().x, styledText.getSelection().y, "").toString()); styledText.setCaretOffset(caretOffset); } }); // 粘贴菜单的点击事件 paste.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Clipboard clipboard = new Clipboard(styledText.getDisplay()); TextTransfer textTransfer = TextTransfer.getInstance(); // 获取剪切板上的文本 String cliptext = (clipboard.getContents(textTransfer) != null ? clipboard.getContents(textTransfer).toString() : ""); clipboard.dispose(); int caretOffset = styledText.getSelection().x; styledText.setText(new StringBuffer(styledText.getText()) .replace(styledText.getSelection().x, styledText.getSelection().y, cliptext).toString()); styledText.setCaretOffset(caretOffset + cliptext.length()); } }); // 复制上下文菜单的点击事件 copy.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getSelectionCount() == 0) { return; } Clipboard clipboard = new Clipboard(styledText.getDisplay()); String plainText = styledText.getSelectionText(); TextTransfer textTransfer = TextTransfer.getInstance(); clipboard.setContents(new String[] { plainText }, new Transfer[] { textTransfer }); clipboard.dispose(); } }); // 全选上下文菜单的点击事件 allSelect.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { styledText.selectAll(); } }); // 清空上下文菜单的点击事件 clear.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { styledText.setText(""); } }); // 更改是否自动换行 warp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (styledText.getWordWrap()) { styledText.setWordWrap(false); warp.setText("打开自动换行"); } else { styledText.setWordWrap(true); warp.setText("关闭自动换行"); } } }); } public static void DropTargetSupport(Shell shell) { DropTarget dropTarget = new DropTarget(shell, DND.DROP_NONE); Transfer[] transfer = new Transfer[] { FileTransfer.getInstance() }; dropTarget.setTransfer(transfer); // 拖拽监听 dropTarget.addDropListener(new DropTargetListener() { @Override public void dragEnter(DropTargetEvent event) { } @Override public void dragLeave(DropTargetEvent event) { } @Override public void dragOperationChanged(DropTargetEvent event) { } @Override public void dragOver(DropTargetEvent event) { } // 获取拖放进来的文件,暂无用途 @Override public void drop(DropTargetEvent event) { String[] files = (String[]) event.data; for (int i = 0; i < files.length; i++) { @SuppressWarnings("unused") File file = new File(files[i]); } } @Override public void dropAccept(DropTargetEvent event) { } }); } }
no commit message
src/com/itlaborer/utils/ApiUtils.java
no commit message
Java
apache-2.0
3e2245a4266ac4e0a01fda752a58a67043ea91e6
0
rhdunn/marklogic-intellij-plugin
/* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.tests.query; import uk.co.reecedunn.intellij.plugin.marklogic.configuration.MarkLogicRunConfiguration; import uk.co.reecedunn.intellij.plugin.marklogic.query.Function; import uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilder; import uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilderFactory; import uk.co.reecedunn.intellij.plugin.marklogic.tests.configuration.ConfigurationTestCase; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @SuppressWarnings("ConstantConditions") public class FunctionTest extends ConfigurationTestCase { public void testEval() { final String query = "(1, 2, 3)"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"(1, 2, 3)\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithDoubleQuotes() { final String query = "1 || \"st\""; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"1 || \"\"st\"\"\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithXmlEntities() { final String query = "<a>&amp;</a>"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"<a>&amp;amp;</a>\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithOptions() { final String query = "(1, 2)"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); configuration.setContentDatabase("lorem"); configuration.setModuleDatabase("ipsum"); configuration.setModuleRoot("dolor"); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"(1, 2)\"\n" + "let $vars := ()\n" + "let $options := " + "<options xmlns=\"xdmp:eval\">" + "<database>{xdmp:database(\"lorem\")}</database>" + "<modules>{xdmp:database(\"ipsum\")}</modules>" + "<root>dolor</root>" + "</options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testNoVarsAndOptionsBuilder() { final String query = "select * from authors"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.sql", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 8.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"select * from authors\"\n" + "let $vars := ()\n" + "let $options := ()\n" + "return try { xdmp:sql($query) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } }
src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/query/FunctionTest.java
/* * Copyright (C) 2017 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.marklogic.tests.query; import uk.co.reecedunn.intellij.plugin.marklogic.configuration.MarkLogicRunConfiguration; import uk.co.reecedunn.intellij.plugin.marklogic.query.Function; import uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilder; import uk.co.reecedunn.intellij.plugin.marklogic.query.QueryBuilderFactory; import uk.co.reecedunn.intellij.plugin.marklogic.tests.configuration.ConfigurationTestCase; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @SuppressWarnings("ConstantConditions") public class FunctionTest extends ConfigurationTestCase { public void testEval() { final String query = "(1, 2, 3)"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"(1, 2, 3)\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithDoubleQuotes() { final String query = "1 || \"st\""; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"1 || \"\"st\"\"\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithXmlEntities() { final String query = "<a>&amp;</a>"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"<a>&amp;amp;</a>\"\n" + "let $vars := ()\n" + "let $options := <options xmlns=\"xdmp:eval\"><root>/</root></options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testQueryWithOptions() { final String query = "(1, 2)"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.xqy", query)); configuration.setContentDatabase("lorem"); configuration.setModuleDatabase("ipsum"); configuration.setModuleRoot("dolor"); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 5.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"(1, 2)\"\n" + "let $vars := ()\n" + "let $options := " + "<options xmlns=\"xdmp:eval\">" + "<database>{xdmp:database(\"lorem\")}</database>" + "<modules>{xdmp:database(\"ipsum\")}</modules>" + "<root>dolor</root>" + "</options>\n" + "return try { xdmp:eval($query, $vars, $options) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } public void testSQL() { final String query = "select * from authors"; final MarkLogicRunConfiguration configuration = createConfiguration(); configuration.setMainModuleFile(createVirtualFile("test.sql", query)); QueryBuilder queryBuilder = QueryBuilderFactory.createQueryBuilderForFile(configuration.getMainModulePath()); Function function = queryBuilder.createEvalBuilder(QueryBuilder.ExecMode.Run, 8.0); StringBuilder builder = new StringBuilder(); function.buildQuery(builder, configuration); final String expected = "let $query := \"select * from authors\"\n" + "let $vars := ()\n" + "let $options := ()\n" + "return try { xdmp:sql($query) } catch ($e) { $e }\n"; assertThat(builder.toString(), is(expected)); } }
Rename the FunctionTest.testSQL to reflect what it is actually testing.
src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/query/FunctionTest.java
Rename the FunctionTest.testSQL to reflect what it is actually testing.
Java
apache-2.0
57d531265530f1d2b1ed192c8706877e54142ead
0
vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.xcontent; import com.fasterxml.jackson.core.JsonParseException; import org.elasticsearch.common.CheckedSupplier; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.nullValue; public class XContentParserTests extends ESTestCase { public void testFloat() throws IOException { final XContentType xContentType = randomFrom(XContentType.values()); final String field = randomAlphaOfLengthBetween(1, 5); final Float value = randomFloat(); try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.startObject(); if (randomBoolean()) { builder.field(field, value); } else { builder.field(field).value(value); } builder.endObject(); final Number number; try (XContentParser parser = createParser(xContentType.xContent(), BytesReference.bytes(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals(field, parser.currentName()); assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken()); number = parser.numberValue(); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } assertEquals(value, number.floatValue(), 0.0f); if (xContentType == XContentType.CBOR) { // CBOR parses back a float assertTrue(number instanceof Float); } else { // JSON, YAML and SMILE parses back the float value as a double // This will change for SMILE in Jackson 2.9 where all binary based // formats will return a float assertTrue(number instanceof Double); } } } public void testReadList() throws IOException { assertThat(readList("{\"foo\": [\"bar\"]}"), contains("bar")); assertThat(readList("{\"foo\": [\"bar\",\"baz\"]}"), contains("bar", "baz")); assertThat(readList("{\"foo\": [1, 2, 3], \"bar\": 4}"), contains(1, 2, 3)); assertThat(readList("{\"foo\": [{\"bar\":1},{\"baz\":2},{\"qux\":3}]}"), hasSize(3)); assertThat(readList("{\"foo\": [null]}"), contains(nullValue())); assertThat(readList("{\"foo\": []}"), hasSize(0)); assertThat(readList("{\"foo\": [1]}"), contains(1)); assertThat(readList("{\"foo\": [1,2]}"), contains(1, 2)); assertThat(readList("{\"foo\": [{},{},{},{}]}"), hasSize(4)); } public void testReadListThrowsException() throws IOException { // Calling XContentParser.list() or listOrderedMap() to read a simple // value or object should throw an exception assertReadListThrowsException("{\"foo\": \"bar\"}"); assertReadListThrowsException("{\"foo\": 1, \"bar\": 2}"); assertReadListThrowsException("{\"foo\": {\"bar\":\"baz\"}}"); } @SuppressWarnings("unchecked") private <T> List<T> readList(String source) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); return (List<T>) (randomBoolean() ? parser.listOrderedMap() : parser.list()); } } private void assertReadListThrowsException(String source) { try { readList(source); fail("should have thrown a parse exception"); } catch (Exception e) { assertThat(e, instanceOf(XContentParseException.class)); assertThat(e.getMessage(), containsString("Failed to parse list")); } } public void testReadMapStrings() throws IOException { Map<String, String> map = readMapStrings("{\"foo\": {\"kbar\":\"vbar\"}}"); assertThat(map.get("kbar"), equalTo("vbar")); assertThat(map.size(), equalTo(1)); map = readMapStrings("{\"foo\": {\"kbar\":\"vbar\", \"kbaz\":\"vbaz\"}}"); assertThat(map.get("kbar"), equalTo("vbar")); assertThat(map.get("kbaz"), equalTo("vbaz")); assertThat(map.size(), equalTo(2)); map = readMapStrings("{\"foo\": {}}"); assertThat(map.size(), equalTo(0)); } public void testMap() throws IOException { String source = "{\"i\": {\"_doc\": {\"f1\": {\"type\": \"text\", \"analyzer\": \"english\"}, " + "\"f2\": {\"type\": \"object\", \"properties\": {\"sub1\": {\"type\": \"keyword\", \"foo\": 17}}}}}}"; Map<String, Object> f1 = new HashMap<>(); f1.put("type", "text"); f1.put("analyzer", "english"); Map<String, Object> sub1 = new HashMap<>(); sub1.put("type", "keyword"); sub1.put("foo", 17); Map<String, Object> properties = new HashMap<>(); properties.put("sub1", sub1); Map<String, Object> f2 = new HashMap<>(); f2.put("type", "object"); f2.put("properties", properties); Map<String, Object> doc = new HashMap<>(); doc.put("f1", f1); doc.put("f2", f2); Map<String, Object> expected = new HashMap<>(); expected.put("_doc", doc); Map<String, Object> i = new HashMap<>(); i.put("i", expected); try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); Map<String, Object> map = parser.map(); assertThat(map, equalTo(i)); } } private Map<String, String> readMapStrings(String source) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); return randomBoolean() ? parser.mapStringsOrdered() : parser.mapStrings(); } } @SuppressWarnings("deprecation") // #isBooleanValueLenient() and #booleanValueLenient() are the test subjects public void testReadLenientBooleans() throws IOException { // allow String, boolean and int representations of lenient booleans String falsy = randomFrom("\"off\"", "\"no\"", "\"0\"", "0", "\"false\"", "false"); String truthy = randomFrom("\"on\"", "\"yes\"", "\"1\"", "1", "\"true\"", "true"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn( Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValueLenient()); assertFalse(parser.booleanValueLenient()); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn( Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValueLenient()); assertTrue(parser.booleanValueLenient()); } } public void testReadBooleansFailsForLenientBooleans() throws IOException { String falsy = randomFrom("\"off\"", "\"no\"", "\"0\"", "0"); String truthy = randomFrom("\"on\"", "\"yes\"", "\"1\"", "1"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER))); assertFalse(parser.isBooleanValue()); if (token.equals(XContentParser.Token.VALUE_STRING)) { expectThrows(IllegalArgumentException.class, parser::booleanValue); } else { expectThrows(JsonParseException.class, parser::booleanValue); } token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER))); assertFalse(parser.isBooleanValue()); if (token.equals(XContentParser.Token.VALUE_STRING)) { expectThrows(IllegalArgumentException.class, parser::booleanValue); } else { expectThrows(JsonParseException.class, parser::booleanValue); } } } public void testReadBooleans() throws IOException { String falsy = randomFrom("\"false\"", "false"); String truthy = randomFrom("\"true\"", "true"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertFalse(parser.booleanValue()); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertTrue(parser.booleanValue()); } } public void testEmptyList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals(Collections.emptyList(), parser.list()); } } public void testSimpleList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .value(1) .value(3) .value(0) .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals(Arrays.asList(1, 3, 0), parser.list()); } } public void testNestedList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .startArray().endArray() .startArray().value(1).value(3).endArray() .startArray().value(2).endArray() .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals( Arrays.asList(Collections.<Integer>emptyList(), Arrays.asList(1, 3), Arrays.asList(2)), parser.list()); } } public void testNestedMapInList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .startObject().field("foo", "bar").endObject() .startObject().endObject() .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals( Arrays.asList(singletonMap("foo", "bar"), emptyMap()), parser.list()); } } public void testSubParserObject() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfTokens; numberOfTokens = generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field assertEquals("first_field", parser.currentName()); assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); // foo assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // marked field assertEquals("marked_field", parser.currentName()); assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // { XContentParser subParser = new XContentSubParser(parser); try { int tokensToSkip = randomInt(numberOfTokens - 1); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } if (randomBoolean()) { // And sometimes skipping children subParser.skipChildren(); } } finally { assertFalse(subParser.isClosed()); subParser.close(); assertTrue(subParser.isClosed()); } assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // last field assertEquals("last_field", parser.currentName()); assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } } public void testSubParserArray() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfArrayElements = randomInt(10); builder.startObject(); builder.field("array"); builder.startArray(); int numberOfTokens = 0; for (int i = 0; i < numberOfArrayElements; ++i) { numberOfTokens += generateRandomObject(builder, 0); } builder.endArray(); builder.endObject(); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // array field assertEquals("array", parser.currentName()); assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); // [ XContentParser subParser = new XContentSubParser(parser); try { int tokensToSkip = randomInt(numberOfTokens); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } if (randomBoolean()) { // And sometimes skipping children subParser.skipChildren(); } } finally { assertFalse(subParser.isClosed()); subParser.close(); assertTrue(subParser.isClosed()); } assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken()); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } } public void testCreateSubParserAtAWrongPlace() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field assertEquals("first_field", parser.currentName()); IllegalStateException exception = expectThrows(IllegalStateException.class, () -> new XContentSubParser(parser)); assertEquals("The sub parser has to be created on the start of an object or array", exception.getMessage()); } } public void testCreateRootSubParser() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfTokens = generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); try (XContentParser subParser = new XContentSubParser(parser)) { int tokensToSkip = randomInt(numberOfTokens + 3); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } } assertNull(parser.nextToken()); } } /** * Generates a random object {"first_field": "foo", "marked_field": {...random...}, "last_field": "bar} * * Returns the number of tokens in the marked field */ private int generateRandomObjectForMarking(XContentBuilder builder) throws IOException { builder.startObject() .field("first_field", "foo") .field("marked_field"); int numberOfTokens = generateRandomObject(builder, 0); builder.field("last_field", "bar").endObject(); return numberOfTokens; } private int generateRandomObject(XContentBuilder builder, int level) throws IOException { int tokens = 2; builder.startObject(); int numberOfElements = randomInt(5); for (int i = 0; i < numberOfElements; i++) { builder.field(randomAlphaOfLength(10) + "_" + i); tokens += generateRandomValue(builder, level + 1); } builder.endObject(); return tokens; } private int generateRandomValue(XContentBuilder builder, int level) throws IOException { @SuppressWarnings("unchecked") CheckedSupplier<Integer, IOException> fieldGenerator = randomFrom( () -> { builder.value(randomInt()); return 1; }, () -> { builder.value(randomAlphaOfLength(10)); return 1; }, () -> { builder.value(randomDouble()); return 1; }, () -> { if (level < 3) { // don't need to go too deep return generateRandomObject(builder, level + 1); } else { builder.value(0); return 1; } }, () -> { if (level < 5) { // don't need to go too deep return generateRandomArray(builder, level); } else { builder.value(0); return 1; } } ); return fieldGenerator.get(); } private int generateRandomArray(XContentBuilder builder, int level) throws IOException { int tokens = 2; int arraySize = randomInt(3); builder.startArray(); for (int i = 0; i < arraySize; i++) { tokens += generateRandomValue(builder, level + 1); } builder.endArray(); return tokens; } }
libs/x-content/src/test/java/org/elasticsearch/common/xcontent/XContentParserTests.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common.xcontent; import com.fasterxml.jackson.core.JsonParseException; import org.elasticsearch.common.CheckedSupplier; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.ESTestCase; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.nullValue; public class XContentParserTests extends ESTestCase { public void testFloat() throws IOException { final XContentType xContentType = randomFrom(XContentType.values()); final String field = randomAlphaOfLengthBetween(1, 5); final Float value = randomFloat(); try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.startObject(); if (randomBoolean()) { builder.field(field, value); } else { builder.field(field).value(value); } builder.endObject(); final Number number; try (XContentParser parser = createParser(xContentType.xContent(), BytesReference.bytes(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals(field, parser.currentName()); assertEquals(XContentParser.Token.VALUE_NUMBER, parser.nextToken()); number = parser.numberValue(); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } assertEquals(value, number.floatValue(), 0.0f); if (xContentType == XContentType.CBOR) { // CBOR parses back a float assertTrue(number instanceof Float); } else { // JSON, YAML and SMILE parses back the float value as a double // This will change for SMILE in Jackson 2.9 where all binary based // formats will return a float assertTrue(number instanceof Double); } } } public void testReadList() throws IOException { assertThat(readList("{\"foo\": [\"bar\"]}"), contains("bar")); assertThat(readList("{\"foo\": [\"bar\",\"baz\"]}"), contains("bar", "baz")); assertThat(readList("{\"foo\": [1, 2, 3], \"bar\": 4}"), contains(1, 2, 3)); assertThat(readList("{\"foo\": [{\"bar\":1},{\"baz\":2},{\"qux\":3}]}"), hasSize(3)); assertThat(readList("{\"foo\": [null]}"), contains(nullValue())); assertThat(readList("{\"foo\": []}"), hasSize(0)); assertThat(readList("{\"foo\": [1]}"), contains(1)); assertThat(readList("{\"foo\": [1,2]}"), contains(1, 2)); assertThat(readList("{\"foo\": [{},{},{},{}]}"), hasSize(4)); } public void testReadListThrowsException() throws IOException { // Calling XContentParser.list() or listOrderedMap() to read a simple // value or object should throw an exception assertReadListThrowsException("{\"foo\": \"bar\"}"); assertReadListThrowsException("{\"foo\": 1, \"bar\": 2}"); assertReadListThrowsException("{\"foo\": {\"bar\":\"baz\"}}"); } @SuppressWarnings("unchecked") private <T> List<T> readList(String source) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); return (List<T>) (randomBoolean() ? parser.listOrderedMap() : parser.list()); } } private void assertReadListThrowsException(String source) { try { readList(source); fail("should have thrown a parse exception"); } catch (Exception e) { assertThat(e, instanceOf(XContentParseException.class)); assertThat(e.getMessage(), containsString("Failed to parse list")); } } public void testReadMapStrings() throws IOException { Map<String, String> map = readMapStrings("{\"foo\": {\"kbar\":\"vbar\"}}"); assertThat(map.get("kbar"), equalTo("vbar")); assertThat(map.size(), equalTo(1)); map = readMapStrings("{\"foo\": {\"kbar\":\"vbar\", \"kbaz\":\"vbaz\"}}"); assertThat(map.get("kbar"), equalTo("vbar")); assertThat(map.get("kbaz"), equalTo("vbaz")); assertThat(map.size(), equalTo(2)); map = readMapStrings("{\"foo\": {}}"); assertThat(map.size(), equalTo(0)); } public void testMap() throws IOException { String source = "{\"i\": {\"_doc\": {\"f1\": {\"type\": \"text\", \"analyzer\": \"english\"}, " + "\"f2\": {\"type\": \"object\", \"properties\": {\"sub1\": {\"type\": \"keyword\", \"foo\": 17}}}}}}"; Map<String, Object> f1 = new HashMap<>(); f1.put("type", "text"); f1.put("analyzer", "english"); Map<String, Object> sub1 = new HashMap<>(); sub1.put("type", "keyword"); sub1.put("foo", 17); Map<String, Object> properties = new HashMap<>(); properties.put("sub1", sub1); Map<String, Object> f2 = new HashMap<>(); f2.put("type", "object"); f2.put("properties", properties); Map<String, Object> doc = new HashMap<>(); doc.put("f1", f1); doc.put("f2", f2); Map<String, Object> expected = new HashMap<>(); expected.put("_doc", doc); Map<String, Object> i = new HashMap<>(); i.put("i", expected); try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); Map<String, Object> map = parser.map(); assertThat(map, equalTo(i)); } } private Map<String, String> readMapStrings(String source) throws IOException { try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); return randomBoolean() ? parser.mapStringsOrdered() : parser.mapStrings(); } } @SuppressWarnings("deprecation") // #isBooleanValueLenient() and #booleanValueLenient() are the test subjects public void testReadLenientBooleans() throws IOException { // allow String, boolean and int representations of lenient booleans String falsy = randomFrom("\"off\"", "\"no\"", "\"0\"", "0", "\"false\"", "false"); String truthy = randomFrom("\"on\"", "\"yes\"", "\"1\"", "1", "\"true\"", "true"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn( Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValueLenient()); assertFalse(parser.booleanValueLenient()); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn( Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValueLenient()); assertTrue(parser.booleanValueLenient()); } } public void testReadBooleansFailsForLenientBooleans() throws IOException { String falsy = randomFrom("\"off\"", "\"no\"", "\"0\"", "0"); String truthy = randomFrom("\"on\"", "\"yes\"", "\"1\"", "1"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER))); assertFalse(parser.isBooleanValue()); if (token.equals(XContentParser.Token.VALUE_STRING)) { expectThrows(IllegalArgumentException.class, parser::booleanValue); } else { expectThrows(JsonParseException.class, parser::booleanValue); } token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_NUMBER))); assertFalse(parser.isBooleanValue()); if (token.equals(XContentParser.Token.VALUE_STRING)) { expectThrows(IllegalArgumentException.class, parser::booleanValue); } else { expectThrows(JsonParseException.class, parser::booleanValue); } } } public void testReadBooleans() throws IOException { String falsy = randomFrom("\"false\"", "false"); String truthy = randomFrom("\"true\"", "true"); try (XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"foo\": " + falsy + ", \"bar\": " + truthy + "}")) { XContentParser.Token token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.START_OBJECT)); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("foo")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertFalse(parser.booleanValue()); token = parser.nextToken(); assertThat(token, equalTo(XContentParser.Token.FIELD_NAME)); assertThat(parser.currentName(), equalTo("bar")); token = parser.nextToken(); assertThat(token, isIn(Arrays.asList(XContentParser.Token.VALUE_STRING, XContentParser.Token.VALUE_BOOLEAN))); assertTrue(parser.isBooleanValue()); assertTrue(parser.booleanValue()); } } public void testEmptyList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals(Collections.emptyList(), parser.list()); } } public void testSimpleList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .value(1) .value(3) .value(0) .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals(Arrays.asList(1, 3, 0), parser.list()); } } public void testNestedList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .startArray().endArray() .startArray().value(1).value(3).endArray() .startArray().value(2).endArray() .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals( Arrays.asList(Collections.<Integer>emptyList(), Arrays.asList(1, 3), Arrays.asList(2)), parser.list()); } } public void testNestedMapInList() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject() .startArray("some_array") .startObject().field("foo", "bar").endObject() .startObject().endObject() .endArray().endObject(); try (XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder))) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); assertEquals("some_array", parser.currentName()); if (random().nextBoolean()) { // sometimes read the start array token, sometimes not assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); } assertEquals( Arrays.asList(singletonMap("foo", "bar"), emptyMap()), parser.list()); } } public void testSubParserObject() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfTokens; numberOfTokens = generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field assertEquals("first_field", parser.currentName()); assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); // foo assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // marked field assertEquals("marked_field", parser.currentName()); assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); // { XContentParser subParser = new XContentSubParser(parser); try { int tokensToSkip = randomInt(numberOfTokens - 1); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } if (randomBoolean()) { // And sometimes skipping children subParser.skipChildren(); } } finally { assertFalse(subParser.isClosed()); subParser.close(); assertTrue(subParser.isClosed()); } assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // last field assertEquals("last_field", parser.currentName()); assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } } public void testSubParserArray() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfArrayElements = randomInt(10); builder.startObject(); builder.field("array"); builder.startArray(); int numberOfTokens = 0; for (int i = 0; i < numberOfArrayElements; ++i) { numberOfTokens += generateRandomObjectForMarking(builder); } builder.endArray(); builder.endObject(); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // array field assertEquals("array", parser.currentName()); assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); // [ XContentParser subParser = new XContentSubParser(parser); try { int tokensToSkip = randomInt(numberOfTokens - 1); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } if (randomBoolean()) { // And sometimes skipping children subParser.skipChildren(); } } finally { assertFalse(subParser.isClosed()); subParser.close(); assertTrue(subParser.isClosed()); } assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken()); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); } } public void testCreateSubParserAtAWrongPlace() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); // first field assertEquals("first_field", parser.currentName()); IllegalStateException exception = expectThrows(IllegalStateException.class, () -> new XContentSubParser(parser)); assertEquals("The sub parser has to be created on the start of an object or array", exception.getMessage()); } } public void testCreateRootSubParser() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); int numberOfTokens = generateRandomObjectForMarking(builder); String content = Strings.toString(builder); try (XContentParser parser = createParser(JsonXContent.jsonXContent, content)) { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); try (XContentParser subParser = new XContentSubParser(parser)) { int tokensToSkip = randomInt(numberOfTokens + 3); for (int i = 0; i < tokensToSkip; i++) { // Simulate incomplete parsing assertNotNull(subParser.nextToken()); } } assertNull(parser.nextToken()); } } /** * Generates a random object {"first_field": "foo", "marked_field": {...random...}, "last_field": "bar} * * Returns the number of tokens in the marked field */ private int generateRandomObjectForMarking(XContentBuilder builder) throws IOException { builder.startObject() .field("first_field", "foo") .field("marked_field"); int numberOfTokens = generateRandomObject(builder, 0); builder.field("last_field", "bar").endObject(); return numberOfTokens; } private int generateRandomObject(XContentBuilder builder, int level) throws IOException { int tokens = 2; builder.startObject(); int numberOfElements = randomInt(5); for (int i = 0; i < numberOfElements; i++) { builder.field(randomAlphaOfLength(10) + "_" + i); tokens += generateRandomValue(builder, level + 1); } builder.endObject(); return tokens; } private int generateRandomValue(XContentBuilder builder, int level) throws IOException { @SuppressWarnings("unchecked") CheckedSupplier<Integer, IOException> fieldGenerator = randomFrom( () -> { builder.value(randomInt()); return 1; }, () -> { builder.value(randomAlphaOfLength(10)); return 1; }, () -> { builder.value(randomDouble()); return 1; }, () -> { if (level < 3) { // don't need to go too deep return generateRandomObject(builder, level + 1); } else { builder.value(0); return 1; } }, () -> { if (level < 5) { // don't need to go too deep return generateRandomArray(builder, level); } else { builder.value(0); return 1; } } ); return fieldGenerator.get(); } private int generateRandomArray(XContentBuilder builder, int level) throws IOException { int tokens = 2; int arraySize = randomInt(3); builder.startArray(); for (int i = 0; i < arraySize; i++) { tokens += generateRandomValue(builder, level + 1); } builder.endArray(); return tokens; } }
Unmute and fix testSubParserArray (#40626) testSubParserArray failed, fixed and improved to not always have an object as outer-level inside array. Closes #40617
libs/x-content/src/test/java/org/elasticsearch/common/xcontent/XContentParserTests.java
Unmute and fix testSubParserArray (#40626)
Java
apache-2.0
24f70e9111d185318bff6f043f181c0637a40db9
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.shell; import static java.util.regex.Pattern.compile; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.helpers.collection.IteratorUtil.asCollection; import static org.neo4j.kernel.impl.util.FileUtils.deleteRecursively; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.shell.impl.RemoteOutput; import org.neo4j.shell.impl.SameJvmClient; import org.neo4j.shell.kernel.GraphDatabaseShellServer; @Ignore public abstract class AbstractShellTest { private static final String DB_PATH = "target/var/shelldb"; protected static GraphDatabaseService db; private static ShellServer shellServer; private ShellClient shellClient; protected static final RelationshipType RELATIONSHIP_TYPE = withName( "TYPE" ); @BeforeClass public static void startUp() throws Exception { deleteRecursively( new File( DB_PATH ) ); db = new EmbeddedGraphDatabase( DB_PATH ); shellServer = new GraphDatabaseShellServer( db ); } @Before public void doBefore() { shellClient = new SameJvmClient( shellServer ); } @After public void doAfter() { shellClient.shutdown(); } @AfterClass public static void shutDown() throws Exception { shellServer.shutdown(); db.shutdown(); } protected static String pwdOutputFor( Object... entities ) { StringBuilder builder = new StringBuilder(); for ( Object entity : entities ) { builder.append( (builder.length() == 0 ? "" : "-->") ); if ( entity instanceof Node ) { builder.append( "(" + ((Node)entity).getId() + ")" ); } else { builder.append( "<" + ((Relationship)entity).getId() + ">" ); } } return Pattern.quote( builder.toString() ); } public void executeCommand( String command, String... theseLinesMustExistRegEx ) throws Exception { OutputCollector output = new OutputCollector(); shellServer.interpretLine( command, shellClient.session(), output ); for ( String lineThatMustExist : theseLinesMustExistRegEx ) { boolean negative = lineThatMustExist.startsWith( "!" ); lineThatMustExist = negative ? lineThatMustExist.substring( 1 ) : lineThatMustExist; Pattern pattern = compile( lineThatMustExist ); boolean found = false; for ( String line : output ) { if ( pattern.matcher( line ).find() ) { found = true; break; } } assertTrue( "Was expecting a line matching '" + lineThatMustExist + "', but didn't find any from out of " + asCollection( output ), found != negative ); } } public void executeCommandExpectingException( String command, String errorMessageShouldContain ) throws Exception { OutputCollector output = new OutputCollector(); try { shellServer.interpretLine( command, shellClient.session(), output ); fail( "Was expecting an exception" ); } catch ( ShellException e ) { String errorMessage = e.getMessage(); if ( !errorMessage.toLowerCase().contains( errorMessageShouldContain.toLowerCase() ) ) { fail( "Error message '" + errorMessage + "' should have contained '" + errorMessageShouldContain + "'" ); } } } protected void assertRelationshipExists( Relationship relationship ) { assertRelationshipExists( relationship.getId() ); } protected void assertRelationshipExists( long id ) { db.getRelationshipById( id ); } protected void assertRelationshipDoesnExist( Relationship relationship ) { assertRelationshipDoesnExist( relationship.getId() ); } protected void assertRelationshipDoesnExist( long id ) { try { db.getRelationshipById( id ); fail( "Relationship " + id + " shouldn't exist" ); } catch ( NotFoundException e ) { // Good } } protected Relationship[] createRelationshipChain( int length ) { return createRelationshipChain( db.getReferenceNode(), length ); } protected Relationship[] createRelationshipChain( Node startingFromNode, int length ) { Relationship[] rels = new Relationship[length]; Transaction tx = db.beginTx(); Node firstNode = db.getReferenceNode(); for ( int i = 0; i < rels.length; i++ ) { Node secondNode = db.createNode(); rels[i] = firstNode.createRelationshipTo( secondNode, RELATIONSHIP_TYPE ); firstNode = secondNode; } tx.success(); tx.finish(); return rels; } protected void setProperty( Node node, String key, Object value ) { Transaction tx = db.beginTx(); node.setProperty( key, value ); tx.success(); tx.finish(); } public class OutputCollector implements Output, Serializable, Iterable<String> { private static final long serialVersionUID = 1L; private final List<String> lines = new ArrayList<String>(); private String ongoingLine = ""; @Override public Appendable append( CharSequence csq, int start, int end ) throws IOException { this.print( RemoteOutput.asString( csq ).substring( start, end ) ); return this; } @Override public Appendable append( char c ) throws IOException { this.print( c ); return this; } @Override public Appendable append( CharSequence csq ) throws IOException { this.print( RemoteOutput.asString( csq ) ); return this; } @Override public void println( Serializable object ) throws RemoteException { print( object ); println(); } @Override public void println() throws RemoteException { lines.add( ongoingLine ); ongoingLine = ""; } @Override public void print( Serializable object ) throws RemoteException { ongoingLine += object.toString(); } @Override public Iterator<String> iterator() { return lines.iterator(); } } }
community/shell/src/test/java/org/neo4j/shell/AbstractShellTest.java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.shell; import static java.util.regex.Pattern.compile; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.neo4j.graphdb.DynamicRelationshipType.withName; import static org.neo4j.helpers.collection.IteratorUtil.asCollection; import static org.neo4j.kernel.impl.util.FileUtils.deleteRecursively; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.shell.impl.RemoteOutput; import org.neo4j.shell.impl.SameJvmClient; import org.neo4j.shell.kernel.GraphDatabaseShellServer; public class AbstractShellTest { private static final String DB_PATH = "target/var/shelldb"; protected static GraphDatabaseService db; private static ShellServer shellServer; private ShellClient shellClient; protected static final RelationshipType RELATIONSHIP_TYPE = withName( "TYPE" ); @BeforeClass public static void startUp() throws Exception { deleteRecursively( new File( DB_PATH ) ); db = new EmbeddedGraphDatabase( DB_PATH ); shellServer = new GraphDatabaseShellServer( db ); } @Before public void doBefore() { shellClient = new SameJvmClient( shellServer ); } @After public void doAfter() { shellClient.shutdown(); } @AfterClass public static void shutDown() throws Exception { shellServer.shutdown(); db.shutdown(); } protected static String pwdOutputFor( Object... entities ) { StringBuilder builder = new StringBuilder(); for ( Object entity : entities ) { builder.append( (builder.length() == 0 ? "" : "-->") ); if ( entity instanceof Node ) { builder.append( "(" + ((Node)entity).getId() + ")" ); } else { builder.append( "<" + ((Relationship)entity).getId() + ">" ); } } return Pattern.quote( builder.toString() ); } public void executeCommand( String command, String... theseLinesMustExistRegEx ) throws Exception { OutputCollector output = new OutputCollector(); shellServer.interpretLine( command, shellClient.session(), output ); for ( String lineThatMustExist : theseLinesMustExistRegEx ) { boolean negative = lineThatMustExist.startsWith( "!" ); lineThatMustExist = negative ? lineThatMustExist.substring( 1 ) : lineThatMustExist; Pattern pattern = compile( lineThatMustExist ); boolean found = false; for ( String line : output ) { if ( pattern.matcher( line ).find() ) { found = true; break; } } assertTrue( "Was expecting a line matching '" + lineThatMustExist + "', but didn't find any from out of " + asCollection( output ), found != negative ); } } public void executeCommandExpectingException( String command, String errorMessageShouldContain ) throws Exception { OutputCollector output = new OutputCollector(); try { shellServer.interpretLine( command, shellClient.session(), output ); fail( "Was expecting an exception" ); } catch ( ShellException e ) { String errorMessage = e.getMessage(); if ( !errorMessage.toLowerCase().contains( errorMessageShouldContain.toLowerCase() ) ) { fail( "Error message '" + errorMessage + "' should have contained '" + errorMessageShouldContain + "'" ); } } } protected void assertRelationshipExists( Relationship relationship ) { assertRelationshipExists( relationship.getId() ); } protected void assertRelationshipExists( long id ) { db.getRelationshipById( id ); } protected void assertRelationshipDoesnExist( Relationship relationship ) { assertRelationshipDoesnExist( relationship.getId() ); } protected void assertRelationshipDoesnExist( long id ) { try { db.getRelationshipById( id ); fail( "Relationship " + id + " shouldn't exist" ); } catch ( NotFoundException e ) { // Good } } protected Relationship[] createRelationshipChain( int length ) { return createRelationshipChain( db.getReferenceNode(), length ); } protected Relationship[] createRelationshipChain( Node startingFromNode, int length ) { Relationship[] rels = new Relationship[length]; Transaction tx = db.beginTx(); Node firstNode = db.getReferenceNode(); for ( int i = 0; i < rels.length; i++ ) { Node secondNode = db.createNode(); rels[i] = firstNode.createRelationshipTo( secondNode, RELATIONSHIP_TYPE ); firstNode = secondNode; } tx.success(); tx.finish(); return rels; } protected void setProperty( Node node, String key, Object value ) { Transaction tx = db.beginTx(); node.setProperty( key, value ); tx.success(); tx.finish(); } public class OutputCollector implements Output, Serializable, Iterable<String> { private static final long serialVersionUID = 1L; private final List<String> lines = new ArrayList<String>(); private String ongoingLine = ""; @Override public Appendable append( CharSequence csq, int start, int end ) throws IOException { this.print( RemoteOutput.asString( csq ).substring( start, end ) ); return this; } @Override public Appendable append( char c ) throws IOException { this.print( c ); return this; } @Override public Appendable append( CharSequence csq ) throws IOException { this.print( RemoteOutput.asString( csq ) ); return this; } @Override public void println( Serializable object ) throws RemoteException { print( object ); println(); } @Override public void println() throws RemoteException { lines.add( ongoingLine ); ongoingLine = ""; } @Override public void print( Serializable object ) throws RemoteException { ongoingLine += object.toString(); } @Override public Iterator<String> iterator() { return lines.iterator(); } } }
Test class error
community/shell/src/test/java/org/neo4j/shell/AbstractShellTest.java
Test class error
Java
apache-2.0
a61512451a6d3ce9f96fa1b902c41cbcde7558a8
0
ksokol/carldav
/* * Copyright 2005-2007 Open Source Applications 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.unitedinternet.cosmo.dao.query.hibernate; import carldav.entity.Item; import org.unitedinternet.cosmo.calendar.query.CalendarFilter; import org.unitedinternet.cosmo.dao.query.ItemFilterProcessor; import org.unitedinternet.cosmo.model.filter.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.*; import java.util.Map.Entry; import static java.util.Locale.ENGLISH; /** * Standard Implementation of <code>ItemFilterProcessor</code>. * Translates filter into HQL Query, executes * query and processes the results. */ public class StandardItemFilterProcessor implements ItemFilterProcessor { private static final CalendarFilterConverter filterConverter = new CalendarFilterConverter(); @PersistenceContext private EntityManager entityManager; public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public List<Item> processFilter(CalendarFilter filter) { final ItemFilter itemFilter = filterConverter.translateToItemFilter(filter); Query hibQuery = buildQuery(entityManager, itemFilter); return hibQuery.getResultList(); } /** * Build Hibernate Query from ItemFilter using HQL. * The query returned is essentially the first pass at * retrieving the matched items. A second pass is required in * order determine if any recurring events match a timeRange * in the filter. This is due to the fact that recurring events * may have complicated recurrence rules that are extremely * hard to match using HQL. * * @param session session * @param filter item filter * @return hibernate query built using HQL */ public Query buildQuery(EntityManager session, ItemFilter filter) { StringBuffer selectBuf = new StringBuffer(); StringBuffer whereBuf = new StringBuffer(); StringBuffer orderBuf = new StringBuffer(); Map<String, Object> params = new TreeMap<>(); selectBuf.append("select i from Item i"); if (filter instanceof NoteItemFilter) { handleNoteItemFilter(selectBuf, whereBuf, params, (NoteItemFilter) filter); } else { handleItemFilter(selectBuf, whereBuf, params, filter); } selectBuf.append(whereBuf); selectBuf.append(orderBuf); Query hqlQuery = session.createQuery(selectBuf.toString()); for (Entry<String, Object> param : params.entrySet()) { hqlQuery.setParameter(param.getKey(), param.getValue()); } if (filter.getMaxResults() != null) { hqlQuery.setMaxResults(filter.getMaxResults()); } return hqlQuery; } private void handleItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, ItemFilter filter) { // filter on uid if (filter.getUid() != null) { formatExpression(whereBuf, params, "i.uid", filter.getUid()); } // filter on parent if (filter.getParent() != null) { selectBuf.append(" join i.collection pd"); appendWhere(whereBuf, "pd.id=:parent"); params.put("parent", filter.getParent()); } if (filter.getDisplayName() != null) { formatExpression(whereBuf, params, "i.displayName", filter.getDisplayName()); } handleStampFilters(whereBuf, filter, params); } private void handleStampFilters(StringBuffer whereBuf, ItemFilter filter, Map<String, Object> params) { for (StampFilter stampFilter : filter.getStampFilters()) { handleStampFilter(whereBuf, stampFilter, params); } } private void handleStampFilter(StringBuffer whereBuf, StampFilter filter, Map<String, Object> params) { if(filter.getType() != null) { appendWhere(whereBuf, "i.type=:type"); params.put("type", filter.getType()); } // handle recurring event filter if (filter.getIsRecurring() != null) { appendWhere(whereBuf, "(i.recurring=:recurring)"); params.put("recurring", filter.getIsRecurring()); } if (filter.getPeriod() != null) { whereBuf.append(" and ( "); whereBuf.append("(i.startDate < :endDate)"); whereBuf.append(" and i.endDate > :startDate)"); // edge case where start==end whereBuf.append(" or (i.startDate=i.endDate and (i.startDate=:startDate or i.startDate=:endDate))"); whereBuf.append(")"); params.put("startDate", filter.getStart()); params.put("endDate", filter.getEnd()); } } private void handleNoteItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, NoteItemFilter filter) { handleItemFilter(selectBuf, whereBuf, params, filter); handleContentItemFilter(selectBuf, whereBuf, params, filter); // filter by icaluid if (filter.getIcalUid() != null) { formatExpression(whereBuf, params, "i.uid", filter.getIcalUid()); } // filter by reminderTime if (filter.getReminderTime() != null) { formatExpression(whereBuf, params, "i.remindertime", filter.getReminderTime()); } if(filter.getModifiedSince() != null){ formatExpression(whereBuf, params, "i.modifiedDate", filter.getModifiedSince()); } } private void handleContentItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, ItemFilter filter) { if ("".equals(selectBuf.toString())) { handleItemFilter(selectBuf, whereBuf, params, filter); } } private void appendWhere(StringBuffer whereBuf, String toAppend) { if ("".equals(whereBuf.toString())) { whereBuf.append(" where " + toAppend); } else { whereBuf.append(" and " + toAppend); } } private String formatForLike(String toFormat) { return "%" + toFormat + "%"; } private void formatExpression(StringBuffer whereBuf, Map<String, Object> params, String propName, FilterCriteria fc) { StringBuffer expBuf = new StringBuffer(); FilterExpression exp = (FilterExpression) fc; if (exp instanceof NullExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" is not null"); } else { expBuf.append(" is null"); } } else if (exp instanceof BetweenExpression) { BetweenExpression be = (BetweenExpression) exp; expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" not"); } String param = "param" + params.size(); expBuf.append(" between :" + param); params.put(param, be.getValue1()); param = "param" + params.size(); expBuf.append(" and :" + param); params.put(param, be.getValue2()); } else { String param = "param" + params.size(); if (exp instanceof EqualsExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append("!="); } else { expBuf.append("="); } params.put(param, exp.getValue()); } else if (exp instanceof LikeExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" not like "); } else { expBuf.append(" like "); } params.put(param, formatForLike(exp.getValue().toString())); } else if (exp instanceof ILikeExpression) { expBuf.append("lower(" + propName + ")"); if (exp.isNegated()) { expBuf.append(" not like "); } else { expBuf.append(" like "); } params.put(param, formatForLike(exp.getValue().toString().toLowerCase(ENGLISH))); } expBuf.append(":" + param); } appendWhere(whereBuf, expBuf.toString()); } }
src/main/java/org/unitedinternet/cosmo/dao/query/hibernate/StandardItemFilterProcessor.java
/* * Copyright 2005-2007 Open Source Applications 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.unitedinternet.cosmo.dao.query.hibernate; import carldav.entity.Item; import org.unitedinternet.cosmo.calendar.query.CalendarFilter; import org.unitedinternet.cosmo.dao.query.ItemFilterProcessor; import org.unitedinternet.cosmo.model.filter.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.*; import java.util.Map.Entry; import static java.util.Locale.ENGLISH; /** * Standard Implementation of <code>ItemFilterProcessor</code>. * Translates filter into HQL Query, executes * query and processes the results. */ public class StandardItemFilterProcessor implements ItemFilterProcessor { private static final CalendarFilterConverter filterConverter = new CalendarFilterConverter(); @PersistenceContext private EntityManager entityManager; public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public List<Item> processFilter(CalendarFilter filter) { final ItemFilter itemFilter = filterConverter.translateToItemFilter(filter); Query hibQuery = buildQuery(entityManager, itemFilter); return hibQuery.getResultList(); } /** * Build Hibernate Query from ItemFilter using HQL. * The query returned is essentially the first pass at * retrieving the matched items. A second pass is required in * order determine if any recurring events match a timeRange * in the filter. This is due to the fact that recurring events * may have complicated recurrence rules that are extremely * hard to match using HQL. * * @param session session * @param filter item filter * @return hibernate query built using HQL */ public Query buildQuery(EntityManager session, ItemFilter filter) { StringBuffer selectBuf = new StringBuffer(); StringBuffer whereBuf = new StringBuffer(); StringBuffer orderBuf = new StringBuffer(); Map<String, Object> params = new TreeMap<>(); if (filter instanceof NoteItemFilter) { handleNoteItemFilter(selectBuf, whereBuf, params, (NoteItemFilter) filter); } else { handleItemFilter(selectBuf, whereBuf, params, filter); } selectBuf.append(whereBuf); selectBuf.append(orderBuf); Query hqlQuery = session.createQuery(selectBuf.toString()); for (Entry<String, Object> param : params.entrySet()) { hqlQuery.setParameter(param.getKey(), param.getValue()); } if (filter.getMaxResults() != null) { hqlQuery.setMaxResults(filter.getMaxResults()); } return hqlQuery; } private void handleItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, ItemFilter filter) { if ("".equals(selectBuf.toString())) { selectBuf.append("select i from Item i"); } // filter on uid if (filter.getUid() != null) { formatExpression(whereBuf, params, "i.uid", filter.getUid()); } // filter on parent if (filter.getParent() != null) { selectBuf.append(" join i.collection pd"); appendWhere(whereBuf, "pd.id=:parent"); params.put("parent", filter.getParent()); } if (filter.getDisplayName() != null) { formatExpression(whereBuf, params, "i.displayName", filter.getDisplayName()); } handleStampFilters(whereBuf, filter, params); } private void handleStampFilters(StringBuffer whereBuf, ItemFilter filter, Map<String, Object> params) { for (StampFilter stampFilter : filter.getStampFilters()) { handleStampFilter(whereBuf, stampFilter, params); } } private void handleStampFilter(StringBuffer whereBuf, StampFilter filter, Map<String, Object> params) { if(filter.getType() != null) { appendWhere(whereBuf, "i.type=:type"); params.put("type", filter.getType()); } // handle recurring event filter if (filter.getIsRecurring() != null) { appendWhere(whereBuf, "(i.recurring=:recurring)"); params.put("recurring", filter.getIsRecurring()); } if (filter.getPeriod() != null) { whereBuf.append(" and ( "); whereBuf.append("(i.startDate < :endDate)"); whereBuf.append(" and i.endDate > :startDate)"); // edge case where start==end whereBuf.append(" or (i.startDate=i.endDate and (i.startDate=:startDate or i.startDate=:endDate))"); whereBuf.append(")"); params.put("startDate", filter.getStart()); params.put("endDate", filter.getEnd()); } } private void handleNoteItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, NoteItemFilter filter) { selectBuf.append("select i from Item i"); handleItemFilter(selectBuf, whereBuf, params, filter); handleContentItemFilter(selectBuf, whereBuf, params, filter); // filter by icaluid if (filter.getIcalUid() != null) { formatExpression(whereBuf, params, "i.uid", filter.getIcalUid()); } // filter by reminderTime if (filter.getReminderTime() != null) { formatExpression(whereBuf, params, "i.remindertime", filter.getReminderTime()); } if(filter.getModifiedSince() != null){ formatExpression(whereBuf, params, "i.modifiedDate", filter.getModifiedSince()); } } private void handleContentItemFilter(StringBuffer selectBuf, StringBuffer whereBuf, Map<String, Object> params, ItemFilter filter) { if ("".equals(selectBuf.toString())) { handleItemFilter(selectBuf, whereBuf, params, filter); } } private void appendWhere(StringBuffer whereBuf, String toAppend) { if ("".equals(whereBuf.toString())) { whereBuf.append(" where " + toAppend); } else { whereBuf.append(" and " + toAppend); } } private String formatForLike(String toFormat) { return "%" + toFormat + "%"; } private void formatExpression(StringBuffer whereBuf, Map<String, Object> params, String propName, FilterCriteria fc) { StringBuffer expBuf = new StringBuffer(); FilterExpression exp = (FilterExpression) fc; if (exp instanceof NullExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" is not null"); } else { expBuf.append(" is null"); } } else if (exp instanceof BetweenExpression) { BetweenExpression be = (BetweenExpression) exp; expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" not"); } String param = "param" + params.size(); expBuf.append(" between :" + param); params.put(param, be.getValue1()); param = "param" + params.size(); expBuf.append(" and :" + param); params.put(param, be.getValue2()); } else { String param = "param" + params.size(); if (exp instanceof EqualsExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append("!="); } else { expBuf.append("="); } params.put(param, exp.getValue()); } else if (exp instanceof LikeExpression) { expBuf.append(propName); if (exp.isNegated()) { expBuf.append(" not like "); } else { expBuf.append(" like "); } params.put(param, formatForLike(exp.getValue().toString())); } else if (exp instanceof ILikeExpression) { expBuf.append("lower(" + propName + ")"); if (exp.isNegated()) { expBuf.append(" not like "); } else { expBuf.append(" like "); } params.put(param, formatForLike(exp.getValue().toString().toLowerCase(ENGLISH))); } expBuf.append(":" + param); } appendWhere(whereBuf, expBuf.toString()); } }
simplified StandardItemFilterProcessor
src/main/java/org/unitedinternet/cosmo/dao/query/hibernate/StandardItemFilterProcessor.java
simplified StandardItemFilterProcessor
Java
apache-2.0
668728f906e434b7c2641b95efd7e18780ddd04f
0
ChetnaChaudhari/tez,apache/tez,navis/tez,dongjiaqiang/tez,Parth-Brahmbhatt/tez,bernhardschaefer/tez,guiling/tez,dongjiaqiang/tez,guiling/tez,sidseth/tez,guiling/tez,dongjiaqiang/tez,bernhardschaefer/tez,amirsojoodi/tez,sidseth/tez,apache/incubator-tez,navis/tez,amirsojoodi/tez,Altiscale/tez,Parth-Brahmbhatt/tez,apache/tez,zjffdu/tez,Altiscale/tez,ueshin/apache-tez,apache/tez,jth/tez,ueshin/apache-tez,jth/tez,ueshin/apache-tez,guiling/tez,navis/tez,jth/tez,ChetnaChaudhari/tez,zjffdu/tez,Parth-Brahmbhatt/tez,jth/tez,dongjiaqiang/tez,bernhardschaefer/tez,amirsojoodi/tez,dongjiaqiang/tez,sequenceiq/tez,Parth-Brahmbhatt/tez,sidseth/tez,zjffdu/tez,ueshin/apache-tez,navis/tez,Altiscale/tez,zjffdu/tez,bernhardschaefer/tez,amirsojoodi/tez,amirsojoodi/tez,sidseth/tez,apache/tez,apache/incubator-tez,zjffdu/tez,sequenceiq/tez,navis/tez,ueshin/apache-tez,guiling/tez,ChetnaChaudhari/tez,sidseth/tez,Parth-Brahmbhatt/tez,sequenceiq/tez,jth/tez,ChetnaChaudhari/tez,Altiscale/tez,bernhardschaefer/tez,apache/tez,ChetnaChaudhari/tez
/** * 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.tez.engine.newruntime; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.token.Token; import org.apache.tez.dag.api.ProcessorDescriptor; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.dag.records.TezTaskAttemptID; import org.apache.tez.engine.common.security.JobTokenIdentifier; import org.apache.tez.engine.newapi.Event; import org.apache.tez.engine.newapi.Input; import org.apache.tez.engine.newapi.LogicalIOProcessor; import org.apache.tez.engine.newapi.LogicalInput; import org.apache.tez.engine.newapi.LogicalOutput; import org.apache.tez.engine.newapi.Output; import org.apache.tez.engine.newapi.Processor; import org.apache.tez.engine.newapi.TezInputContext; import org.apache.tez.engine.newapi.TezOutputContext; import org.apache.tez.engine.newapi.TezProcessorContext; import org.apache.tez.engine.newapi.impl.EventMetaData; import org.apache.tez.engine.newapi.impl.EventMetaData.EventProducerConsumerType; import org.apache.tez.engine.newapi.impl.InputSpec; import org.apache.tez.engine.newapi.impl.OutputSpec; import org.apache.tez.engine.newapi.impl.TaskSpec; import org.apache.tez.engine.newapi.impl.TezEvent; import org.apache.tez.engine.newapi.impl.TezInputContextImpl; import org.apache.tez.engine.newapi.impl.TezOutputContextImpl; import org.apache.tez.engine.newapi.impl.TezProcessorContextImpl; import org.apache.tez.engine.newapi.impl.TezUmbilical; import org.apache.tez.engine.shuffle.common.ShuffleUtils; import com.google.common.base.Preconditions; @Private public class LogicalIOProcessorRuntimeTask extends RuntimeTask { private static final Log LOG = LogFactory .getLog(LogicalIOProcessorRuntimeTask.class); private final TaskSpec taskSpec; private final Configuration tezConf; private final TezUmbilical tezUmbilical; private final List<InputSpec> inputSpecs; private final List<LogicalInput> inputs; private final List<OutputSpec> outputSpecs; private final List<LogicalOutput> outputs; private final ProcessorDescriptor processorDescriptor; private final LogicalIOProcessor processor; private final Map<String, ByteBuffer> serviceConsumerMetadata; private Map<String, LogicalInput> inputMap; private Map<String, LogicalOutput> outputMap; public LogicalIOProcessorRuntimeTask(TaskSpec taskSpec, Configuration tezConf, TezUmbilical tezUmbilical, Token<JobTokenIdentifier> jobToken) throws IOException { // TODO Remove jobToken from here post TEZ-421 LOG.info("Initializing LogicalIOProcessorRuntimeTask with TaskSpec: " + taskSpec); this.taskSpec = taskSpec; this.tezConf = tezConf; this.tezUmbilical = tezUmbilical; this.inputSpecs = taskSpec.getInputs(); this.inputs = createInputs(inputSpecs); this.outputSpecs = taskSpec.getOutputs(); this.outputs = createOutputs(outputSpecs); this.processorDescriptor = taskSpec.getProcessorDescriptor(); this.processor = createProcessor(processorDescriptor); this.serviceConsumerMetadata = new HashMap<String, ByteBuffer>(); this.serviceConsumerMetadata.put(ShuffleUtils.SHUFFLE_HANDLER_SERVICE_ID, ShuffleUtils.convertJobTokenToBytes(jobToken)); this.state = State.NEW; } public void initialize() throws Exception { Preconditions.checkState(this.state == State.NEW, "Already initialized"); this.state = State.INITED; inputMap = new LinkedHashMap<String, LogicalInput>(inputs.size()); outputMap = new LinkedHashMap<String, LogicalOutput>(outputs.size()); // TODO Maybe close initialized inputs / outputs in case of failure to // initialize. // Initialize all inputs. TODO: Multi-threaded at some point. for (int i = 0; i < inputs.size(); i++) { String srcVertexName = inputSpecs.get(i).getSourceVertexName(); initializeInput(inputs.get(i), inputSpecs.get(i)); inputMap.put(srcVertexName, inputs.get(i)); } // Initialize all outputs. TODO: Multi-threaded at some point. for (int i = 0; i < outputs.size(); i++) { String destVertexName = outputSpecs.get(i).getDestinationVertexName(); initializeOutput(outputs.get(i), outputSpecs.get(i)); outputMap.put(destVertexName, outputs.get(i)); } // Initialize processor. initializeLogicalIOProcessor(); } public void run() throws Exception { synchronized (this.state) { Preconditions.checkState(this.state == State.INITED, "Can only run while in INITED state. Current: " + this.state); this.state = State.RUNNING; } LogicalIOProcessor lioProcessor = (LogicalIOProcessor) processor; lioProcessor.run(inputMap, outputMap); } public void close() throws Exception { Preconditions.checkState(this.state == State.RUNNING, "Can only run while in RUNNING state. Current: " + this.state); this.state = State.CLOSED; // Close the Inputs. for (int i = 0; i < inputs.size(); i++) { String srcVertexName = inputSpecs.get(i).getSourceVertexName(); List<Event> closeInputEvents = inputs.get(i).close(); sendTaskGeneratedEvents(closeInputEvents, EventProducerConsumerType.INPUT, taskSpec.getVertexName(), srcVertexName, taskSpec.getTaskAttemptID()); } // Close the Processor. processor.close(); // Close the Outputs. for (int i = 0; i < outputs.size(); i++) { String destVertexName = outputSpecs.get(i).getDestinationVertexName(); List<Event> closeOutputEvents = outputs.get(i).close(); sendTaskGeneratedEvents(closeOutputEvents, EventProducerConsumerType.OUTPUT, taskSpec.getVertexName(), destVertexName, taskSpec.getTaskAttemptID()); } } private void initializeInput(Input input, InputSpec inputSpec) throws Exception { TezInputContext tezInputContext = createInputContext(inputSpec); if (input instanceof LogicalInput) { ((LogicalInput) input).setNumPhysicalInputs(inputSpec .getPhysicalEdgeCount()); } List<Event> events = input.initialize(tezInputContext); sendTaskGeneratedEvents(events, EventProducerConsumerType.INPUT, tezInputContext.getTaskVertexName(), tezInputContext.getSourceVertexName(), taskSpec.getTaskAttemptID()); } private void initializeOutput(Output output, OutputSpec outputSpec) throws Exception { TezOutputContext tezOutputContext = createOutputContext(outputSpec); if (output instanceof LogicalOutput) { ((LogicalOutput) output).setNumPhysicalOutputs(outputSpec .getPhysicalEdgeCount()); } List<Event> events = output.initialize(tezOutputContext); sendTaskGeneratedEvents(events, EventProducerConsumerType.OUTPUT, tezOutputContext.getTaskVertexName(), tezOutputContext.getDestinationVertexName(), taskSpec.getTaskAttemptID()); } private void initializeLogicalIOProcessor() throws Exception { TezProcessorContext processorContext = createProcessorContext(); processor.initialize(processorContext); } private TezInputContext createInputContext(InputSpec inputSpec) { TezInputContext inputContext = new TezInputContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), inputSpec.getSourceVertexName(), taskSpec.getTaskAttemptID(), tezCounters, inputSpec.getInputDescriptor().getUserPayload(), this, serviceConsumerMetadata); return inputContext; } private TezOutputContext createOutputContext(OutputSpec outputSpec) { TezOutputContext outputContext = new TezOutputContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), outputSpec.getDestinationVertexName(), taskSpec.getTaskAttemptID(), tezCounters, outputSpec.getOutputDescriptor().getUserPayload(), this, serviceConsumerMetadata); return outputContext; } private TezProcessorContext createProcessorContext() { TezProcessorContext processorContext = new TezProcessorContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), taskSpec.getTaskAttemptID(), tezCounters, processorDescriptor.getUserPayload(), this, serviceConsumerMetadata); return processorContext; } private List<LogicalInput> createInputs(List<InputSpec> inputSpecs) { List<LogicalInput> inputs = new ArrayList<LogicalInput>(inputSpecs.size()); for (InputSpec inputSpec : inputSpecs) { Input input = RuntimeUtils.createClazzInstance(inputSpec .getInputDescriptor().getClassName()); if (input instanceof LogicalInput) { inputs.add((LogicalInput) input); } else { throw new TezUncheckedException(input.getClass().getName() + " is not a sub-type of LogicalInput." + " Only LogicalInput sub-types supported by LogicalIOProcessor."); } } return inputs; } private List<LogicalOutput> createOutputs(List<OutputSpec> outputSpecs) { List<LogicalOutput> outputs = new ArrayList<LogicalOutput>( outputSpecs.size()); for (OutputSpec outputSpec : outputSpecs) { Output output = RuntimeUtils.createClazzInstance(outputSpec .getOutputDescriptor().getClassName()); if (output instanceof LogicalOutput) { outputs.add((LogicalOutput) output); } else { throw new TezUncheckedException(output.getClass().getName() + " is not a sub-type of LogicalOutput." + " Only LogicalOutput sub-types supported by LogicalIOProcessor."); } } return outputs; } private LogicalIOProcessor createProcessor( ProcessorDescriptor processorDescriptor) { Processor processor = RuntimeUtils.createClazzInstance(processorDescriptor .getClassName()); if (!(processor instanceof LogicalIOProcessor)) { throw new TezUncheckedException(processor.getClass().getName() + " is not a sub-type of LogicalIOProcessor." + " Only LogicalOutput sub-types supported by LogicalIOProcessor."); } return (LogicalIOProcessor) processor; } private void sendTaskGeneratedEvents(List<Event> events, EventProducerConsumerType generator, String taskVertexName, String edgeVertexName, TezTaskAttemptID taskAttemptID) { if (events != null && events.size() > 0) { EventMetaData eventMetaData = new EventMetaData(generator, taskVertexName, edgeVertexName, taskAttemptID); List<TezEvent> tezEvents = new ArrayList<TezEvent>(events.size()); for (Event e : events) { TezEvent te = new TezEvent(e, eventMetaData); tezEvents.add(te); } tezUmbilical.addEvents(tezEvents); } } public void handleEvent(TezEvent e) { switch (e.getDestinationInfo().getEventGenerator()) { case INPUT: LogicalInput input = inputMap.get( e.getDestinationInfo().getEdgeVertexName()); if (input != null) { input.handleEvents(Collections.singletonList(e.getEvent())); } else { throw new TezUncheckedException("Unhandled event for invalid target: " + e); } break; case OUTPUT: LogicalOutput output = outputMap.get( e.getDestinationInfo().getEdgeVertexName()); if (output != null) { output.handleEvents(Collections.singletonList(e.getEvent())); } else { throw new TezUncheckedException("Unhandled event for invalid target: " + e); } break; case PROCESSOR: processor.handleEvents(Collections.singletonList(e.getEvent())); break; case SYSTEM: LOG.warn("Trying to send a System event in a Task: " + e); break; } } }
tez-engine/src/main/java/org/apache/tez/engine/newruntime/LogicalIOProcessorRuntimeTask.java
/** * 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.tez.engine.newruntime; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.token.Token; import org.apache.tez.dag.api.ProcessorDescriptor; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.engine.common.security.JobTokenIdentifier; import org.apache.tez.engine.newapi.Event; import org.apache.tez.engine.newapi.Input; import org.apache.tez.engine.newapi.LogicalIOProcessor; import org.apache.tez.engine.newapi.LogicalInput; import org.apache.tez.engine.newapi.LogicalOutput; import org.apache.tez.engine.newapi.Output; import org.apache.tez.engine.newapi.Processor; import org.apache.tez.engine.newapi.TezInputContext; import org.apache.tez.engine.newapi.TezOutputContext; import org.apache.tez.engine.newapi.TezProcessorContext; import org.apache.tez.engine.newapi.impl.InputSpec; import org.apache.tez.engine.newapi.impl.OutputSpec; import org.apache.tez.engine.newapi.impl.TaskSpec; import org.apache.tez.engine.newapi.impl.TezEvent; import org.apache.tez.engine.newapi.impl.TezInputContextImpl; import org.apache.tez.engine.newapi.impl.TezOutputContextImpl; import org.apache.tez.engine.newapi.impl.TezProcessorContextImpl; import org.apache.tez.engine.newapi.impl.TezUmbilical; import org.apache.tez.engine.shuffle.common.ShuffleUtils; import com.google.common.base.Preconditions; @Private public class LogicalIOProcessorRuntimeTask extends RuntimeTask { private static final Log LOG = LogFactory .getLog(LogicalIOProcessorRuntimeTask.class); private final TaskSpec taskSpec; private final Configuration tezConf; private final TezUmbilical tezUmbilical; private final List<InputSpec> inputSpecs; private final List<LogicalInput> inputs; private final List<OutputSpec> outputSpecs; private final List<LogicalOutput> outputs; private final ProcessorDescriptor processorDescriptor; private final LogicalIOProcessor processor; private final Map<String, ByteBuffer> serviceConsumerMetadata; private Map<String, LogicalInput> inputMap; private Map<String, LogicalOutput> outputMap; private Map<String, List<Event>> initInputEventMap; private Map<String, List<Event>> initOutputEventMap; private Map<String, List<Event>> closeInputEventMap; private Map<String, List<Event>> closeOutputEventMap; public LogicalIOProcessorRuntimeTask(TaskSpec taskSpec, Configuration tezConf, TezUmbilical tezUmbilical, Token<JobTokenIdentifier> jobToken) throws IOException { // TODO Remove jobToken from here post TEZ-421 LOG.info("Initializing LogicalIOProcessorRuntimeTask with TaskSpec: " + taskSpec); this.taskSpec = taskSpec; this.tezConf = tezConf; this.tezUmbilical = tezUmbilical; this.inputSpecs = taskSpec.getInputs(); this.inputs = createInputs(inputSpecs); this.outputSpecs = taskSpec.getOutputs(); this.outputs = createOutputs(outputSpecs); this.processorDescriptor = taskSpec.getProcessorDescriptor(); this.processor = createProcessor(processorDescriptor); this.serviceConsumerMetadata = new HashMap<String, ByteBuffer>(); this.serviceConsumerMetadata.put(ShuffleUtils.SHUFFLE_HANDLER_SERVICE_ID, ShuffleUtils.convertJobTokenToBytes(jobToken)); this.state = State.NEW; } public void initialize() throws Exception { Preconditions.checkState(this.state == State.NEW, "Already initialized"); this.state = State.INITED; inputMap = new LinkedHashMap<String, LogicalInput>(inputs.size()); outputMap = new LinkedHashMap<String, LogicalOutput>(outputs.size()); initInputEventMap = new LinkedHashMap<String, List<Event>>(inputs.size()); initOutputEventMap = new LinkedHashMap<String, List<Event>>(outputs.size()); // TODO Maybe close initialized inputs / outputs in case of failure to // initialize. // Initialize all inputs. TODO: Multi-threaded at some point. for (int i = 0; i < inputs.size(); i++) { String srcVertexName = inputSpecs.get(i).getSourceVertexName(); List<Event> initInputEvents = initializeInput(inputs.get(i), inputSpecs.get(i)); // TODO Add null/event list checking here or in the actual executor. initInputEventMap.put(srcVertexName, initInputEvents); inputMap.put(srcVertexName, inputs.get(i)); } // Initialize all outputs. TODO: Multi-threaded at some point. for (int i = 0; i < outputs.size(); i++) { String destVertexName = outputSpecs.get(i).getDestinationVertexName(); List<Event> initOutputEvents = initializeOutput(outputs.get(i), outputSpecs.get(i)); // TODO Add null/event list checking here or in the actual executor. initOutputEventMap.put(destVertexName, initOutputEvents); outputMap.put(destVertexName, outputs.get(i)); } // Initialize processor. initializeLogicalIOProcessor(); } public Map<String, List<Event>> getInputInitEvents() { Preconditions.checkState(this.state != State.NEW, "Not initialized yet"); return initInputEventMap; } public Map<String, List<Event>> getOutputInitEvents() { Preconditions.checkState(this.state != State.NEW, "Not initialized yet"); return initOutputEventMap; } public void run() throws Exception { synchronized (this.state) { Preconditions.checkState(this.state == State.INITED, "Can only run while in INITED state. Current: " + this.state); this.state = State.RUNNING; } LogicalIOProcessor lioProcessor = (LogicalIOProcessor) processor; lioProcessor.run(inputMap, outputMap); } public void close() throws Exception { Preconditions.checkState(this.state == State.RUNNING, "Can only run while in RUNNING state. Current: " + this.state); this.state=State.CLOSED; closeInputEventMap = new LinkedHashMap<String, List<Event>>(inputs.size()); closeOutputEventMap = new LinkedHashMap<String, List<Event>>(outputs.size()); // Close the Inputs. for (int i = 0; i < inputs.size(); i++) { String srcVertexName = inputSpecs.get(i).getSourceVertexName(); List<Event> closeInputEvents = inputs.get(i).close(); closeInputEventMap.put(srcVertexName, closeInputEvents); } // Close the Processor. processor.close(); // Close the Outputs. for (int i = 0; i < outputs.size(); i++) { String destVertexName = outputSpecs.get(i).getDestinationVertexName(); List<Event> closeOutputEvents = outputs.get(i).close(); closeOutputEventMap.put(destVertexName, closeOutputEvents); } } public Map<String, List<Event>> getInputCloseEvents() { Preconditions.checkState(this.state == State.CLOSED, "Not closed yet"); return closeInputEventMap; } public Map<String, List<Event>> getOutputCloseEvents() { Preconditions.checkState(this.state == State.CLOSED, "Not closed yet"); return closeOutputEventMap; } private List<Event> initializeInput(Input input, InputSpec inputSpec) throws Exception { TezInputContext tezInputContext = createInputContext(inputSpec); if (input instanceof LogicalInput) { ((LogicalInput) input).setNumPhysicalInputs(inputSpec .getPhysicalEdgeCount()); } return input.initialize(tezInputContext); } private List<Event> initializeOutput(Output output, OutputSpec outputSpec) throws Exception { TezOutputContext tezOutputContext = createOutputContext(outputSpec); if (output instanceof LogicalOutput) { ((LogicalOutput) output).setNumPhysicalOutputs(outputSpec .getPhysicalEdgeCount()); } return output.initialize(tezOutputContext); } private void initializeLogicalIOProcessor() throws Exception { TezProcessorContext processorContext = createProcessorContext(); processor.initialize(processorContext); } private TezInputContext createInputContext(InputSpec inputSpec) { TezInputContext inputContext = new TezInputContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), inputSpec.getSourceVertexName(), taskSpec.getTaskAttemptID(), tezCounters, inputSpec.getInputDescriptor().getUserPayload(), this, serviceConsumerMetadata); return inputContext; } private TezOutputContext createOutputContext(OutputSpec outputSpec) { TezOutputContext outputContext = new TezOutputContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), outputSpec.getDestinationVertexName(), taskSpec.getTaskAttemptID(), tezCounters, outputSpec.getOutputDescriptor().getUserPayload(), this, serviceConsumerMetadata); return outputContext; } private TezProcessorContext createProcessorContext() { TezProcessorContext processorContext = new TezProcessorContextImpl(tezConf, tezUmbilical, taskSpec.getVertexName(), taskSpec.getTaskAttemptID(), tezCounters, processorDescriptor.getUserPayload(), this, serviceConsumerMetadata); return processorContext; } private List<LogicalInput> createInputs(List<InputSpec> inputSpecs) { List<LogicalInput> inputs = new ArrayList<LogicalInput>(inputSpecs.size()); for (InputSpec inputSpec : inputSpecs) { Input input = RuntimeUtils.createClazzInstance(inputSpec .getInputDescriptor().getClassName()); if (input instanceof LogicalInput) { inputs.add((LogicalInput) input); } else { throw new TezUncheckedException(input.getClass().getName() + " is not a sub-type of LogicalInput." + " Only LogicalInput sub-types supported by LogicalIOProcessor."); } } return inputs; } private List<LogicalOutput> createOutputs(List<OutputSpec> outputSpecs) { List<LogicalOutput> outputs = new ArrayList<LogicalOutput>( outputSpecs.size()); for (OutputSpec outputSpec : outputSpecs) { Output output = RuntimeUtils.createClazzInstance(outputSpec .getOutputDescriptor().getClassName()); if (output instanceof LogicalOutput) { outputs.add((LogicalOutput) output); } else { throw new TezUncheckedException(output.getClass().getName() + " is not a sub-type of LogicalOutput." + " Only LogicalOutput sub-types supported by LogicalIOProcessor."); } } return outputs; } private LogicalIOProcessor createProcessor( ProcessorDescriptor processorDescriptor) { Processor processor = RuntimeUtils.createClazzInstance(processorDescriptor .getClassName()); if (!(processor instanceof LogicalIOProcessor)) { throw new TezUncheckedException(processor.getClass().getName() + " is not a sub-type of LogicalIOProcessor." + " Only LogicalOutput sub-types supported by LogicalIOProcessor."); } return (LogicalIOProcessor) processor; } public void handleEvent(TezEvent e) { switch (e.getDestinationInfo().getEventGenerator()) { case INPUT: LogicalInput input = inputMap.get( e.getDestinationInfo().getEdgeVertexName()); if (input != null) { input.handleEvents(Collections.singletonList(e.getEvent())); } else { throw new TezUncheckedException("Unhandled event for invalid target: " + e); } break; case OUTPUT: LogicalOutput output = outputMap.get( e.getDestinationInfo().getEdgeVertexName()); if (output != null) { output.handleEvents(Collections.singletonList(e.getEvent())); } else { throw new TezUncheckedException("Unhandled event for invalid target: " + e); } break; case PROCESSOR: processor.handleEvents(Collections.singletonList(e.getEvent())); break; case SYSTEM: LOG.warn("Trying to send a System event in a Task: " + e); break; } } }
TEZ-442. Handle events generated by I/O initialize and close (part of TEZ-398). (sseth)
tez-engine/src/main/java/org/apache/tez/engine/newruntime/LogicalIOProcessorRuntimeTask.java
TEZ-442. Handle events generated by I/O initialize and close (part of TEZ-398). (sseth)
Java
apache-2.0
9886e3d402c0c2acef6341888999ca2e4679ebb9
0
NerdCats/RoboCat
package co.gobd.gofetch.activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import co.gobd.gofetch.R; import co.gobd.gofetch.adapter.SupportedOrderAdapter; public class SupportedOrderActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_supported_order); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); RecyclerView rvSupportedOrder = (RecyclerView) findViewById(R.id.recycler_view_supported_order); rvSupportedOrder.setHasFixedSize(false); // Number of columns in the staggered grid view final int SPAN_COUNT = 2; GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT, GridLayoutManager.VERTICAL, false); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return (position % 3 == 0 ? 2 : 1); } }); rvSupportedOrder.setLayoutManager(layoutManager); SupportedOrderAdapter supportedOrderAdapter = new SupportedOrderAdapter(SupportedOrderActivity.this); rvSupportedOrder.setAdapter(supportedOrderAdapter); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
app/src/main/java/co/gobd/gofetch/activity/SupportedOrderActivity.java
package co.gobd.gofetch.activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import co.gobd.gofetch.R; import co.gobd.gofetch.adapter.SupportedOrderAdapter; import co.gobd.gofetch.mock.FakeServiceCall; public class SupportedOrderActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_supported_order); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); RecyclerView rvSupportedOrder = (RecyclerView) findViewById(R.id.recycler_view_supported_order); rvSupportedOrder.setHasFixedSize(false); // Number of columns in the staggered grid view final int SPAN_COUNT = 2; GridLayoutManager layoutManager = new GridLayoutManager(this, SPAN_COUNT, GridLayoutManager.VERTICAL, false); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return (position % 3 == 0 ? 2 : 1); } }); rvSupportedOrder.setLayoutManager(layoutManager); SupportedOrderAdapter supportedOrderAdapter = new SupportedOrderAdapter(SupportedOrderActivity.this); rvSupportedOrder.setAdapter(supportedOrderAdapter); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
GFETCH-72 Screen orientation change is handled in Activity#onConfigurationChanged() method. This solves the problem of recreating the activity and instances but causes some design issues. The app bar on protrait/landscaped mode is not properly showed, it keeps its previous state always. Need to fix this issue later but for now on, it's working.
app/src/main/java/co/gobd/gofetch/activity/SupportedOrderActivity.java
GFETCH-72 Screen orientation change is handled in Activity#onConfigurationChanged() method. This solves the problem of recreating the activity and instances but causes some design issues. The app bar on protrait/landscaped mode is not properly showed, it keeps its previous state always. Need to fix this issue later but for now on, it's working.
Java
apache-2.0
bd7b73664347e7b739149ce08caf6d71fffb91f1
0
chaoyi66/commons-lang,hollycroxton/commons-lang,byMan/naya279,PascalSchumacher/commons-lang,longestname1/commonslang,xuerenlv/commons-lang,jacktan1991/commons-lang,MuShiiii/commons-lang,MarkDacek/commons-lang,arbasha/commons-lang,vanta/commons-lang,chaoyi66/commons-lang,weston100721/commons-lang,xiwc/commons-lang,arbasha/commons-lang,xiwc/commons-lang,apache/commons-lang,MuShiiii/commons-lang,arbasha/commons-lang,mohanaraosv/commons-lang,apache/commons-lang,vanta/commons-lang,weston100721/commons-lang,jankill/commons-lang,PascalSchumacher/commons-lang,lovecindy/commons-lang,longestname1/commonslang,longestname1/commonslang,weston100721/commons-lang,Ajeet-Ganga/commons-lang,MuShiiii/commons-lang,Ajeet-Ganga/commons-lang,mohanaraosv/commons-lang,xuerenlv/commons-lang,MarkDacek/commons-lang,apache/commons-lang,suntengteng/commons-lang,byMan/naya279,chaoyi66/commons-lang,britter/commons-lang,jacktan1991/commons-lang,byMan/naya279,xiwc/commons-lang,jankill/commons-lang,lovecindy/commons-lang,hollycroxton/commons-lang,suntengteng/commons-lang,suntengteng/commons-lang,jacktan1991/commons-lang,britter/commons-lang,britter/commons-lang,MarkDacek/commons-lang,vanta/commons-lang,mohanaraosv/commons-lang,PascalSchumacher/commons-lang,Ajeet-Ganga/commons-lang,hollycroxton/commons-lang,xuerenlv/commons-lang,lovecindy/commons-lang,jankill/commons-lang
/* * 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.commons.lang3.text.translate; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.EnumSet; /** * Translates escaped unicode values of the form \\u+\d\d\d\d back to * unicode. * * @author Apache Software Foundation * @since 3.0 * @version $Id$ */ public class UnicodeUnescaper extends CharSequenceTranslator { public static enum OPTION { escapePlus } // TODO?: Create an OptionsSet class to hide some of the conditional logic below private final EnumSet<OPTION> options; /** * Create a UnicodeUnescaper. * * The constructor takes a list of options, only one of which is currently * available (whether to expect a plus sign after the 'u'). * * For example, to handle "\\u+0047": * new UnicodeUnescaper(UnicodeUnescaper.OPTION.escapePlus) * * @param options to apply to this unescaper */ public UnicodeUnescaper(OPTION... options) { if(options.length > 0) { this.options = EnumSet.copyOf(Arrays.asList(options)); } } /** * Whether the passed in option is currently set. * * @param option to check state of * @return whether the option is set */ public boolean isSet(OPTION option) { return (options == null) ? false : options.contains(option); } /** * {@inheritDoc} */ @Override public int translate(CharSequence input, int index, Writer out) throws IOException { if(input.charAt(index) == '\\') { if( (index + 1 < input.length()) && input.charAt(index + 1) == 'u') { // consume optional additional 'u' chars int i=2; while( (index + i < input.length()) && input.charAt(index + i) == 'u') { i++; } // consume + symbol in \\u+0045 if(isSet(OPTION.escapePlus)) { if( (index + i < input.length()) && (input.charAt(index + i) == '+') ) { i++; } } if( (index + i + 4 <= input.length()) ) { // Get 4 hex digits CharSequence unicode = input.subSequence(index + i, index + i + 4); try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe); } return i + 4; } else { throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '" + input.subSequence(index, input.length()) + "' due to end of CharSequence"); } } } return 0; } }
src/main/java/org/apache/commons/lang3/text/translate/UnicodeUnescaper.java
/* * 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.commons.lang3.text.translate; import java.io.IOException; import java.io.Writer; import java.util.Arrays; import java.util.EnumSet; /** * Translates escaped unicode values of the form \\u+\d\d\d\d back to * unicode. * * @author Apache Software Foundation * @since 3.0 * @version $Id$ */ public class UnicodeUnescaper extends CharSequenceTranslator { public static enum OPTION { escapePlus } // TODO?: Create an OptionsSet class to hide some of the conditional logic below private final EnumSet<OPTION> options; /** * Create a UnicodeUnescaper. * * The constructor takes a list of options, only one of which is currently * available (whether to expect a plus sign after the 'u'). * * For example, to handle "\\u+0047": * new UnicodeUnescaper(UnicodeUnescaper.OPTION.escapePlus) * * @param options to apply to this unescaper */ public UnicodeUnescaper(OPTION... options) { if(options.length > 0) { this.options = EnumSet.copyOf(Arrays.asList(options)); } else { this.options = null; } } /** * Whether the passed in option is currently set. * * @param option to check state of * @return whether the option is set */ public boolean isSet(OPTION option) { return (options == null) ? false : options.contains(option); } /** * {@inheritDoc} */ @Override public int translate(CharSequence input, int index, Writer out) throws IOException { if(input.charAt(index) == '\\') { if( (index + 1 < input.length()) && input.charAt(index + 1) == 'u') { // consume optional additional 'u' chars int i=2; while( (index + i < input.length()) && input.charAt(index + i) == 'u') { i++; } // consume + symbol in \\u+0045 if(isSet(OPTION.escapePlus)) { if( (index + i < input.length()) && (input.charAt(index + i) == '+') ) { i++; } } if( (index + i + 4 <= input.length()) ) { // Get 4 hex digits CharSequence unicode = input.subSequence(index + i, index + i + 4); try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe); } return i + 4; } else { throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '" + input.subSequence(index, input.length()) + "' due to end of CharSequence"); } } } return 0; } }
Removed unnecessary lines (options are already null by default) git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@1065233 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/lang3/text/translate/UnicodeUnescaper.java
Removed unnecessary lines (options are already null by default)
Java
apache-2.0
47abda2a7d26629ef8428000c664af6f9487bc4c
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * * Copyright 2005-2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.stomp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import javax.jms.Connection; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @version $Revision$ */ public class StompSubscriptionRemoveTest extends TestCase { private static final Log log = LogFactory.getLog(StompSubscriptionRemoveTest.class); private Socket stompSocket; private ByteArrayOutputStream inputBuffer; /** * @param args * @throws Exception */ public void testRemoveSubscriber() throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(true); broker.addConnector("stomp://localhost:61613").setName("Stomp"); broker.addConnector("tcp://localhost:61616").setName("Default"); broker.start(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); Message message = session.createTextMessage("Testas"); for (int idx = 0; idx < 2000; ++idx) { producer.send(message); log.debug("Sending: " + idx); } producer.close(); // consumer.close(); session.close(); connection.close(); stompSocket = new Socket("localhost", 61613); inputBuffer = new ByteArrayOutputStream(); String connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "\n"; sendFrame(connect_frame); String f = receiveFrame(100000); String frame = "SUBSCRIBE\n" + "destination:/queue/" + getDestinationName() + "\n" + "ack:client\n\n"; sendFrame(frame); int messagesCount = 0; int count = 0; while (count < 2) { String receiveFrame = receiveFrame(10000); DataInput input = new DataInputStream(new ByteArrayInputStream(receiveFrame.getBytes())); String line; while (true) { line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } else { line = line.trim(); if (line.length() > 0) { break; } } } line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } String messageId = line.substring(line.indexOf(':') + 1); messageId = messageId.trim(); String ackmessage = "ACK\n" + "message-id:" + messageId + "\n\n"; sendFrame(ackmessage); log.debug(receiveFrame); //Thread.sleep(1000); ++messagesCount; ++count; } stompSocket.close(); stompSocket = new Socket("localhost", 61613); inputBuffer = new ByteArrayOutputStream(); connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "\n"; sendFrame(connect_frame); f = receiveFrame(5000); frame = "SUBSCRIBE\n" + "destination:/queue/" + getDestinationName() + "\n" + "ack:client\n\n"; sendFrame(frame); try { while (count != 2000) { String receiveFrame = receiveFrame(5000); DataInput input = new DataInputStream(new ByteArrayInputStream(receiveFrame.getBytes())); String line; while (true) { line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } else { line = line.trim(); if (line.length() > 0) { break; } } } line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } String messageId = line.substring(line.indexOf(':') + 1); messageId = messageId.trim(); String ackmessage = "ACK\n" + "message-id:" + messageId + "\n\n"; sendFrame(ackmessage); log.debug("Received: " + receiveFrame); //Thread.sleep(1000); ++messagesCount; ++count; } } catch (IOException ex) { ex.printStackTrace(); } stompSocket.close(); broker.stop(); log.info("Total messages received: " + messagesCount); assertTrue("Messages received after connection loss: " + messagesCount, messagesCount >= 2000); // The first ack messages has no chance complete, so we receiving more messages // Don't know how to list subscriptions for the broker. Currently you // can check using JMX console. You'll see // Subscription without any connections } public void sendFrame(String data) throws Exception { byte[] bytes = data.getBytes("UTF-8"); OutputStream outputStream = stompSocket.getOutputStream(); outputStream.write(bytes); outputStream.write(0); outputStream.flush(); } public String receiveFrame(long timeOut) throws Exception { stompSocket.setSoTimeout((int) timeOut); InputStream is = stompSocket.getInputStream(); int c = 0; for (;;) { c = is.read(); if (c < 0) { throw new IOException("socket closed."); } else if (c == 0) { c = is.read(); byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, "UTF-8"); } else { inputBuffer.write(c); } } } protected String getDestinationName() { return getClass().getName() + "." + getName(); } }
activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java
/** * * Copyright 2005-2006 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.stomp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import javax.jms.Connection; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @version $Revision$ */ public class StompSubscriptionRemoveTest extends TestCase { private static final Log log = LogFactory.getLog(StompSubscriptionRemoveTest.class); private Socket stompSocket; private ByteArrayOutputStream inputBuffer; /** * @param args * @throws Exception */ public void testRemoveSubscriber() throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(true); broker.addConnector("stomp://localhost:61613").setName("Stomp"); broker.addConnector("tcp://localhost:61616").setName("Default"); broker.start(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(new ActiveMQQueue(getDestinationName())); Message message = session.createTextMessage("Testas"); for (int idx = 0; idx < 2000; ++idx) { producer.send(message); log.debug("Sending: " + idx); } producer.close(); // consumer.close(); session.close(); connection.close(); stompSocket = new Socket("localhost", 61613); inputBuffer = new ByteArrayOutputStream(); String connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "\n" + Stomp.NULL; sendFrame(connect_frame); String f = receiveFrame(100000); String frame = "SUBSCRIBE\n" + "destination:/queue/" + getDestinationName() + "\n" + "ack:client\n\n" + Stomp.NULL; sendFrame(frame); int messagesCount = 0; int count = 0; while (count < 2) { String receiveFrame = receiveFrame(10000); DataInput input = new DataInputStream(new ByteArrayInputStream(receiveFrame.getBytes())); String line; while (true) { line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } else { line = line.trim(); if (line.length() > 0) { break; } } } line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } String messageId = line.substring(line.indexOf(':') + 1); messageId = messageId.trim(); String ackmessage = "ACK\n" + "message-id:" + messageId + "\n\n" + Stomp.NULL; sendFrame(ackmessage); log.debug(receiveFrame); //Thread.sleep(1000); ++messagesCount; ++count; } stompSocket.close(); Thread.sleep(10000); // for (int idx = 0; idx < 500; ++idx) { // producer.send(message); // log.debug("Sending: " +idx); // } stompSocket = new Socket("localhost", 61613); inputBuffer = new ByteArrayOutputStream(); connect_frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n" + "\n" + Stomp.NULL; sendFrame(connect_frame); f = receiveFrame(100000); frame = "SUBSCRIBE\n" + "destination:/queue/" + getDestinationName() + "\n" + "ack:client\n\n" + Stomp.NULL; sendFrame(frame); try { while (count != 2000) { String receiveFrame = receiveFrame(10000); DataInput input = new DataInputStream(new ByteArrayInputStream(receiveFrame.getBytes())); String line; while (true) { line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } else { line = line.trim(); if (line.length() > 0) { break; } } } line = input.readLine(); if (line == null) { throw new IOException("connection was closed"); } String messageId = line.substring(line.indexOf(':') + 1); messageId = messageId.trim(); String ackmessage = "ACK\n" + "message-id:" + messageId + "\n\n" + Stomp.NULL; sendFrame(ackmessage); log.debug("Received: " + receiveFrame); //Thread.sleep(1000); ++messagesCount; ++count; } } catch (IOException ex) { // timeout } stompSocket.close(); broker.stop(); log.info("Total messages received: " + messagesCount); assertTrue("Messages received after connection loss: " + messagesCount, messagesCount >= 2000); // The first ack messages has no chance complete, so we receiving more messages // Don't know how to list subscriptions for the broker. Currently you // can check using JMX console. You'll see // Subscription without any connections } public void sendFrame(String data) throws Exception { byte[] bytes = data.getBytes("UTF-8"); OutputStream outputStream = stompSocket.getOutputStream(); for (int i = 0; i < bytes.length; i++) { outputStream.write(bytes[i]); } outputStream.flush(); } public String receiveFrame(long timeOut) throws Exception { stompSocket.setSoTimeout((int) timeOut); InputStream is = stompSocket.getInputStream(); int c = 0; for (;;) { c = is.read(); if (c < 0) { throw new IOException("socket closed."); } else if (c == 0) { c = is.read(); byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, "UTF-8"); } else { inputBuffer.write(c); } } } protected String getDestinationName() { return getClass().getName() + "." + getName(); } }
Trying to get this to pass more reliably on linux git-svn-id: 7f3df76e74c7ad56904d6048df705810748eb1a6@418424 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java
Trying to get this to pass more reliably on linux