answer
stringlengths
17
10.2M
package info.nightscout.androidaps.plugins.pump.omnipod.comm; import org.joda.time.DateTime; import java.util.Collections; import java.util.List; import javax.inject.Inject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkCommunicationException; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.OmnipodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageSequenceNumberException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalResponseException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NonceOutOfSyncException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NonceResyncException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NotEnoughDataException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodFaultException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.PodReturnedErrorResponseException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodPacket; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.DeactivatePodCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.ErrorResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoFaultEvent; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse; import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; // TODO make singleton public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { @Inject public AAPSLogger aapsLogger; @Inject OmnipodPumpStatus omnipodPumpStatus; //@Inject OmnipodPumpPlugin omnipodPumpPlugin; //@Inject RileyLinkServiceData rileyLinkServiceData; //@Inject ServiceTaskExecutor serviceTaskExecutor; @Inject public OmnipodCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { super(injector, rfspy); omnipodPumpStatus.previousConnection = sp.getLong( RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); } // @Override // protected void configurePumpSpecificSettings() { @Override public boolean tryToConnectToDevice() { // TODO return false; } @Override public byte[] createPumpMessageContent(RLMessageType type) { return new byte[0]; } @Override public PumpStatus getPumpStatus() { return null; } @Override public boolean isDeviceReachable() { return false; } @Override public boolean hasTunning() { return false; } @Override public <E extends RLMessage> E createResponseMessage(byte[] payload, Class<E> clazz) { return (E) new OmnipodPacket(payload); } @Override public void setPumpDeviceState(PumpDeviceState pumpDeviceState) { this.omnipodPumpStatus.setPumpDeviceState(pumpDeviceState); } public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodStateManager podStateManager, MessageBlock command) { return sendCommand(responseClass, podStateManager, command, true); } public <T extends MessageBlock> T sendCommand(Class<T> responseClass, PodStateManager podStateManager, MessageBlock command, boolean automaticallyResyncNone) { OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), Collections.singletonList(command), podStateManager.getMessageNumber()); return exchangeMessages(responseClass, podStateManager, message, automaticallyResyncNone); } // Convenience method public <T> T executeAction(OmnipodAction<T> action) { return action.execute(this); } public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message) { return exchangeMessages(responseClass, podStateManager, message, true); } public <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, boolean automaticallyResyncNonce) { return exchangeMessages(responseClass, podStateManager, message, null, null, automaticallyResyncNonce); } public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { return exchangeMessages(responseClass, podStateManager, message, addressOverride, ackAddressOverride, true); } public synchronized <T extends MessageBlock> T exchangeMessages(Class<T> responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { aapsLogger.debug(LTag.PUMPCOMM, "Exchanging OmnipodMessage [responseClass={}, podStateManager={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}]: {}", responseClass.getSimpleName(), podStateManager, message, addressOverride, ackAddressOverride, automaticallyResyncNonce); for (int i = 0; 2 > i; i++) { if (podStateManager.isPaired() && message.isNonceResyncable()) { podStateManager.advanceToNextNonce(); } MessageBlock responseMessageBlock; try { responseMessageBlock = transportMessages(podStateManager, message, addressOverride, ackAddressOverride); } catch (Exception ex) { podStateManager.setLastFailedCommunication(DateTime.now()); throw ex; } aapsLogger.debug(LTag.PUMPCOMM, "Received response from the Pod [responseMessageBlock={}]", responseMessageBlock); if (responseMessageBlock instanceof StatusResponse) { podStateManager.updateFromStatusResponse((StatusResponse) responseMessageBlock); } if (responseClass.isInstance(responseMessageBlock)) { podStateManager.setLastSuccessfulCommunication(DateTime.now()); return (T) responseMessageBlock; } else { if (responseMessageBlock.getType() == MessageBlockType.ERROR_RESPONSE) { ErrorResponse error = (ErrorResponse) responseMessageBlock; if (error.getErrorResponseCode() == ErrorResponse.ERROR_RESPONSE_CODE_BAD_NONCE) { podStateManager.resyncNonce(error.getNonceSearchKey(), message.getSentNonce(), message.getSequenceNumber()); if (automaticallyResyncNonce) { message.resyncNonce(podStateManager.getCurrentNonce()); } else { podStateManager.setLastFailedCommunication(DateTime.now()); throw new NonceOutOfSyncException(); } } else { podStateManager.setLastFailedCommunication(DateTime.now()); throw new PodReturnedErrorResponseException(error); } } else if (responseMessageBlock.getType() == MessageBlockType.POD_INFO_RESPONSE && ((PodInfoResponse) responseMessageBlock).getSubType() == PodInfoType.FAULT_EVENT) { PodInfoFaultEvent faultEvent = ((PodInfoResponse) responseMessageBlock).getPodInfo(); podStateManager.setFaultEvent(faultEvent); podStateManager.setLastFailedCommunication(DateTime.now()); throw new PodFaultException(faultEvent); } else { podStateManager.setLastFailedCommunication(DateTime.now()); throw new IllegalResponseException(responseClass.getSimpleName(), responseMessageBlock.getType()); } } } podStateManager.setLastFailedCommunication(DateTime.now()); throw new NonceResyncException(); } private MessageBlock transportMessages(PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { int packetAddress = podStateManager.getAddress(); if (addressOverride != null) { packetAddress = addressOverride; } podStateManager.increaseMessageNumber(); boolean firstPacket = true; byte[] encodedMessage; // this does not work well with the deactivate pod command, we somehow either // receive an ACK instead of a normal response, or a partial response and a communication timeout if (message.isNonceResyncable() && !message.containsBlock(DeactivatePodCommand.class)) { OmnipodMessage paddedMessage = new OmnipodMessage(message); // If messages are nonce resyncable, we want do distinguish between certain and uncertain failures for verification purposes // However, some commands (e.g. cancel delivery) are single packet command by nature. When we get a timeout with a single packet, // we are unsure whether or not the command was received by the pod // However, if we send > 1 packet, we know that the command wasn't received if we never send the subsequent packets, // because the last packet contains the CRC. // So we pad the message with get status commands to make it > packet paddedMessage.padWithGetStatusCommands(PacketType.PDM.getMaxBodyLength()); // First packet is of type PDM encodedMessage = paddedMessage.getEncoded(); } else { encodedMessage = message.getEncoded(); } OmnipodPacket response = null; while (encodedMessage.length > 0) { PacketType packetType = firstPacket ? PacketType.PDM : PacketType.CON; OmnipodPacket packet = new OmnipodPacket(packetAddress, packetType, podStateManager.getPacketNumber(), encodedMessage); byte[] encodedMessageInPacket = packet.getEncodedMessage(); // getting the data remaining to be sent encodedMessage = ByteUtil.substring(encodedMessage, encodedMessageInPacket.length, encodedMessage.length - encodedMessageInPacket.length); firstPacket = false; try { // We actually ignore previous (ack) responses if it was not last packet to send response = exchangePackets(podStateManager, packet); } catch (Exception ex) { OmnipodException newException; if (ex instanceof OmnipodException) { newException = (OmnipodException) ex; } else { newException = new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); } boolean lastPacket = encodedMessage.length == 0; // If this is not the last packet, the message wasn't fully sent, // so it's impossible for the pod to have received the message newException.setCertainFailure(!lastPacket); aapsLogger.debug(LTag.PUMPCOMM, "Caught exception in transportMessages. Set certainFailure to {} because encodedMessage.length={}", newException.isCertainFailure(), encodedMessage.length); throw newException; } } if (response.getPacketType() == PacketType.ACK) { throw new IllegalPacketTypeException(null, PacketType.ACK); } OmnipodMessage receivedMessage = null; byte[] receivedMessageData = response.getEncodedMessage(); while (receivedMessage == null) { try { receivedMessage = OmnipodMessage.decodeMessage(receivedMessageData); if (receivedMessage.getAddress() != message.getAddress()) { throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress()); } if (receivedMessage.getSequenceNumber() != podStateManager.getMessageNumber()) { throw new IllegalMessageSequenceNumberException(podStateManager.getMessageNumber(), receivedMessage.getSequenceNumber()); } } catch (NotEnoughDataException ex) { // Message is (probably) not complete yet OmnipodPacket ackForCon = createAckPacket(podStateManager, packetAddress, ackAddressOverride); try { OmnipodPacket conPacket = exchangePackets(podStateManager, ackForCon, 3, 40); if (conPacket.getPacketType() != PacketType.CON) { throw new IllegalPacketTypeException(PacketType.CON, conPacket.getPacketType()); } receivedMessageData = ByteUtil.concat(receivedMessageData, conPacket.getEncodedMessage()); } catch (OmnipodException ex2) { throw ex2; } catch (Exception ex2) { throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex2); } } } ackUntilQuiet(podStateManager, packetAddress, ackAddressOverride); List<MessageBlock> messageBlocks = receivedMessage.getMessageBlocks(); if (messageBlocks.size() == 0) { throw new NotEnoughDataException(receivedMessageData); } else if (messageBlocks.size() > 1) { // BS: don't expect this to happen aapsLogger.error(LTag.PUMPBTCOMM, "Received more than one message block: {}", messageBlocks.toString()); } MessageBlock messageBlock = messageBlocks.get(0); if (messageBlock.getType() != MessageBlockType.ERROR_RESPONSE) { podStateManager.increaseMessageNumber(); } return messageBlock; } private OmnipodPacket createAckPacket(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { if (packetAddress == null) { packetAddress = podStateManager.getAddress(); } if (messageAddress == null) { messageAddress = podStateManager.getAddress(); } return new OmnipodPacket(packetAddress, PacketType.ACK, podStateManager.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress)); } private void ackUntilQuiet(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { OmnipodPacket ack = createAckPacket(podStateManager, packetAddress, messageAddress); boolean quiet = false; while (!quiet) try { sendAndListen(ack, 300, 1, 0, 40, OmnipodPacket.class); } catch (RileyLinkCommunicationException ex) { if (RileyLinkBLEError.Timeout.equals(ex.getErrorCode())) { quiet = true; } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in ackUntilQuiet", ex); } } catch (OmnipodException ex) { aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in ackUntilQuiet", ex); } catch (Exception ex) { throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); } podStateManager.increasePacketNumber(); } private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet) { return exchangePackets(podStateManager, packet, 0, 333, 9000, 127); } private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) { return exchangePackets(podStateManager, packet, repeatCount, 333, 9000, preambleExtensionMilliseconds); } private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) { long timeoutTime = System.currentTimeMillis() + exchangeTimeoutMilliseconds; podStateManager.increasePacketNumber(); while (System.currentTimeMillis() < timeoutTime) { OmnipodPacket response = null; try { response = sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds, OmnipodPacket.class); } catch (RileyLinkCommunicationException | OmnipodException ex) { aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in exchangePackets: " + ex.getClass().getSimpleName() + ": " + ex.getMessage()); continue; } catch (Exception ex) { throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); } if (response == null) { aapsLogger.debug(LTag.PUMPBTCOMM, "exchangePackets response is null"); continue; } else if (!response.isValid()) { aapsLogger.debug(LTag.PUMPBTCOMM, "exchangePackets response is invalid: " + response); continue; } if (response.getAddress() != packet.getAddress() && response.getAddress() != OmnipodConst.DEFAULT_ADDRESS) { // In some (strange) cases, the Pod remains a packet address of 0xffffffff during it's lifetime aapsLogger.debug(LTag.PUMPBTCOMM, "Packet address " + response.getAddress() + " doesn't match " + packet.getAddress()); continue; } if (response.getSequenceNumber() != podStateManager.getPacketNumber()) { aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podStateManager.getPacketNumber()); continue; } // Once we have verification that the POD heard us, we can increment our counters podStateManager.increasePacketNumber(); return response; } throw new CommunicationException(CommunicationException.Type.TIMEOUT); } }
package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationService; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.BeepConfigCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.CancelDeliveryCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.defs.BeepConfigType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; import info.nightscout.androidaps.plugins.pump.omnipod.exception.ActionInitializationException; public class CancelDeliveryAction implements OmnipodAction<StatusResponse> { private final PodSessionState podState; private final EnumSet<DeliveryType> deliveryTypes; private final boolean acknowledgementBeep; public CancelDeliveryAction(PodSessionState podState, EnumSet<DeliveryType> deliveryTypes, boolean acknowledgementBeep) { if (podState == null) { throw new ActionInitializationException("Pod state cannot be null"); } if (deliveryTypes == null) { throw new ActionInitializationException("Delivery types cannot be null"); } this.podState = podState; this.deliveryTypes = deliveryTypes; this.acknowledgementBeep = acknowledgementBeep; } @Override public StatusResponse execute(OmnipodCommunicationService communicationService) { List<MessageBlock> messageBlocks = new ArrayList<>(); messageBlocks.add(new CancelDeliveryCommand(podState.getCurrentNonce(), acknowledgementBeep && deliveryTypes.size() == 1 ? BeepType.BEEP : BeepType.NO_BEEP, deliveryTypes)); if (acknowledgementBeep && deliveryTypes.size() > 1) { // Workaround for strange beep behaviour when cancelling multiple delivery types at the same time // FIXME we should use other constructor with all beep configs. // Theoretically, if we would cancel multiple delivery types but not all, // we should keep the beep config for delivery types that we're not cancelling. // We currently have no use case that though, // as we either cancel 1 type or all types, messageBlocks.add(new BeepConfigCommand(BeepConfigType.BEEP)); } return communicationService.exchangeMessages(StatusResponse.class, podState, new OmnipodMessage(podState.getAddress(), messageBlocks, podState.getMessageNumber())); } }
package de.ptb.epics.eve.editor.views.chainview; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.gef.EditPart; import org.eclipse.jface.databinding.swt.ISWTObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.ExpandBar; import org.eclipse.swt.widgets.ExpandItem; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import de.ptb.epics.eve.data.EventImpacts; import de.ptb.epics.eve.data.PluginTypes; import de.ptb.epics.eve.data.measuringstation.PlugIn; import de.ptb.epics.eve.data.measuringstation.PluginParameter; import de.ptb.epics.eve.data.scandescription.Chain; import de.ptb.epics.eve.data.scandescription.ControlEvent; import de.ptb.epics.eve.data.scandescription.ScanModule; import de.ptb.epics.eve.data.scandescription.errors.ChainError; import de.ptb.epics.eve.data.scandescription.errors.ChainErrorTypes; import de.ptb.epics.eve.data.scandescription.errors.IModelError; import de.ptb.epics.eve.data.scandescription.updatenotification.ControlEventTypes; import de.ptb.epics.eve.data.scandescription.updatenotification.IModelUpdateListener; import de.ptb.epics.eve.data.scandescription.updatenotification.ModelUpdateEvent; import de.ptb.epics.eve.editor.Activator; import de.ptb.epics.eve.editor.dialogs.PluginControllerDialog; import de.ptb.epics.eve.editor.gef.editparts.ChainEditPart; import de.ptb.epics.eve.editor.gef.editparts.ScanDescriptionEditPart; import de.ptb.epics.eve.editor.gef.editparts.ScanModuleEditPart; import de.ptb.epics.eve.editor.gef.editparts.StartEventEditPart; import de.ptb.epics.eve.editor.gef.editparts.tree.ScanModuleTreeEditPart; import de.ptb.epics.eve.editor.views.EditorViewPerspectiveListener; import de.ptb.epics.eve.editor.views.IEditorView; import de.ptb.epics.eve.editor.views.eventcomposite.EventComposite; import de.ptb.epics.eve.util.jface.SelectionProviderWrapper; /** * @author Marcus Michalsky * @since 1.12 */ public class ChainView extends ViewPart implements IEditorView, ISelectionListener, IModelUpdateListener { /** the unique identifier of the view */ public static final String ID = "de.ptb.epics.eve.editor.views.ChainView"; // logging private static Logger logger = Logger.getLogger(ChainView.class.getName()); private Chain currentChain; // the utmost composite (which contains all elements) private Composite top; private ExpandBar bar; // (1st) Save Options Expand Item & contained composite private ExpandItem saveOptionsExpandItem; private Composite saveOptionsComposite; // (2nd) Comment Expand Item & contained composite private ExpandItem commentExpandItem; private Composite commentComposite; // (3rd) Events Expand Item & contained Composite private ExpandItem eventsExpandItem; private Composite eventsComposite; private Label fileFormatLabel; private Combo fileFormatCombo; private ControlDecoration fileFormatComboControlDecoration; private FileFormatComboSelectionListener fileFormatComboSelectionListener; private Button fileFormatOptionsButton; private FileFormatOptionsButtonSelectionListener fileFormatOptionsButtonSelectionListener; private Label filenameLabel; private Text filenameInput; private ControlDecoration fileNameInputControlDecoration; private FileNameInputModifiedListener fileNameInputModifiedListener; private Button filenameBrowseButton; private Button saveScanDescriptionCheckBox; private Button confirmSaveCheckBox; private Button autoIncrementCheckBox; private Text commentInput; public CTabFolder eventsTabFolder; private CTabItem pauseTabItem; private EventComposite pauseEventComposite; private CTabItem redoTabItem; private EventComposite redoEventComposite; private CTabItem breakTabItem; private EventComposite breakEventComposite; private CTabItem stopTabItem; private EventComposite stopEventComposite; private Image warnImage; private Image errorImage; private Image eventErrorImage; private DataBindingContext context; private ISelectionProvider selectionProvider; private IObservableValue selectionObservable; private IObservableValue saveScanDescriptionTargetObservable; private IObservableValue saveScanDescriptionModelObservable; private IObservableValue confirmSaveTargetObservable; private IObservableValue confirmSaveModelObservable; private IObservableValue autoIncrementTargetObservable; private IObservableValue autoIncrementModelObservable; private IObservableValue commentTargetObservable; private IObservableValue commentTargetDelayedObservable; private IObservableValue commentModelObservable; // Delegates private EditorViewPerspectiveListener perspectiveListener; private SelectionProviderWrapper selectionProviderWrapper; /** * {@inheritDoc} */ @Override public void createPartControl(Composite parent) { logger.debug("createPartControl"); parent.setLayout(new FillLayout()); // if no measuring station is loaded -> show error and do nothing if (Activator.getDefault().getMeasuringStation() == null) { final Label errorLabel = new Label(parent, SWT.NONE); errorLabel.setText("No Measuring Station has been loaded. " + "Please check Preferences!"); return; } this.warnImage = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_WARNING) .getImage(); this.errorImage = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR) .getImage(); this.eventErrorImage = PlatformUI.getWorkbench().getSharedImages() .getImage(ISharedImages.IMG_OBJS_ERROR_TSK); // top composite this.top = new Composite(parent, SWT.NONE); this.top.setLayout(new GridLayout()); // expand bar for Save Options, Comment & Events this.bar = new ExpandBar(this.top, SWT.V_SCROLL); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.grabExcessVerticalSpace = true; gridData.horizontalAlignment = GridData.FILL; gridData.verticalAlignment = GridData.FILL; this.bar.setLayoutData(gridData); // save composite gets a 3 column grid this.saveOptionsComposite = new Composite(this.bar, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; gridLayout.horizontalSpacing = 12; this.saveOptionsComposite.setLayout(gridLayout); // GUI: "File Format: <Combo Box>" this.fileFormatLabel = new Label(this.saveOptionsComposite, SWT.NONE); this.fileFormatLabel.setText("File Format:"); this.fileFormatCombo = new Combo(this.saveOptionsComposite, SWT.READ_ONLY); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; this.fileFormatCombo.setLayoutData(gridData); // insert all available SAVE plug ins in the combo box List<String> pluginNames = new ArrayList<String>(); PlugIn[] plugins = Activator.getDefault().getMeasuringStation() .getPlugins().toArray(new PlugIn[0]); for (int i = 0; i < plugins.length; ++i) { if (plugins[i].getType() == PluginTypes.SAVE) { pluginNames.add(plugins[i].getName()); } } this.fileFormatCombo.setItems(pluginNames.toArray(new String[0])); this.fileFormatComboControlDecoration = new ControlDecoration( fileFormatCombo, SWT.LEFT); this.fileFormatComboControlDecoration.setImage(errorImage); this.fileFormatComboControlDecoration .setDescriptionText("The File Format is mandatory!"); this.fileFormatComboControlDecoration.hide(); fileFormatComboSelectionListener = new FileFormatComboSelectionListener(); this.fileFormatCombo .addSelectionListener(fileFormatComboSelectionListener); // Save Plug in Options button this.fileFormatOptionsButton = new Button(this.saveOptionsComposite, SWT.NONE); this.fileFormatOptionsButton.setText("Options"); gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.verticalAlignment = GridData.CENTER; this.fileFormatOptionsButton.setLayoutData(gridData); fileFormatOptionsButtonSelectionListener = new FileFormatOptionsButtonSelectionListener(); this.fileFormatOptionsButton .addSelectionListener(fileFormatOptionsButtonSelectionListener); // end of: GUI: "File Format: <Combo Box>" // GUI: "Filename: <Textfield>" this.filenameLabel = new Label(this.saveOptionsComposite, SWT.NONE); this.filenameLabel.setText("Filename:"); this.filenameInput = new Text(this.saveOptionsComposite, SWT.BORDER); String tooltip = "The file name where the data should be saved.\n " + "The following macros can be used:\n" + "${WEEK} : calendar week\n" + "${YEAR} : year as yyyy\n" + "${MONTH} : month as MM\n" + "${MONTHSTR} : month as MMM (e.g., Jul)\n" + "${DAY} : day as dd\n" + "${DAYSTR} : day as EEE (e.g., Mon)\n" + "${DATE} : date as yyyyMMdd (e.g., 20111231)\n" + "${DATE-} : date as yyyy-MM-dd (e.g., 2011-12-31)\n" + "${TIME} : time as HHmmss\n" + "${TIME-} : time as HH-mm-ss\n" + "${PV:<pvname>} : replace with value of pvname"; this.filenameInput.setToolTipText(tooltip); gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.verticalAlignment = GridData.CENTER; gridData.horizontalAlignment = GridData.FILL; this.filenameInput.setLayoutData(gridData); this.fileNameInputControlDecoration = new ControlDecoration( filenameInput, SWT.LEFT); this.fileNameInputControlDecoration.setImage(errorImage); this.fileNameInputControlDecoration.hide(); fileNameInputModifiedListener = new FileNameInputModifiedListener(); this.filenameInput.addModifyListener(fileNameInputModifiedListener); // Browse Button this.filenameBrowseButton = new Button(this.saveOptionsComposite, SWT.NONE); this.filenameBrowseButton.setText("Browse..."); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.verticalAlignment = GridData.CENTER; this.filenameBrowseButton.setLayoutData(gridData); this.filenameBrowseButton .addMouseListener(new SearchButtonMouseListener()); // Save Scan Description check box this.saveScanDescriptionCheckBox = new Button( this.saveOptionsComposite, SWT.CHECK); this.saveScanDescriptionCheckBox.setText("Save Scan-Description"); this.saveScanDescriptionCheckBox .setToolTipText("Check to save the scan description into the datafile."); gridData = new GridData(); gridData.horizontalSpan = 4; this.saveScanDescriptionCheckBox.setLayoutData(gridData); // Confirm Save check box this.confirmSaveCheckBox = new Button(this.saveOptionsComposite, SWT.CHECK); this.confirmSaveCheckBox.setText("Confirm Save"); this.confirmSaveCheckBox .setToolTipText("Check if saving the datafile should be confirmed"); gridData = new GridData(); gridData.horizontalSpan = 4; this.confirmSaveCheckBox.setLayoutData(gridData); // Add auto incrementing Number to Filename check box this.autoIncrementCheckBox = new Button(this.saveOptionsComposite, SWT.CHECK); this.autoIncrementCheckBox .setText("Add Autoincrementing Number to Filename"); gridData = new GridData(); gridData.horizontalSpan = 4; this.autoIncrementCheckBox.setLayoutData(gridData); // add expand item to the expander this.saveOptionsExpandItem = new ExpandItem(this.bar, SWT.NONE, 0); saveOptionsExpandItem.setText("Save Options"); saveOptionsExpandItem.setHeight(this.saveOptionsComposite.computeSize( SWT.DEFAULT, SWT.DEFAULT).y); saveOptionsExpandItem.setControl(this.saveOptionsComposite); this.saveOptionsExpandItem.setExpanded(true); this.commentComposite = new Composite(this.bar, SWT.NONE); FillLayout fillLayout = new FillLayout(); fillLayout.marginWidth = 5; this.commentComposite.setLayout(fillLayout); // Comment Input this.commentInput = new Text(this.commentComposite, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.V_SCROLL); // add comment expander to the expand bar this.commentExpandItem = new ExpandItem(this.bar, SWT.NONE, 0); commentExpandItem.setText("Comment"); commentExpandItem.setHeight(100); commentExpandItem.setControl(this.commentComposite); this.commentExpandItem.setExpanded(true); this.eventsComposite = new Composite(this.bar, SWT.NONE); fillLayout = new FillLayout(); fillLayout.marginWidth = 5; this.eventsComposite.setLayout(fillLayout); // events tab folder contains the tabs pause, redo, break & stop eventsTabFolder = new CTabFolder(this.eventsComposite, SWT.FLAT); this.eventsTabFolder.setSimple(true); this.eventsTabFolder.setBorderVisible(true); eventsTabFolder .addSelectionListener(new EventsTabFolderSelectionListener()); pauseEventComposite = new EventComposite(eventsTabFolder, SWT.NONE, ControlEventTypes.PAUSE_EVENT, this); redoEventComposite = new EventComposite(eventsTabFolder, SWT.NONE, ControlEventTypes.CONTROL_EVENT, this); breakEventComposite = new EventComposite(eventsTabFolder, SWT.NONE, ControlEventTypes.CONTROL_EVENT, this); stopEventComposite = new EventComposite(eventsTabFolder, SWT.NONE, ControlEventTypes.CONTROL_EVENT, this); this.pauseTabItem = new CTabItem(eventsTabFolder, SWT.FLAT); this.pauseTabItem.setText(" Pause "); this.pauseTabItem.setControl(pauseEventComposite); this.pauseTabItem.setToolTipText("Event to pause an resume this scan"); this.redoTabItem = new CTabItem(eventsTabFolder, SWT.FLAT); this.redoTabItem.setText(" Redo "); this.redoTabItem.setControl(redoEventComposite); this.redoTabItem .setToolTipText("Repeat the current scan point, if redo event occurs"); this.breakTabItem = new CTabItem(eventsTabFolder, SWT.FLAT); this.breakTabItem.setText(" Skip "); this.breakTabItem.setControl(breakEventComposite); this.breakTabItem .setToolTipText("Finish the current scan module and continue with next"); this.stopTabItem = new CTabItem(eventsTabFolder, SWT.FLAT); this.stopTabItem.setText(" Stop "); this.stopTabItem.setControl(stopEventComposite); this.stopTabItem.setToolTipText("Stop this scan"); // add Events expander to the expand bar this.eventsExpandItem = new ExpandItem(this.bar, SWT.NONE, 0); this.eventsExpandItem.setText("Events"); this.eventsExpandItem.setHeight(this.eventsComposite.computeSize( SWT.DEFAULT, SWT.DEFAULT).y); this.eventsExpandItem.setControl(this.eventsComposite); this.eventsExpandItem.setExpanded(true); this.eventsTabFolder.showItem(this.pauseTabItem); top.setVisible(false); // the selection service only accepts one selection provider per view, // since we have four tables capable of providing selections a wrapper // handles them and registers the active one with the global selection // service selectionProviderWrapper = new SelectionProviderWrapper(); getSite().setSelectionProvider(selectionProviderWrapper); // listen to selection changes (if a chain (or one of its scan modules) // is selected, its attributes are made available for editing) getSite().getWorkbenchWindow().getSelectionService() .addSelectionListener(this); // listen to "last editor closed" to reset the view. perspectiveListener = new EditorViewPerspectiveListener(this); PlatformUI.getWorkbench().getActiveWorkbenchWindow() .addPerspectiveListener(perspectiveListener); this.bindValues(); } private void bindValues() { this.context = new DataBindingContext(); this.selectionProvider = new ChainSelectionProvider(); this.selectionObservable = ViewersObservables .observeSingleSelection(selectionProvider); this.saveScanDescriptionTargetObservable = SWTObservables .observeSelection(saveScanDescriptionCheckBox); this.saveScanDescriptionModelObservable = BeansObservables .observeDetailValue(selectionObservable, Chain.class, Chain.SAVE_SCAN_DESCRIPTION_PROP, Boolean.class); this.context.bindValue(saveScanDescriptionTargetObservable, saveScanDescriptionModelObservable, new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); this.confirmSaveTargetObservable = SWTObservables .observeSelection(confirmSaveCheckBox); this.confirmSaveModelObservable = BeansObservables.observeDetailValue( selectionObservable, Chain.class, Chain.CONFIRM_SAVE_PROP, Boolean.class); this.context.bindValue(confirmSaveTargetObservable, confirmSaveModelObservable, new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); this.autoIncrementTargetObservable = SWTObservables .observeSelection(autoIncrementCheckBox); this.autoIncrementModelObservable = BeansObservables .observeDetailValue(selectionObservable, Chain.class, Chain.AUTO_INCREMENT_PROP, Boolean.class); this.context.bindValue(autoIncrementTargetObservable, autoIncrementModelObservable, new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); this.commentTargetObservable = SWTObservables.observeText(commentInput, SWT.Modify); this.commentTargetDelayedObservable = SWTObservables .observeDelayedValue(1000, (ISWTObservableValue) this.commentTargetObservable); this.commentModelObservable = BeansObservables.observeDetailValue( selectionObservable, Chain.class, Chain.COMMENT_PROP, String.class); this.context.bindValue(commentTargetDelayedObservable, commentModelObservable, new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE)); } /** * {@inheritDoc} */ @Override public void setFocus() { logger.debug("Focus gained -> forward to top composite"); this.top.setFocus(); } /** * Sets the current {@link de.ptb.epics.eve.data.scandescription.Chain} (the * underlying model whose contents is presented by this view). * * @param currentChain * the {@link de.ptb.epics.eve.data.scandescription.Chain} that * should be set current. Use <code>null</code> to present an * empty view. */ private void setCurrentChain(final Chain currentChain) { logger.debug("setCurrentChain"); if (this.currentChain != null) { this.currentChain.removeModelUpdateListener(this); } // set the new chain as current chain this.currentChain = currentChain; if (this.currentChain != null) { this.currentChain.addModelUpdateListener(this); } updateEvent(null); } /** * {@inheritDoc} */ @Override public void reset() { this.setCurrentChain(null); } /** * * @return */ public Chain getCurrentChain() { return this.currentChain; } /* * called by setCurrentChain() to check for errors in user input and show * error decorators. */ private void checkForErrors() { // reset all this.fileFormatComboControlDecoration.hide(); this.fileNameInputControlDecoration.hide(); this.pauseTabItem.setImage(null); this.breakTabItem.setImage(null); this.redoTabItem.setImage(null); this.stopTabItem.setImage(null); if (this.currentChain.getSavePluginController().getModelErrors().size() > 0) { this.fileFormatComboControlDecoration.show(); this.fileFormatCombo.deselectAll(); } File file = new File(this.currentChain.getSaveFilename()); if (file.isFile() && file.exists()) { this.fileNameInputControlDecoration.setImage(warnImage); this.fileNameInputControlDecoration .setDescriptionText("File already exists!"); this.fileNameInputControlDecoration.show(); } file = null; for (IModelError error : this.currentChain.getModelErrors()) { if (error instanceof ChainError) { final ChainError chainError = (ChainError) error; this.fileNameInputControlDecoration.setImage(errorImage); this.fileNameInputControlDecoration.show(); if (chainError.getErrorType() == ChainErrorTypes.FILENAME_EMPTY) { this.fileNameInputControlDecoration .setDescriptionText("Filename must not be empty!"); } else if (chainError.getErrorType() == ChainErrorTypes.FILENAME_ILLEGAL_CHARACTER) { this.fileNameInputControlDecoration .setDescriptionText("Filename contains illegal characters!"); } } } for (ControlEvent event : this.currentChain.getPauseEvents()) { if (event.getModelErrors().size() > 0) { this.pauseTabItem.setImage(eventErrorImage); } } for (ControlEvent event : this.currentChain.getBreakEvents()) { if (event.getModelErrors().size() > 0) { this.breakTabItem.setImage(eventErrorImage); } } for (ControlEvent event : this.currentChain.getRedoEvents()) { if (event.getModelErrors().size() > 0) { this.redoTabItem.setImage(eventErrorImage); } } for (ControlEvent event : this.currentChain.getStopEvents()) { if (event.getModelErrors().size() > 0) { this.stopTabItem.setImage(eventErrorImage); } } } /** * {@inheritDoc} */ @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { logger.debug("selection changed"); if (selection instanceof IStructuredSelection) { if (((IStructuredSelection) selection).size() == 0) { return; } } // since at any given time this view can only display options of // one device we take the first element of the selection Object o = ((IStructuredSelection) selection).toList().get(0); if (o instanceof ScanModuleEditPart || o instanceof ScanModuleTreeEditPart) { // a scan module belongs to a chain -> show chain if (logger.isDebugEnabled()) { logger.debug("ScanModule " + ((ScanModule)((EditPart)o).getModel()) + " selected."); } setCurrentChain(((ScanModule)((EditPart)o).getModel()).getChain()); } else if (o instanceof StartEventEditPart) { // a start event belongs to a chain -> show chain if (logger.isDebugEnabled()) { logger.debug("Chain " + (((StartEventEditPart) o).getModel()).getChain() + " selected."); } setCurrentChain((((StartEventEditPart) o).getModel()).getChain()); } else if (o instanceof ChainEditPart) { logger.debug("selection is ScanDescriptionEditPart: " + o); setCurrentChain(null); } else if (o instanceof ScanDescriptionEditPart) { logger.debug("selection is ScanDescriptionEditPart: " + o); setCurrentChain(null); } else { logger.debug("selection other than Chain -> ignore: " + o); } } /** * * @param selectionProvider */ public void setSelectionProvider(ISelectionProvider selectionProvider) { this.selectionProviderWrapper.setSelectionProvider(selectionProvider); } /* * used by setCurrentChain() to re-enable listeners */ private void addListeners() { this.fileFormatCombo .addSelectionListener(fileFormatComboSelectionListener); this.filenameInput.addModifyListener(fileNameInputModifiedListener); } /* * used by setCurrentChain() to temporarily disable listeners */ private void removeListeners() { this.fileFormatCombo .removeSelectionListener(fileFormatComboSelectionListener); this.filenameInput.removeModifyListener(fileNameInputModifiedListener); } private void suspendModelUpdateListener() { this.currentChain.removeModelUpdateListener(this); } private void resumeModelUpdateListener() { this.currentChain.addModelUpdateListener(this); } /** * {@inheritDoc} */ @Override public void updateEvent(ModelUpdateEvent modelUpdateEvent) { removeListeners(); if (this.currentChain != null) { this.top.setVisible(true); if (this.eventsTabFolder.getSelection() == null) { this.eventsTabFolder.setSelection(this.pauseTabItem); } this.setPartName("Chain: " + this.currentChain.getId()); if (this.currentChain.getSavePluginController().getPlugin() != null) { this.fileFormatCombo.setText(this.currentChain .getSavePluginController().getPlugin().getName()); } if (this.currentChain.getSaveFilename() != null) { this.filenameInput.setText(this.currentChain.getSaveFilename()); this.filenameInput.setSelection(this.filenameInput.getText() .length()); } this.pauseEventComposite.setEvents(this.currentChain, EventImpacts.PAUSE); this.redoEventComposite.setEvents(this.currentChain, EventImpacts.REDO); this.breakEventComposite.setEvents(this.currentChain, EventImpacts.BREAK); this.stopEventComposite.setEvents(this.currentChain, EventImpacts.STOP); checkForErrors(); } else { // currentChain == null this.fileFormatCombo.deselectAll(); this.filenameInput.setText(""); this.pauseEventComposite.setEvents(this.currentChain, null); this.redoEventComposite.setEvents(this.currentChain, null); this.breakEventComposite.setEvents(this.currentChain, null); this.stopEventComposite.setEvents(this.currentChain, null); this.setPartName("No Chain selected"); this.top.setVisible(false); } addListeners(); } /** * {@link org.eclipse.swt.events.ModifyListener} of * <code>savePluginCombo</code>. */ private class FileFormatComboSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent e) { currentChain.getSavePluginController().setPlugin( Activator.getDefault().getMeasuringStation() .getPluginByName(fileFormatCombo.getText())); checkForErrors(); } } /** * {@link org.eclipse.swt.events.SelectionListener} of * <code>savePluginOptionsButton</code>. */ private class FileFormatOptionsButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent e) { PluginControllerDialog dialog = new PluginControllerDialog(null, currentChain.getSavePluginController()); dialog.setBlockOnOpen(true); dialog.open(); } } /** * {@link org.eclipse.swt.events.ModifyListener} of * <code>fileNameInput</code>. */ private class FileNameInputModifiedListener implements ModifyListener { /** * {@inheritDoc} */ @Override public void modifyText(ModifyEvent e) { suspendModelUpdateListener(); currentChain.setSaveFilename(filenameInput.getText().trim()); checkForErrors(); resumeModelUpdateListener(); } } /** * {@link org.eclipse.swt.events.MouseListener} of <code>searchButton</code> * . */ private class SearchButtonMouseListener implements MouseListener { /** * {@inheritDoc} */ @Override public void mouseDoubleClick(MouseEvent e) { } /** * {@inheritDoc}<br> * <br> * Opens a file dialog to choose the destination of the data file. */ @Override public void mouseDown(MouseEvent e) { int lastSeperatorIndex; final String filePath; if (currentChain.getSaveFilename() != null && !currentChain.getSaveFilename().isEmpty()) { // there already is a filename (and path) -> show the path lastSeperatorIndex = currentChain.getSaveFilename() .lastIndexOf(File.separatorChar); filePath = currentChain.getSaveFilename().substring(0, lastSeperatorIndex + 1); } else { // no filename -> set path to <rootDir>/daten/ or <rootDir> String rootdir = Activator.getDefault().getRootDirectory(); File file = new File(rootdir + "data/"); if (file.exists()) { filePath = rootdir + "data/"; } else { filePath = rootdir; } file = null; } logger.debug("FileDialog path: " + filePath); FileDialog fileWindow = new FileDialog(getSite().getShell(), SWT.SAVE); fileWindow.setFilterPath(filePath); String name = fileWindow.open(); if (name != null) { // try to get suffix parameter of the selected plug in final Iterator<PluginParameter> it = currentChain .getSavePluginController().getPlugin().getParameters() .iterator(); PluginParameter pluginParameter = null; while (it.hasNext()) { pluginParameter = it.next(); if (pluginParameter.getName().equals("suffix")) { break; } pluginParameter = null; } if (pluginParameter != null) { // suffix found -> replace String suffix = currentChain.getSavePluginController() .get("suffix").toString(); // remove old suffix final int lastPoint = name.lastIndexOf('.'); final int lastSep = name.lastIndexOf('/'); if ((lastPoint > 0) && (lastPoint > lastSep)) { filenameInput.setText(name.substring(0, lastPoint) + "." + suffix); } else { filenameInput.setText(name + "." + suffix); } } else { filenameInput.setText(name); } filenameInput.setSelection(filenameInput.getText().length()); } } /** * {@inheritDoc} */ @Override public void mouseUp(MouseEvent e) { } } /** * {@link org.eclipse.swt.events.SelectionListener} of * <code>eventsTabFolder</code>. * * @author Marcus Michalsky * @since 1.1 */ private class EventsTabFolderSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent e) { selectionProviderWrapper .setSelectionProvider(((EventComposite) eventsTabFolder .getSelection().getControl()).getTableViewer()); } } }
package fhscs.snake.impl; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import fhscs.snake.Game; @SuppressWarnings("serial") public class GameCanvas extends Canvas { private final Game game; private Color snakeColor = Color.GREEN; private Color appleColor = Color.RED; private static final int blockSize = 20; public GameCanvas(Game game) { this.game = game; } @Override public void paint(Graphics g) { drawSnake(g); drawApple(g); drawBoard(g); } /** * Draws the {@link Snake} */ private void drawSnake(Graphics g) { g.setColor(this.snakeColor); for (Point p : game.getSnake().getLocations()) { g.fillRect( (int)(blockSize*(p.getX()-1)), (int)(blockSize*(game.getBoard().getHeight() - p.getY())), (int)(blockSize*(p.getY())), (int)(blockSize*(game.getBoard().getHeight() - p.getY() + 1)) ); } } /** * Draws the Apple */ private void drawApple(Graphics g) { g.setColor(appleColor); g.fillRect(game.getApple().x + blockSize, game.getApple().y + blockSize, 2*blockSize, 2*blockSize); } /** * Draws the {@link Board} */ private void drawBoard(Graphics g) { } /** * Set the color of the snake. * @param c the color of the snake */ public void setSnakeColor(Color c) { this.snakeColor = c; } /** * Returns the color of the snake. * @return the color of the snake. */ public Color getSnakeColor() { return snakeColor; } /** * Returns the color of the apple. * @return the color of the apple */ public Color getAppleColor() { return appleColor; } /** * Set the color of the apple * @param appleColor the color of the apple */ public void setAppleColor(Color appleColor) { this.appleColor = appleColor; } }
package org.csstudio.scan.server.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import org.csstudio.scan.ScanSystemPreferences; import org.csstudio.scan.command.LoopCommand; import org.csstudio.scan.command.ScanCommand; import org.csstudio.scan.commandimpl.WaitForDevicesCommand; import org.csstudio.scan.commandimpl.WaitForDevicesCommandImpl; import org.csstudio.scan.data.ScanData; import org.csstudio.scan.data.ScanSampleFormatter; import org.csstudio.scan.device.Device; import org.csstudio.scan.device.DeviceContext; import org.csstudio.scan.device.DeviceContextHelper; import org.csstudio.scan.device.DeviceInfo; import org.csstudio.scan.log.DataLog; import org.csstudio.scan.log.DataLogFactory; import org.csstudio.scan.server.MacroContext; import org.csstudio.scan.server.MemoryInfo; import org.csstudio.scan.server.Scan; import org.csstudio.scan.server.ScanCommandImpl; import org.csstudio.scan.server.ScanCommandUtil; import org.csstudio.scan.server.ScanContext; import org.csstudio.scan.server.ScanInfo; import org.csstudio.scan.server.ScanState; import org.epics.util.time.TimeDuration; /** Scan that can be executed: Commands, device context, state * * <p>Combines a {@link DeviceContext} with {@link ScanContextImpl}ementations * and can execute them. * When a command is executed, it receives a {@link ScanContext} view * of the scan for limited access to the devices, data logger etc. * * @author Kay Kasemir */ @SuppressWarnings("nls") public class ExecutableScan extends LoggedScan implements ScanContext, Callable<Object> { /** Commands to execute */ final private transient List<ScanCommandImpl<?>> pre_scan, implementations, post_scan; /** Macros for resolving device names */ final private MacroContext macros; /** Devices used by the scan */ final protected DeviceContext devices; /** Log each device access, or require specific log command? */ private volatile boolean automatic_log_mode = false; /** Data logger, non-null while when executing the scan * SYNC on this for access */ private DataLog data_logger = null; /** Total number of commands to execute */ final private long total_work_units; /** Commands executed so far */ final protected AtomicLong work_performed = new AtomicLong(); /** State of this scan */ private AtomicReference<ScanState> state = new AtomicReference<>(ScanState.Idle); private volatile String error = null; /** Start time, set when execution starts */ private volatile long start_ms = 0; /** Actual or estimated end time */ private volatile long end_ms = 0; /** Last valid address * <p>The current_command may be within an IncludeCommand, * where addresses are no longer set. * This address tracks the most recent valid address. */ private volatile long current_address = -1; /** Currently executed command or <code>null</code> */ private volatile ScanCommandImpl<?> current_command = null; /** {@link Future} after scan has been submitted to {@link ExecutorService} */ private volatile Future<Object> future = null; /** Device Names for status PVs */ private String device_active = null, device_status = null, device_state = null, device_progress = null, device_finish = null; /** Timeout for updating the status PVs */ final private static TimeDuration timeout = TimeDuration.ofSeconds(10); /** Initialize * @param name User-provided name for this scan * @param devices {@link DeviceContext} to use for scan * @param implementations Commands to execute in this scan * @throws Exception on error (cannot access log, ...) */ public ExecutableScan(final String name, final DeviceContext devices, ScanCommandImpl<?>... implementations) throws Exception { this(name, devices, Collections.<ScanCommandImpl<?>>emptyList(), Arrays.asList(implementations), Collections.<ScanCommandImpl<?>>emptyList()); } /** Initialize * @param name User-provided name for this scan * @param devices {@link DeviceContext} to use for scan * @param pre_scan Commands to execute before the 'main' section of the scan * @param implementations Commands to execute in this scan * @param post_scan Commands to execute before the 'main' section of the scan * @throws Exception on error (cannot access log, ...) */ public ExecutableScan(final String name, final DeviceContext devices, final List<ScanCommandImpl<?>> pre_scan, final List<ScanCommandImpl<?>> implementations, final List<ScanCommandImpl<?>> post_scan) throws Exception { this(DataLogFactory.createDataLog(name), devices, pre_scan, implementations, post_scan); } /** Initialize * @param scan {@link Scan} * @param devices {@link DeviceContext} to use for scan * @param pre_scan Commands to execute before the 'main' section of the scan * @param implementations Commands to execute in this scan * @param post_scan Commands to execute before the 'main' section of the scan * @throws Exception on error (cannot access log, ...) */ public ExecutableScan(final Scan scan, final DeviceContext devices, final List<ScanCommandImpl<?>> pre_scan, final List<ScanCommandImpl<?>> implementations, final List<ScanCommandImpl<?>> post_scan) throws Exception { super(scan); this.macros = new MacroContext(ScanSystemPreferences.getMacros()); this.devices = devices; this.pre_scan = pre_scan; this.implementations = implementations; this.post_scan = post_scan; // Assign addresses to all commands, // determine work units long address = 0; long work_units = 0; for (ScanCommandImpl<?> impl : implementations) { address = impl.setAddress(address); work_units += impl.getWorkUnits(); } total_work_units = work_units; } public void submit(final ExecutorService executor) { if (future != null) throw new IllegalStateException("Already submitted for execution"); future = executor.submit(this); } /** @return {@link ScanState} */ @Override public ScanState getScanState() { return state.get(); } /** @return Info about current state of this scan */ @Override public ScanInfo getScanInfo() { final long address = current_address; final ScanCommandImpl<?> command = current_command; final String command_name; final ScanState state = getScanState(); final long runtime; final long performed_work_units; if (start_ms <= 0) { // Not started command_name = ""; runtime = 0; performed_work_units = 0; } else if (state.isDone()) { // Finished, aborted command_name = "- end -"; runtime = end_ms - start_ms; performed_work_units = total_work_units; } else { // Running command_name = command == null ? "" : command.toString(); final long now = System.currentTimeMillis(); runtime = now - start_ms; performed_work_units = work_performed.get(); // Estimate end time final long finish_estimate = performed_work_units <= 0 ? now : start_ms + runtime*total_work_units/performed_work_units; // Somewhat smoothly update end time w/ estimate if (end_ms <= 0) end_ms = finish_estimate; else end_ms = 4*(end_ms/5) + finish_estimate/5; } return new ScanInfo(this, state, error, runtime, end_ms, performed_work_units, total_work_units, address, command_name); } /** @return Commands executed by this scan */ public List<ScanCommand> getScanCommands() { // Fetch underlying commands for implementations final List<ScanCommand> commands = new ArrayList<ScanCommand>(implementations.size()); for (ScanCommandImpl<?> impl : implementations) commands.add(impl.getCommand()); return commands; } /** @param address Command address * @return ScanCommand with that address * @throws Exception when not found */ public ScanCommand getCommandByAddress(final long address) throws Exception { final ScanCommand found = findCommandByAddress(getScanCommands(), address); if (found == null) throw new Exception("Invalid command address " + address); return found; } /** Recursively search for command by address * @param commands Command list * @param address Desired command address * @return Command with that address or <code>null</code> */ private ScanCommand findCommandByAddress(final List<ScanCommand> commands, final long address) { for (ScanCommand command : commands) { if (command.getAddress() == address) return command; else if (command instanceof LoopCommand) { final LoopCommand loop = (LoopCommand) command; final ScanCommand found = findCommandByAddress(loop.getBody(), address); if (found != null) return found; } } return null; } /** Attempt to update a command parameter to a new value * @param address Address of the command * @param property_id Property to update * @param value New value for the property * @throws Exception on error */ public void updateScanProperty(final long address, final String property_id, final Object value) throws Exception { final ScanCommand command = getCommandByAddress(address); try { command.setProperty(property_id, value); } catch (Exception ex) { throw new Exception("Cannot update " + property_id + " of " + command.getCommandName(), ex); } } /** {@inheritDoc} */ @Override public MacroContext getMacros() { return macros; } /** Obtain devices used by this scan. * * <p>Note that the result can differ before and * after the scan gets executed because devices * are added to the device context as needed. * * @return Devices used by this scan */ public Device[] getDevices() { return devices.getDevices(); } /** {@inheritDoc} */ @Override public Device getDevice(final String name) throws Exception { return devices.getDevice(name); } /** {@inheritDoc} */ @Override public void setLogMode(final boolean automatic) { automatic_log_mode = automatic; } /** {@inheritDoc} */ @Override public boolean isAutomaticLogMode() { return automatic_log_mode; } /** {@inheritDoc} */ @Override public synchronized DataLog getDataLog() { return data_logger; } /** {@inheritDoc} */ @Override public synchronized long getLastScanDataSerial() throws Exception { if (data_logger == null) return super.getLastScanDataSerial(); return data_logger.getLastScanDataSerial(); } /** {@inheritDoc} */ @Override public synchronized ScanData getScanData() throws Exception { if (data_logger == null) return super.getScanData(); return data_logger.getScanData(); } /** Callable for executing all commands on the scan, * turning exceptions into a 'Failed' scan state. */ @Override public Object call() throws Exception { final Logger log = Logger.getLogger(getClass().getName()); log.log(Level.INFO, "Executing {0} [{1}]", new Object[] { getName(), new MemoryInfo()}); try ( final DataLog logger = DataLogFactory.getDataLog(this); ) { // Set logger for execution of scan synchronized (this) { data_logger = logger; } execute_or_die_trying(); // Exceptions will already have been caught within execute_or_die_trying, // hopefully updating the status PVs, but there could be exceptions // when connecting or closing devices which we'll catch here } catch (InterruptedException ex) { state.set(ScanState.Aborted); error = ScanState.Aborted.name(); } catch (Exception ex) { state.set(ScanState.Failed); error = ex.getMessage(); log.log(Level.WARNING, "Scan " + getName() + " failed", ex); } // Set actual end time, not estimated end_ms = System.currentTimeMillis(); // Un-set data logger synchronized (this) { data_logger = null; } return null; } /** Execute all commands on the scan, * passing exceptions back up. * @throws Exception on error */ private void execute_or_die_trying() throws Exception { // Was scan aborted before it ever got to run? if (state.get() == ScanState.Aborted) return; // Otherwise expect 'Idle' if (! state.compareAndSet(ScanState.Idle, ScanState.Running)) throw new IllegalStateException("Cannot run Scan that is " + state.get()); start_ms = System.currentTimeMillis(); // Locate devices for status PVs final String prefix = ScanSystemPreferences.getStatusPvPrefix(); if (prefix != null && !prefix.isEmpty()) { device_active = prefix + "Active"; devices.addPVDevice(new DeviceInfo(device_active)); device_status = prefix + "Status"; devices.addPVDevice(new DeviceInfo(device_status)); device_state = prefix + "State"; devices.addPVDevice(new DeviceInfo(device_state)); device_progress = prefix + "Progress"; devices.addPVDevice(new DeviceInfo(device_progress)); device_finish = prefix + "Finish"; devices.addPVDevice(new DeviceInfo(device_finish)); } // Add devices used by commands DeviceContextHelper.addScanDevices(devices, macros, pre_scan); DeviceContextHelper.addScanDevices(devices, macros, implementations); DeviceContextHelper.addScanDevices(devices, macros, post_scan); // Start Devices devices.startDevices(); // Execute commands try { execute(new WaitForDevicesCommandImpl(new WaitForDevicesCommand(devices.getDevices()), null)); // Initialize scan status PVs. Error will prevent scan from starting. if (device_active != null) { getDevice(device_status).write(getName()); ScanCommandUtil.write(this, device_state, getScanState().ordinal(), 0.1, timeout); ScanCommandUtil.write(this, device_active, Double.valueOf(1.0), 0.1, timeout); ScanCommandUtil.write(this, device_progress, Double.valueOf(0.0), 0.1, timeout); getDevice(device_finish).write("Starting ..."); } try { // Execute pre-scan commands execute(pre_scan); // Reset work step counter to only count the 'main' commands work_performed.set(0); // Execute the submitted commands execute(implementations); // Successful finish state.set(ScanState.Finished); } finally { // Try post-scan commands even if submitted commands ran into problems or were aborted. // Save the state before going back to Running for post commands. final long saved_steps = work_performed.get(); final ScanState saved_state = state.getAndSet(ScanState.Running); execute(post_scan); // Restore saved state work_performed.set(saved_steps); state.set(saved_state); } } catch (Exception ex) { if (state.get() == ScanState.Aborted) error = ScanState.Aborted.name(); else { error = ex.getMessage(); state.set(ScanState.Failed); Logger.getLogger(getClass().getName()).log(Level.WARNING, "Scan " + getName() + " failed", ex); } } finally { current_address = -1; current_command = null; end_ms = System.currentTimeMillis(); try { // Final status PV update. if (device_active != null) { getDevice(device_status).write(""); ScanCommandUtil.write(this, device_state, getScanState().ordinal(), 0.1, timeout); getDevice(device_finish).write(ScanSampleFormatter.format(new Date())); ScanCommandUtil.write(this, device_progress, Double.valueOf(100.0), 0.1, timeout); ScanCommandUtil.write(this, device_active, Double.valueOf(0.0), 0.1, timeout); } } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.WARNING, "Final Scan status PV update failed", ex); } // Stop devices devices.stopDevices(); } } /** {@inheritDoc} */ @Override public void execute(final List<ScanCommandImpl<?>> commands) throws Exception { for (ScanCommandImpl<?> command : commands) { final ScanState current_state = state.get(); if (current_state != ScanState.Running && current_state != ScanState.Paused) return; execute(command); } } /** {@inheritDoc} */ @Override public void execute(final ScanCommandImpl<?> command) throws Exception { if (state.get() == ScanState.Paused) { if (device_state != null) ScanCommandUtil.write(this, device_state, state.get().ordinal(), 0.1, timeout); while (state.get() == ScanState.Paused) { synchronized (this) { wait(); } } if (device_state != null) ScanCommandUtil.write(this, device_state, state.get().ordinal(), 0.1, timeout); } boolean retry; do { retry = false; try { // Update current command, but only track address if valid. // Will NOT update the address when going into IncludeCommand. current_command = command; if (current_command.getCommand().getAddress() >= 0) current_address = current_command.getCommand().getAddress(); Logger.getLogger(getClass().getName()).log(Level.FINE, "@{0}: {1}", new Object[] { current_address, command }); command.execute(this); } catch (Exception error) { // Was command interrupted on purpose? // That would typically result in an 'InterruptedException', // but interrupted command might wrap that into a different type // of exception // -> Best way to detect an abort is via the scan state if (state.get() == ScanState.Aborted) { final String message = "Command aborted: " + command.toString(); Logger.getLogger(getClass().getName()).log(Level.INFO, message, error); throw error; } // Command generated an error final String message = "Command failed: " + command.toString(); Logger.getLogger(getClass().getName()).log(Level.WARNING, message, error); // Error handler determines how to proceed switch (command.handleError(this, error)) { case Abort: // Abort on the original error throw error; case Continue: // Ignore the error, move on return; case Retry: retry = true; } } // Try to update Scan PVs on progress. Log errors, but continue scan if (device_status != null) { final ScanInfo info = getScanInfo(); try { ScanCommandUtil.write(this, device_progress, Double.valueOf(info.getPercentage()), 0.1, timeout); getDevice(device_finish).write(ScanSampleFormatter.formatCompactDateTime(info.getFinishTime())); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.WARNING, "Error updating status PVs", ex); } } } while (retry); } /** Pause execution of a currently executing scan */ public void pause() { state.compareAndSet(ScanState.Running, ScanState.Paused); } /** Resume execution of a paused scan */ public void resume() { state.compareAndSet(ScanState.Paused, ScanState.Running); // Notify should only be necessary if compareAndSet actually switched to Running, // but doesn't hurt if called in any case synchronized (this) { notifyAll(); } } /** Ask for execution to stop */ public void abort() { // Set state to aborted unless it is already 'done' state.getAndUpdate((current_state) -> current_state.isDone() ? current_state : ScanState.Aborted); if (future != null) future.cancel(true); synchronized (this) { notifyAll(); } } /** {@inheritDoc} */ @Override public void workPerformed(final int work_units) { work_performed.addAndGet(work_units); } }
package fi.tnie.db.feature; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import fi.tnie.db.QueryHelper; import fi.tnie.db.env.CatalogFactory; import fi.tnie.db.expr.Identifier; import fi.tnie.db.expr.SchemaElementName; import fi.tnie.db.expr.Statement; import fi.tnie.db.expr.ddl.CreateSchema; import fi.tnie.db.expr.ddl.CreateTable; import fi.tnie.db.expr.ddl.DropSchema; import fi.tnie.db.expr.ddl.DropTable; import fi.tnie.db.meta.BaseTable; import fi.tnie.db.meta.Catalog; import fi.tnie.db.meta.Environment; import fi.tnie.db.meta.Schema; import fi.tnie.db.query.QueryException; public class Features extends AbstractFeature { private static final String FEATURES_SCHEMA = "features"; private static final String FEATURE_TABLE = "feature"; private static final String DEPENDENCY_TABLE = "dependency"; private List<Feature> featureList; private static Logger logger = Logger.getLogger(Features.class); public Features() { super(Features.class, 0, 1); } @Override public SQLGenerator getSQLGenerator() { return new Generator(); } public void addFeature(Feature feature) { if (feature == null) { throw new NullPointerException("'feature' must not be null"); } getFeatureList().add(feature); } private List<Feature> getFeatureList() { if (featureList == null) { featureList = new ArrayList<Feature>(); } return featureList; } class Generator implements SQLGenerator { @Override public SQLGenerationResult modify(Catalog cat) throws SQLGenerationException { final SQLGenerationResult result = new SQLGenerationResult(); final Environment env = cat.getEnvironment(); final Identifier sn = schemaName(env); final Schema schema = cat.schemas().get(sn); if (schema == null) { result.add(new CreateSchema(sn)); } Identifier features = featuresTable(env); { BaseTable table = getBaseTable(schema, features); if (table == null) { CreateTable ct = createFeaturesTable(cat, sn, features); result.add(ct); } } { Identifier n = dependenciesTable(env); BaseTable table = getBaseTable(schema, n); if (table == null) { CreateTable ct = createDependenciesTable(cat, sn, n, features); result.add(ct); } } return result; } private BaseTable getBaseTable(Schema schema, Identifier n) { return (schema == null) ? null : schema.baseTables().get(n); } private CreateTable createFeaturesTable(Catalog cat, Identifier sn, Identifier tn) { // using catalog name as a qualifier would be too stiff, right? SchemaElementName sen = new SchemaElementName(null, sn, tn); TableDesign td = new TableDesign(cat.getEnvironment(), new CreateTable(sen)); // Maybe we should add a flag to column definition to mark // autoincrement column and inspect that later? td.serial("ID"); td.varchar("NAME", 12); td.integer("VERSION_MAJOR"); td.integer("VERSION_MINOR"); return td.getTable(); } private CreateTable createDependenciesTable(Catalog cat, Identifier sn, Identifier tn, Identifier features) { // using catalog name as a qualifier would be too stiff, right? SchemaElementName sen = new SchemaElementName(null, sn, tn); TableDesign td = new TableDesign(cat.getEnvironment(), new CreateTable(sen)); String dependent = "DEPENDENT"; String dependency = "DEPENDENCY"; td.integer(dependent); td.integer(dependency); td.integer("MIN_MAJOR"); td.integer("MAX_MAJOR"); td.integer("MIN_MINOR"); td.integer("MAX_MINOR"); td.primaryKey(); return td.getTable(); } @Override public SQLGenerationResult revert(Catalog cat) throws SQLGenerationException { Environment env = cat.getEnvironment(); SQLGenerationResult r = new SQLGenerationResult(); Schema schema = cat.schemas().get(schemaName(env)); drop(r, schema, dependenciesTable(env)); drop(r, schema, featuresTable(env)); drop(r, schema); return r; } private void drop(SQLGenerationResult r, Schema schema) { if (schema != null) { r.add(new DropSchema(schema.getUnqualifiedName())); } } void drop(SQLGenerationResult result, Schema schema, Identifier name) { BaseTable table = getBaseTable(schema, name); if (table != null) { result.add(new DropTable(table.getName())); } } private Identifier schemaName(Environment env) { return env.createIdentifier(FEATURES_SCHEMA); } private Identifier featuresTable(Environment env) { return env.createIdentifier(FEATURE_TABLE); } private Identifier dependenciesTable(Environment env) { return env.createIdentifier(DEPENDENCY_TABLE); } } public void installAll(Connection c, CatalogFactory cf, boolean intermediateCommit) throws QueryException, SQLException, SQLGenerationException { logger().debug("installAll - enter"); List<Feature> features = getFeatureList(); { ArrayList<Feature> reversed = new ArrayList<Feature>(features); Collections.reverse(reversed); boolean revert = true; for(int i = 0; i < 5; i++) { // revert all if (!process(c, cf, reversed, revert, intermediateCommit)) { } } } for(int i = 0; i < 5; i++) { // keep generating layers until any feature // has nothing to add/remove: if (!process(c, cf, features, false, intermediateCommit)) { break; } } if (!intermediateCommit) { c.commit(); } logger().debug("installAll - exit"); } private boolean process(Connection c, CatalogFactory cf, List<Feature> features, boolean revert, boolean commit) throws QueryException, SQLException, SQLGenerationException { logger().debug("process - enter"); Catalog cat = cf.create(c); int count = 0; for (Feature f : features) { SQLGenerator g = f.getSQLGenerator(); if (g != null) { SQLGenerationResult result = revert ? g.revert(cat) : g.modify(cat); List<Statement> list = result.statements(); if (!list.isEmpty()) { executeAll(c, list); if (commit) { c.commit(); } count += list.size(); // recreate catalog to get the updated meta-data: cat = cf.create(c); } } } logger().debug("process - exit: " + count); return count > 0; } private void executeAll(Connection c, List<Statement> list) throws SQLException { for (Statement statement : list) { String sql = statement.generate(); logger().debug("query: " + sql); PreparedStatement ps = c.prepareStatement(sql); try { ps.executeUpdate(); } finally { ps = QueryHelper.doClose(ps); } } } public static Logger logger() { return Features.logger; } }
package org.csstudio.scan.server; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.csstudio.scan.ScanSystemPreferences; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; import org.python.core.PyException; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; /** Helper for obtaining Jython interpreter * * TODO Join with org.csstudio.opibuilder.script.ScriptStoreFactory into a new org.csstudio.jython * * @author Kay Kasemir */ @SuppressWarnings("nls") public class JythonSupport { private static List<String> paths = init(); final private PythonInterpreter interpreter; /** Perform static, one-time initialization */ private static List<String> init() { final List<String> paths = new ArrayList<String>(); try { // Add Jython's /Lib to path final Bundle bundle = Platform.getBundle("org.python.jython"); if (bundle == null) throw new Exception("Cannot locate jython bundle"); // Different packaging where jython.jar is expanded, /Lib at plugin root String home = FileLocator.resolve(new URL("platform:/plugin/org.python.jython")).getPath(); // Turn politically correct URL path digestible by jython if (home.startsWith("file:/")) home = home.substring(5); home = home.replace(".jar!", ".jar"); paths.add(home + "Lib/"); // Add scan script paths final String[] pref_paths = ScanSystemPreferences.getScriptPaths(); for (String pref_path : pref_paths) { // Resolve platform:/plugin/... if (pref_path.startsWith("platform:/plugin/")) { final String plugin_path = pref_path.substring(17); // Locate name of plugin and path within plugin final int sep = plugin_path.indexOf('/'); final String plugin, path_within; if (sep < 0) { plugin = plugin_path; path_within = "/"; } else { plugin = plugin_path.substring(0, sep); path_within = plugin_path.substring(sep + 1); } final String path = getPluginPath(plugin, path_within); if (path == null) throw new Exception("Error in scan script path " + pref_path); else paths.add(path); } else // Add as-is paths.add(pref_path); } // Disable cachedir to avoid creation of cachedir folder. // See http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning final Properties props = new Properties(); props.setProperty(PySystemState.PYTHON_CACHEDIR_SKIP, "true"); // Jython 2.7(b3) needs these to set sys.prefix and sys.executable. // If left undefined, initialization of Lib/site.py fails with // posixpath.py", line 394, in normpath AttributeError: // 'NoneType' object has no attribute 'startswith' props.setProperty("python.home", home); props.setProperty("python.executable", "css"); PythonInterpreter.initialize(System.getProperties(), props, new String[] {""}); } catch (Exception ex) { Logger.getLogger(JythonSupport.class.getName()). log(Level.SEVERE, "Once this worked OK, but now the Jython initialization failed. Don't you hate computers?", ex); } return paths; } /** Locate a path inside a bundle. * * <p>If the bundle is JAR-ed up, the {@link FileLocator} will * return a location with "file:" and "..jar!/path". * This method patches the location such that it can be used * on the Jython path. * * @param bundle_name Name of bundle * @param path_in_bundle Path within bundle * @return Location of that path within bundle, or <code>null</code> if not found or no bundle support * @throws IOException on error */ private static String getPluginPath(final String bundle_name, final String path_in_bundle) throws IOException { final Bundle bundle = Platform.getBundle(bundle_name); if (bundle == null) return null; final URL url = FileLocator.find(bundle, new Path(path_in_bundle), null); if (url == null) return null; String path = FileLocator.resolve(url).getPath(); path = path.replace("file:/", "/"); path = path.replace(".jar!/", ".jar/"); return path; } /** Initialize * @throws Exception on error */ public JythonSupport() throws Exception { final PySystemState state = new PySystemState(); // Path to Python standard lib, numjy, scan system for (String path : paths) state.path.append(new PyString(path)); // Creating a PythonInterpreter is very slow. // In addition, concurrent creation is not supported, resulting in // Lib/site.py", line 571, in <module> .. // Lib/sysconfig.py", line 159, in _subst_vars AttributeError: {'userbase'} // or Lib/site.py", line 122, in removeduppaths java.util.ConcurrentModificationException // Sync. on JythonSupport to serialize the interpreter creation and avoid above errors. // Curiously, this speeds the interpreter creation up, // presumably because they're not concurrently trying to access the same resources? synchronized (JythonSupport.class) { interpreter = new PythonInterpreter(null, state); } } /** Load a Jython class * * @param type Type of the Java object to return * @param class_name Name of the Jython class, * must be in package (file) using lower case of class name * @param args Arguments to pass to constructor * @return Java object for instance of Jython class * @throws Exception on error */ @SuppressWarnings("unchecked") public <T> T loadClass(final Class<T> type, final String class_name, final String... args) throws Exception { // Get package name final String pack_name = class_name.toLowerCase(); Logger.getLogger(getClass().getName()).log(Level.FINE, "Loading Jython class {0} from {1}", new Object[] { class_name, pack_name }); try { // Import class into Jython interpreter.exec("from " + pack_name + " import " + class_name); } catch (PyException ex) { Logger.getLogger(getClass().getName()).log(Level.WARNING, "Error loading Jython class {0} from {1}", new Object[] { class_name, pack_name }); Logger.getLogger(getClass().getName()).log(Level.WARNING, "Search path: {0}",interpreter.getSystemState().path); throw new Exception("Error loading Jython class " + class_name + ":" + getExceptionMessage(ex), ex); } // Create Java reference final PyObject py_class = interpreter.get(class_name); final PyObject py_object; if (args.length <= 0) py_object = py_class.__call__(); else { final PyObject[] py_args = new PyObject[args.length]; for (int i=0; i<py_args.length; ++i) py_args[i] = new PyString(args[i]); py_object = py_class.__call__(py_args); } final T java_ref = (T) py_object.__tojava__(type); return java_ref; } /** We can only report the message of an exception back to scan server * clients, not the whole exception because it doesn't 'serialize'. * The PyException, however, tends to have no message at all. * This helper tries to generate a somewhat useful message * from the content of the exception. * @param ex Python exception * @return Message with info about python exception */ public static String getExceptionMessage(final PyException ex) { final StringBuilder buf = new StringBuilder(); if (ex.value instanceof PyString) buf.append(" ").append(ex.value.asString()); else if (ex.getCause() != null) buf.append(" ").append(ex.getCause().getMessage()); if (ex.traceback != null) { buf.append(" "); ex.traceback.dumpStack(buf); } return buf.toString(); } }
package filter.expression; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import model.Model; import model.TurboIssue; import model.TurboLabel; import model.TurboMilestone; import model.TurboUser; import util.Utility; import filter.MetaQualifierInfo; import filter.QualifierApplicationException; public class Qualifier implements FilterExpression { private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMM yy, h:mm a"); public static final Qualifier EMPTY = new Qualifier("", ""); private final String name; // Only one of these will be present at a time private Optional<DateRange> dateRange = Optional.empty(); private Optional<String> content = Optional.empty(); private Optional<LocalDate> date = Optional.empty(); private Optional<NumberRange> numberRange = Optional.empty(); // Copy constructor public Qualifier(Qualifier other) { this.name = other.getName(); if (other.getDateRange().isPresent()) { this.dateRange = other.getDateRange(); } else if (other.getDate().isPresent()) { this.date = other.getDate(); } else if (other.getContent().isPresent()) { this.content = other.getContent(); } else if (other.getNumberRange().isPresent()) { this.numberRange = other.getNumberRange(); } else { assert false : "Unrecognised content type! You may have forgotten to add it above"; } } public Qualifier(String name, String content) { this.name = name; this.content = Optional.of(content); } public Qualifier(String name, NumberRange numberRange) { this.name = name; this.numberRange = Optional.of(numberRange); } public Qualifier(String name, DateRange dateRange) { this.name = name; this.dateRange = Optional.of(dateRange); } public Qualifier(String name, LocalDate date) { this.name = name; this.date = Optional.of(date); } /** * Helper function for testing a filter expression against an issue. * Ensures that meta-qualifiers are taken care of. * Should always be used over isSatisfiedBy. */ public static boolean process(FilterExpression expr, TurboIssue issue) { FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::isNotMetaQualifier); List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier); return exprWithNormalQualifiers.isSatisfiedBy(issue, new MetaQualifierInfo(metaQualifiers)); } public boolean isEmptyQualifier() { return name.isEmpty() && content.isPresent() && content.get().isEmpty(); } public boolean isSatisfiedBy(TurboIssue issue, MetaQualifierInfo info) { assert name != null && content != null; // The empty qualifier is satisfied by anything if (isEmptyQualifier()) return true; switch (name) { case "id": return idSatisfies(issue); case "keyword": return keywordSatisfies(issue, info); case "title": return titleSatisfies(issue); case "body": return bodySatisfies(issue); case "milestone": return milestoneSatisfies(issue); case "parent": return parentSatisfies(issue); case "label": return labelsSatisfy(issue); case "author": return authorSatisfies(issue); case "assignee": return assigneeSatisfies(issue); case "involves": case "user": return involvesSatisfies(issue); case "type": return typeSatisfies(issue); case "state": case "status": return stateSatisfies(issue); case "has": return satisfiesHasConditions(issue); case "no": return satisfiesNoConditions(issue); case "is": return satisfiesIsConditions(issue); case "created": return satisfiesCreationDate(issue); case "updated": return satisfiesUpdatedHours(issue); default: return false; } } @Override public void applyTo(TurboIssue issue, Model model) throws QualifierApplicationException { assert name != null && content != null; // The empty qualifier should not be applied to anything assert !isEmptyQualifier(); switch (name) { case "title": case "desc": case "body": case "keyword": throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging"); case "id": throw new QualifierApplicationException("Unnecessary filter: id is immutable"); case "created": throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date"); case "has": case "no": case "is": throw new QualifierApplicationException("Ambiguous filter: " + name); case "milestone": applyMilestone(issue, model); break; case "parent": applyParent(issue, model); break; case "label": applyLabel(issue, model); break; case "assignee": applyAssignee(issue, model); break; case "author": throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue"); case "involves": case "user": throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue"); case "state": case "status": applyState(issue); break; default: break; } } @Override public boolean canBeAppliedToIssue() { return true; } @Override public List<String> getQualifierNames() { return new ArrayList<String>(Arrays.asList(name)); } @Override public FilterExpression filter(Predicate<Qualifier> pred) { if (pred.test(this)) { return new Qualifier(this); } else { return EMPTY; } } @Override public List<Qualifier> find(Predicate<Qualifier> pred) { if (pred.test(this)) { ArrayList<Qualifier> result = new ArrayList<>(); result.add(this); return result; } else { return new ArrayList<>(); } } /** * This method is used to serialise qualifiers. Thus whatever form returned * should be syntactically valid. */ @Override public String toString() { if (this == EMPTY) { return ""; } else if (content.isPresent()) { if (name.equals("keyword")) { return content.get(); } else { return name + ":" + content.get().toString(); } } else if (date.isPresent()) { return name + ":" + date.get().toString(); } else if (dateRange.isPresent()) { return name + ":" + dateRange.get().toString(); } else if (numberRange.isPresent()) { return name + ":" + numberRange.get().toString(); } else { assert false : "Should not happen"; return ""; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Qualifier other = (Qualifier) obj; if (content == null) { if (other.content != null) return false; } else if (!content.equals(other.content)) return false; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (dateRange == null) { if (other.dateRange != null) return false; } else if (!dateRange.equals(other.dateRange)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } private static boolean isNotMetaQualifier(Qualifier q) { return !isMetaQualifier(q); } private static boolean isMetaQualifier(Qualifier q) { switch (q.getName()) { case "in": return true; default: return false; } } private int parseIdString(String id) { if (id.startsWith(" return Integer.parseInt(id.substring(1)); } else if (Character.isDigit(id.charAt(0))) { return Integer.parseInt(id); } else { return -1; } } private boolean idSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getId() == parseIdString(content.get()); } private boolean satisfiesUpdatedHours(TurboIssue issue) { if (!numberRange.isPresent()) return false; long hours = issue.getUpdatedAt().until(LocalDateTime.now(), ChronoUnit.HOURS); return numberRange.get().encloses(Utility.safeLongToInt(hours)); } private boolean satisfiesCreationDate(TurboIssue issue) { LocalDate creationDate = LocalDate.parse(issue.getCreatedAt(), formatter); if (date.isPresent()) { return creationDate.isEqual(date.get()); } else if (dateRange.isPresent()) { return dateRange.get().encloses(creationDate); } else { return false; } } private boolean satisfiesHasConditions(TurboIssue issue) { if (!content.isPresent()) return false; switch (content.get()) { case "label": case "labels": return issue.getLabels().size() > 0; case "milestone": case "milestones": return issue.getMilestone() != null; case "assignee": case "assignees": return issue.getAssignee() != null; case "parent": case "parents": return issue.getParentIssue() != -1; default: return false; } } private boolean satisfiesNoConditions(TurboIssue issue) { if (!content.isPresent()) return false; return !satisfiesHasConditions(issue); } private boolean satisfiesIsConditions(TurboIssue issue) { if (!content.isPresent()) return false; switch (content.get()) { case "open": case "closed": return stateSatisfies(issue); case "pr": case "issue": return typeSatisfies(issue); case "merged": case "unmerged": return isPullRequest(issue) && !issue.isOpen(); default: return false; } } private boolean stateSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String content = this.content.get().toLowerCase(); if (content.contains("open")) { return issue.isOpen(); } else if (content.contains("closed")) { return !issue.isOpen(); } else { return false; } } private boolean assigneeSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; TurboUser assignee = issue.getAssignee(); String content = this.content.get().toLowerCase(); if (assignee == null) return false; return assignee.getAlias().toLowerCase().contains(content) || assignee.getGithubName().toLowerCase().contains(content) || (assignee.getRealName() != null && assignee.getRealName().toLowerCase().contains(content)); } private boolean authorSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String creator = issue.getCreator().toLowerCase(); return creator != null && creator.contains(content.get().toLowerCase()); } private boolean involvesSatisfies(TurboIssue issue) { return authorSatisfies(issue) || assigneeSatisfies(issue); } private boolean labelsSatisfy(TurboIssue issue) { if (!content.isPresent()) return false; String group = ""; String labelName = content.get().toLowerCase(); Optional<String[]> tokens = TurboLabel.parseName(labelName); if (tokens.isPresent()) { group = tokens.get()[0]; labelName = tokens.get()[1]; } else { // The name isn't in the format group.name or group. // Take the entire thing to be the label name } // Both can't be null assert group != null && labelName != null; // At most one can be empty assert !(group.isEmpty() && labelName.isEmpty()); for (TurboLabel l : issue.getLabels()) { if (labelName.isEmpty() || l.getName() != null && l.getName().toLowerCase().contains(labelName)) { if (group.isEmpty() || l.getGroup() != null && l.getGroup().toLowerCase().contains(group)) { return true; } } } return false; } private boolean parentSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String parent = content.get().toLowerCase(); int index = parseIdString(parent); if (index > 0) { TurboIssue current = issue; // The parent itself should show if (current.getId() == index) return true; // Descendants should show too return current.hasAncestor(index); } // Invalid issue number return false; } private boolean milestoneSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; if (issue.getMilestone() == null) return false; return issue.getMilestone().getTitle().toLowerCase().contains(content.get().toLowerCase()); } private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) { if (info.getIn().isPresent()) { switch (info.getIn().get()) { case "title": return titleSatisfies(issue); case "body": case "desc": return bodySatisfies(issue); default: return false; } } else { return titleSatisfies(issue) || bodySatisfies(issue); } } private boolean bodySatisfies(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getDescription().toLowerCase().contains(content.get().toLowerCase()); } private boolean titleSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getTitle().toLowerCase().contains(content.get().toLowerCase()); } private boolean isPullRequest(TurboIssue issue) { return issue.getPullRequest() != null; } private boolean typeSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String content = this.content.get().toLowerCase(); if (content.equals("issue")) { return !isPullRequest(issue); } else if (content.equals("pr") || content.equals("pullrequest")) { return isPullRequest(issue); } else { return false; } } private void applyMilestone(TurboIssue issue, Model model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Invalid milestone " + (date.isPresent() ? date.get() : dateRange.get())); } // Find milestones containing the partial title List<TurboMilestone> milestones = model.getMilestones().stream().filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase())).collect(Collectors.toList()); if (milestones.size() > 1) { throw new QualifierApplicationException("Ambiguous filter: can apply any of the following milestones: " + milestones.toString()); } else { issue.setMilestone(milestones.get(0)); } } private void applyParent(TurboIssue issue, Model model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Invalid parent " + (date.isPresent() ? date.get() : dateRange.get())); } String parent = content.get().toLowerCase(); int index = parseIdString(parent); if (index != -1) { issue.setParentIssue(index); } else { // Find parents containing the partial title List<TurboIssue> parents = model.getIssues().stream().filter(i -> i.getTitle().toLowerCase().contains(parent.toLowerCase())).collect(Collectors.toList()); if (parents.size() > 1) { throw new QualifierApplicationException("Ambiguous filter: can apply any of the following parents: " + parents.toString()); } else { issue.setParentIssue(parents.get(0).getId()); } } } private void applyLabel(TurboIssue issue, Model model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Invalid label " + (date.isPresent() ? date.get() : dateRange.get())); } // Find labels containing the label name List<TurboLabel> labels = model.getLabels() .stream() .filter(l -> l.toGhName().toLowerCase().contains(content.get().toLowerCase())).collect(Collectors.toList()); if (labels.size() > 1) { throw new QualifierApplicationException("Ambiguous filter: can apply any of the following labels: " + labels.toString()); } else { issue.addLabel(labels.get(0)); } } private void applyAssignee(TurboIssue issue, Model model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Invalid assignee " + (date.isPresent() ? date.get() : dateRange.get())); } // Find assignees containing the partial title List<TurboUser> assignees = model.getCollaborators().stream().filter(c -> c.getGithubName().toLowerCase().contains(content.get().toLowerCase())).collect(Collectors.toList()); if (assignees.size() > 1) { throw new QualifierApplicationException("Ambiguous filter: can apply any of the following assignees: " + assignees.toString()); } else { issue.setAssignee(assignees.get(0)); } } private void applyState(TurboIssue issue) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Invalid state " + (date.isPresent() ? date.get() : dateRange.get())); } if (content.get().toLowerCase().contains("open")) { issue.setOpen(true); } else if (content.get().toLowerCase().contains("closed")) { issue.setOpen(false); } } public Optional<NumberRange> getNumberRange() { return numberRange; } public Optional<DateRange> getDateRange() { return dateRange; } public Optional<String> getContent() { return content; } public Optional<LocalDate> getDate() { return date; } public String getName() { return name; } }
package org.ovirt.engine.core.vdsbroker.xmlrpc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodRetryHandler; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.lang.StringUtils; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcClientException; import org.apache.xmlrpc.client.XmlRpcCommonsTransport; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import org.apache.xmlrpc.client.XmlRpcTransport; import org.apache.xmlrpc.client.util.ClientFactory; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.utils.ThreadLocalParamsContainer; import org.ovirt.engine.core.utils.crypt.EngineEncryptionUtils; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.ovirt.engine.core.vdsbroker.vdsbroker.FutureCall; public class XmlRpcUtils { private static final String HTTP = "http: private static final String HTTPS = "https: private static Log log = LogFactory.getLog(XmlRpcUtils.class); static { if (Config.<Boolean> getValue(ConfigValues.EncryptHostCommunication)) { URL keystoreUrl; try { // registering the https protocol with a socket factory that // provides client authentication. ProtocolSocketFactory factory = new AuthSSLProtocolSocketFactory(EngineEncryptionUtils.getKeyManagers(), EngineEncryptionUtils.getTrustManagers()); Protocol clientAuthHTTPS = new Protocol("https", factory, 54321); Protocol.registerProtocol("https", clientAuthHTTPS); } catch (Exception e) { log.fatal("Failed to init AuthSSLProtocolSocketFactory. SSL connections will not work", e); } } } /** * wrapper for the apache xmlrpc client factory. gets the xmlrpc connection parameters and an interface to implement * and returns an instance which implements the given interface. * @param <T> * the type of the instance for the interface * @param hostName * - the host to connect to * @param port * - the port to connect to * @param clientTimeOut * - the time out for the connection * @param type * - the instance type of the interface for this connection * @param isSecure * - if a connection should be https or http * @return an instance of the given type. */ public static <T> Pair<T, HttpClient> getConnection(String hostName, int port, int clientTimeOut, int connectionTimeOut, int clientRetries, Class<T> type, boolean isSecure) { Pair<String, URL> urlInfo = getConnectionUrl(hostName, port, null, isSecure); if (urlInfo == null) { return null; } return getHttpConnection(urlInfo.getSecond(), clientTimeOut, connectionTimeOut, clientRetries, type); } public static Pair<String, URL> getConnectionUrl(String hostName, int port, String path, boolean isSecure) { URL serverUrl; String prefix; String url; if (isSecure) { prefix = HTTPS; } else { prefix = HTTP; } try { url = prefix + hostName + ":" + port + (path != null ? "/" + path : ""); serverUrl = new URL(url); } catch (MalformedURLException mfue) { log.error("failed to form the xml-rpc url", mfue); return null; } return new Pair<>(url, serverUrl); } public static void shutDownConnection(HttpClient httpClient) { if (httpClient != null && httpClient.getHttpConnectionManager() != null) { ((MultiThreadedHttpConnectionManager) (httpClient).getHttpConnectionManager()).shutdown(); } } @SuppressWarnings("unchecked") private static <T> Pair<T, HttpClient> getHttpConnection(URL serverUrl, int clientTimeOut, int connectionTimeOut, int clientRetries, Class<T> type) { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(serverUrl); config.setConnectionTimeout(connectionTimeOut); config.setReplyTimeout(clientTimeOut); XmlRpcClient xmlRpcClient = new XmlRpcClient(); xmlRpcClient.setConfig(config); XmlRpcCommonsTransportFactory transportFactory = new CustomXmlRpcCommonsTransportFactory(xmlRpcClient); HttpClient httpclient = createHttpClient(clientRetries, connectionTimeOut); transportFactory.setHttpClient(httpclient); xmlRpcClient.setTransportFactory(transportFactory); ClientFactory clientFactory = new ClientFactory(xmlRpcClient); T connector = (T) clientFactory.newInstance(Thread.currentThread().getContextClassLoader(), type, null); T asyncConnector = (T) AsyncProxy.newInstance(connector, clientTimeOut); Pair<T, HttpClient> returnValue = new Pair<T, HttpClient>(asyncConnector, httpclient); return returnValue; } private static HttpClient createHttpClient(int clientRetries, int connectionTimeout) { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setConnectionTimeout(connectionTimeout); MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); httpConnectionManager.setParams(params); // Create the client: HttpClient client = new HttpClient(httpConnectionManager); // Configure the HTTP client so it will retry the execution of // methods when there are IO errors: int retries = Config.<Integer> getValue(ConfigValues.vdsRetries); HttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(retries, false); HttpClientParams parameters = client.getParams(); parameters.setParameter(HttpMethodParams.RETRY_HANDLER, handler); // Done: return client; } private static class AsyncProxy implements InvocationHandler { private Object obj; private long timeoutInMilisec; public static Object newInstance(Object obj, long timeoutInMilisec) { return Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), obj.getClass().getInterfaces(), new AsyncProxy(obj, timeoutInMilisec)); } private AsyncProxy(Object obj, long timeoutInMilisec) { this.obj = obj; this.timeoutInMilisec = timeoutInMilisec; } @Override public Object invoke(Object proxy, final Method m, final Object[] args) throws Throwable { Object result; FutureTask<Object> future; FutureCall annotation = m.getAnnotation(FutureCall.class); if (annotation != null) { future = new FutureTask<Object>(createCallable(obj, getMethod(m, annotation, proxy), args, ThreadLocalParamsContainer.getCorrelationId())); ThreadPoolUtil.execute(future); return future; } else { future = new FutureTask<Object>(createCallable(obj, m, args, ThreadLocalParamsContainer.getCorrelationId())); ThreadPoolUtil.execute(future); try { result = future.get(timeoutInMilisec, TimeUnit.MILLISECONDS); } catch (Exception e) { if (e instanceof TimeoutException) { future.cancel(true); } throw new UndeclaredThrowableException(e); } return result; } } private Method getMethod(Method m, FutureCall annotation, Object proxy) throws SecurityException, NoSuchMethodException { if (!annotation.delegeteTo().isEmpty()) { return proxy.getClass().getDeclaredMethod(annotation.delegeteTo(), m.getParameterTypes()); } return m; } private Callable<Object> createCallable(Object obj, Method m, Object[] args, String correlationId) { return new InternalCallable(obj, m, args, correlationId); } private final class InternalCallable implements Callable<Object> { private Object obj; private Method m; private Object[] args; private String correlationId; public InternalCallable(Object obj, Method m, Object[] args, String correlationId) { this.obj = obj; this.m = m; this.args = args; this.correlationId = correlationId; } @Override public Object call() throws Exception { try { ThreadLocalParamsContainer.setCorrelationId(correlationId); return m.invoke(obj, args); } catch (Exception e) { throw e; } } } } /** * Designed to extend the request header with a value specifying the correlation ID to propagate to VDSM. */ private static class CustomXmlRpcCommonsTransport extends XmlRpcCommonsTransport { private static final String FLOW_ID_HEADER_NAME = "FlowID"; public CustomXmlRpcCommonsTransport(XmlRpcCommonsTransportFactory pFactory) { super(pFactory); } @Override protected void initHttpHeaders(XmlRpcRequest pRequest) throws XmlRpcClientException { super.initHttpHeaders(pRequest); String correlationId = ThreadLocalParamsContainer.getCorrelationId(); if (StringUtils.isNotBlank(correlationId)) { method.setRequestHeader(FLOW_ID_HEADER_NAME, correlationId); } } }; /** * Designed to to override the factory with a customized transport. */ private static class CustomXmlRpcCommonsTransportFactory extends XmlRpcCommonsTransportFactory { public CustomXmlRpcCommonsTransportFactory(XmlRpcClient pClient) { super(pClient); } @Override public XmlRpcTransport getTransport() { return new CustomXmlRpcCommonsTransport(this); } }; }
package org.openhab.io.semantic.tests; import org.openhab.io.semantic.core.QueryResult; import org.openhab.io.semantic.core.SemanticService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SemanticServiceTestImpl implements SemanticService { private static Logger logger = LoggerFactory.getLogger(SemanticServiceTestImpl.class); public void activate(){ logger.debug("Test Impl of semantic service activated"); } public void deactivate() { logger.debug("Test Impl of semantic service deactivated"); } @Override public QueryResult executeSelect(String queryAsString) { return new QueryResultTestImpl(queryAsString); } @Override public QueryResult executeSelect(String queryAsString, boolean withLatestValues) { return new QueryResultTestImpl(queryAsString); } @Override public boolean executeAsk(String askAsString) { return true; } @Override public boolean executeAsk(String askAsString, boolean withLatestValues) { return true; } @Override public QueryResult sendCommand(String queryAsString, String command) { return new QueryResultTestImpl(queryAsString); } @Override public QueryResult sendCommand(String queryAsString, String command, boolean withLatestValues) { return new QueryResultTestImpl(queryAsString); } @Override public String getCurrentInstanceAsString() { return "static test instance"; } @Override public void setAllValues() { // TODO Auto-generated method stub } @Override public String getRestUrlForItem(String uid) { // TODO Auto-generated method stub return null; } @Override public String getTypeName(String itemName) { return "default type name"; } @Override public String getLocationName(String itemName) { return "default location name"; } @Override public QueryResult getAllSensors() { // TODO Auto-generated method stub return null; } }
package foam.lib.json; import foam.lib.parse.*; public class UnicodeParser extends ProxyParser { public UnicodeParser() { super(new Seq(new Whitespace(), new Literal("\\"), new Literal("u"), new Repeat(new HexCharParser(), null, 4, 4), new Whitespace())); } public PStream parse(PStream ps, ParserContext x) { ps = super.parse(ps, x); if ( ps != null ) { Object[] values = (Object[]) ps.value(); // Gets the repeated hex char sequence values = (Object[]) values[3]; char hexChar = (char) ( hexToInt(values[0], 3) + hexToInt(values[1], 2) + hexToInt(values[2], 1) + hexToInt(values[3], 0) ); return ps.setValue(Character.valueOf(hexChar)); } return ps; } public static int hexToInt(Object o, int power) { char c = o.toString().charAt(0); // Converts to upper case if necessary if ( c >= 'a' && c <= 'z' ) { c = Character.toUpperCase(c); } return ( c <= '9' ? c - '0' : 10 + c - 'A' ) * (int) Math.pow(16, power); } }
package gov.nih.nci.caadapter.ui.mapping.V2V3; import edu.knu.medinfo.hl7.v2tree.ElementNode; import edu.knu.medinfo.hl7.v2tree.HL7MessageTreeException; import edu.knu.medinfo.hl7.v2tree.HL7V2MessageTree; import edu.knu.medinfo.hl7.v2tree.MetaDataLoader; import gov.nih.nci.caadapter.common.Message; import gov.nih.nci.caadapter.common.util.Config; import gov.nih.nci.caadapter.common.util.FileUtil; import gov.nih.nci.caadapter.common.util.GeneralUtilities; import gov.nih.nci.caadapter.common.validation.ValidatorResults; import gov.nih.nci.caadapter.ui.common.AbstractMainFrame; import gov.nih.nci.caadapter.ui.common.DefaultSettings; import gov.nih.nci.caadapter.ui.common.message.ValidationMessageDialog; import gov.nih.nci.caadapter.ui.specification.csv.CSVPanel; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; public class V2ConverterToSCSPanel extends JPanel implements ActionListener { /** * Logging constant used to identify source of log entry, that could be later used to create * logging mechanism to uniquely identify the logged class. */ private static final String LOGID = "$RCSfile: V2ConverterToSCSPanel.java,v $"; public static String RCSID = "$Header: /share/content/gforge/caadapter/caadapter/components/userInterface/src/gov/nih/nci/caadapter/ui/mapping/V2V3/V2ConverterToSCSPanel.java,v 1.8 2008-05-30 04:05:39 umkis Exp $"; private JRadioButton jrStrictValidationYes; private JRadioButton jrStrictValidationNo; private JLabel jlStrictValidation; //private JRadioButton jrHL7MessageTypeOnly = new JRadioButton(); //private JRadioButton jrHL7MessageFile = new JRadioButton(); private JRadioButton jrBoth; private JRadioButton jrCSV; private JRadioButton jrSCS; private JRadioButton jrOutputWhole; private JRadioButton jrOutputApparentOnly; private JRadioButton jrOBXSelection; private JRadioButton jrOBXApparentOnly; private JRadioButton jrOBXDataTypeSTOnly; private JRadioButton jrGroupingYes; private JRadioButton jrGroupingNo; private JLabel jlGrouping1; private JLabel jlGrouping2; private JLabel jlHL7VersionLabel; private JComboBox jcHL7Version; private JLabel jlInputMessageTypeLabel; private JTextField jtInputMessageType; private JButton jbInputMessageTypeConfirm; private JButton jbViewErrorMessages; private JTextField jtDataDirectory; private JButton jbDataDirectoryBrowse; private JLabel jlInputFileLabel; private JTextField jtInputFile; private JButton jbInputFileBrowse; private JLabel jlInputSCSLabel; private JTextField jtInputSCSFile; private JButton jbInputSCSFileBrowse; private JLabel jlValidateSCSLabel; private JTextField jtValidateSCSFile; private JButton jbValidateSCSFileBrowse; private JLabel jlMultiMessageNote = new JLabel("The input v2 message file has multi messages."); private JLabel jlInputCSVLabel; private JTextField jtInputCSVFile; private JButton jbInputCSVFileBrowse; private String[] jcbOBXName = {"ST", "TX", "FT", "NA", "MA", "NM", "TS", "DT", "TM", "TN", "XTN", "CE", "CD", "MO", "CP", "SN", "ED" ,"RP" , "AD", "XAD", "PN", "XPN", "CX", "CN", "XCN", "CK", "XON"}; private JCheckBox[] jcbOBXCheck = new JCheckBox[jcbOBXName.length]; private JButton jbGenerate; private JButton jbReset; private JButton jbNext; private JButton jbClose; private JLabel jlPanelTitle; private JPanel optionSourcePanel; private JPanel optionOutputPanel; private JPanel inputSourcePanel; private JPanel inputFilesPanel; private JPanel optionOBXSelection; private JPanel generateButtonPanel; private boolean wasSuccessfullyParsed = false; private boolean foundOBXSegment = false; private boolean wasOBXUsed = false; private boolean buttonNextVisible = false; private boolean buttonCloseVisible = false; private boolean msgTypeOnly = false; private boolean hasMultiMessages = false; private String oneMessage = ""; private File oneMessageFile = null; private String segmentsOBX = ""; private MetaDataLoader v2MetaDataPath = null; private HL7V2MessageTree v2Tree; private V2Converter converter; private java.util.List<String> listOBXDataType = new ArrayList<String>(); private java.util.List<String> listOBXDataType2 = new ArrayList<String>(); private ValidatorResults validatorResults = new ValidatorResults(); private java.util.List<String> errorMessages = new ArrayList<String>(); private String versionDirTag = "version"; private AbstractMainFrame mainFrame = null; private JFrame frame = null; private JDialog dialog = null; private Dimension minimum = new Dimension(540, 740); public V2ConverterToSCSPanel() { try { setupMainPanel(null); } catch(IOException ee) {} } public V2ConverterToSCSPanel(Object v2DataPath) throws IOException { setupMainPanel(v2DataPath); } public V2ConverterToSCSPanel(Object v2DataPath, AbstractMainFrame mFrame) throws IOException { setupMainPanel(v2DataPath); mainFrame = mFrame; } private boolean isValidDataDirectory() { String dataDir = jtDataDirectory.getText(); if ((dataDir == null)||(dataDir.trim().equals(""))) dataDir = ""; dataDir = dataDir.trim(); //System.out.println("CCCC OK 6 : " + dataDir); if (setV2DataPath(dataDir).equals("OK")) return true; jtDataDirectory.setText(""); return false; } private void setInitialState() { if (jcHL7Version.getItemCount() > 0) jcHL7Version.setEnabled(true); else jcHL7Version.setEnabled(false); jtDataDirectory.setEditable(false); jtInputFile.setEditable(false); jbNext.setEnabled(false); jbNext.setVisible(buttonNextVisible); jbClose.setVisible(buttonCloseVisible); jbViewErrorMessages.setEnabled(false); jtInputSCSFile.setEditable(false); jtValidateSCSFile.setEditable(true); jtInputCSVFile.setEditable(true); jtInputSCSFile.setEditable(true); jtInputFile.setText(""); jtInputMessageType.setText(""); jtInputSCSFile.setText(""); jtValidateSCSFile.setText(""); jtInputCSVFile.setText(""); jbReset.setEnabled(true); partlyReset(); setRadioButtonState(); } private void partlyReset() { wasSuccessfullyParsed = false; foundOBXSegment = false; wasOBXUsed = false; msgTypeOnly = false; msgTypeOnly = false; hasMultiMessages = false; oneMessage = ""; oneMessageFile = null; validatorResults = new ValidatorResults(); errorMessages = new ArrayList<String>(); listOBXDataType = new ArrayList<String>(); listOBXDataType2 = new ArrayList<String>(); converter = null; for(int i=0;i<jcbOBXCheck.length;i++) jcbOBXCheck[i].setSelected(false); } private void setRadioButtonState() { boolean cTag = isValidDataDirectory(); jtInputMessageType.setEditable(cTag); jtInputFile.setEnabled(cTag); jtInputMessageType.setEnabled(cTag); jbInputMessageTypeConfirm.setEnabled(cTag); jbInputFileBrowse.setEnabled(cTag); jlInputFileLabel.setEnabled(cTag); jlInputMessageTypeLabel.setEnabled(cTag); jlHL7VersionLabel.setEnabled(cTag); jcHL7Version.setEnabled(cTag); jcHL7Version.setEditable(false); jrStrictValidationYes.setEnabled(cTag); jrStrictValidationNo.setEnabled(cTag); jlStrictValidation.setEnabled(cTag); //String fileN = jtInputSCSFile.getText(); String fileN = jtInputFile.getText(); boolean fTag = (!((fileN==null)||(fileN.trim().equals("")))); jrBoth.setEnabled(wasSuccessfullyParsed&&fTag); jrSCS.setEnabled(wasSuccessfullyParsed); jrCSV.setEnabled(wasSuccessfullyParsed&&fTag); // if (hasMultiMessages) // jrBoth.setEnabled(false); // jrSCS.setEnabled(wasSuccessfullyParsed&&hasMultiMessages); // jrCSV.setEnabled(false); if (fTag) { jrOutputWhole.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrSCS.isEnabled()&&jrSCS.isSelected())); jrOutputApparentOnly.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrSCS.isEnabled()&&jrSCS.isSelected())); jrOBXApparentOnly.setEnabled(wasSuccessfullyParsed&&foundOBXSegment); } else { jrOutputWhole.setSelected(true); jrOutputWhole.setEnabled(false); jrOutputApparentOnly.setEnabled(false); jrOBXApparentOnly.setEnabled(false); if (jrOBXApparentOnly.isSelected()) jrOBXSelection.setSelected(true); } jrGroupingYes.setEnabled(wasSuccessfullyParsed&&foundOBXSegment&&(!(jrOBXDataTypeSTOnly.isEnabled()&&jrOBXDataTypeSTOnly.isSelected()))); jrGroupingNo.setEnabled(wasSuccessfullyParsed&&foundOBXSegment&&(!(jrOBXDataTypeSTOnly.isEnabled()&&jrOBXDataTypeSTOnly.isSelected()))); jlGrouping1.setEnabled(wasSuccessfullyParsed&&foundOBXSegment&&(!(jrOBXDataTypeSTOnly.isEnabled()&&jrOBXDataTypeSTOnly.isSelected()))); jlGrouping2.setEnabled(jlGrouping1.isEnabled()); jrOBXSelection.setEnabled(wasSuccessfullyParsed&&foundOBXSegment); jrOBXDataTypeSTOnly.setEnabled(wasSuccessfullyParsed&&foundOBXSegment&&(!wasOBXUsed)); jlMultiMessageNote.setVisible(hasMultiMessages); if (jrCSV.isSelected()) { jrGroupingYes.setEnabled(false); jrGroupingNo.setEnabled(false); jlGrouping1.setEnabled(false); jlGrouping2.setEnabled(jlGrouping1.isEnabled()); jrOBXApparentOnly.setEnabled(false); jrOBXSelection.setEnabled(false); jrOBXDataTypeSTOnly.setEnabled(false); } //msgTypeOnly // jlHL7VersionLabel.setEnabled(jrHL7MessageTypeOnly.isSelected()); // jcHL7Version.setEnabled(jrHL7MessageTypeOnly.isSelected()); // jtInputMessageType.setEnabled(jrHL7MessageTypeOnly.isSelected()); // jtInputMessageType.setEditable(jrHL7MessageTypeOnly.isSelected()); // jbInputMessageTypeConfirm.setEnabled(jrHL7MessageTypeOnly.isSelected()); // jtInputFile.setEnabled(jrHL7MessageFile.isSelected()); // jbInputFileBrowse.setEnabled(jrHL7MessageFile.isSelected()); jlValidateSCSLabel.setEnabled(jrCSV.isEnabled()&&jrCSV.isSelected()); jtValidateSCSFile.setEnabled(jrCSV.isEnabled()&&jrCSV.isSelected()); jbValidateSCSFileBrowse.setEnabled(jrCSV.isEnabled()&&jrCSV.isSelected()); jlInputSCSLabel.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrSCS.isEnabled()&&jrSCS.isSelected())); jtInputSCSFile.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrSCS.isEnabled()&&jrSCS.isSelected())); jbInputSCSFileBrowse.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrSCS.isEnabled()&&jrSCS.isSelected())); jlInputCSVLabel.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrCSV.isEnabled()&&jrCSV.isSelected())); jtInputCSVFile.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrCSV.isEnabled()&&jrCSV.isSelected())); jbInputCSVFileBrowse.setEnabled((jrBoth.isEnabled()&&jrBoth.isSelected())||(jrCSV.isEnabled()&&jrCSV.isSelected())); if (!jtInputFile.isEnabled()) jtInputFile.setText(""); if (!jtInputMessageType.isEnabled()) jtInputMessageType.setText(""); if (!jtInputCSVFile.isEnabled()) jtInputCSVFile.setText(""); if (!jtInputSCSFile.isEnabled()) jtInputSCSFile.setText(""); if (!jtValidateSCSFile.isEnabled()) jtValidateSCSFile.setText(""); for(int i=0;i<jcbOBXCheck.length;i++) { jcbOBXCheck[i].setEnabled((jrOBXSelection.isEnabled())&&(jrOBXSelection.isSelected())); //jcbOBXCheck[i].setSelected(false); } for(int j=0;j<listOBXDataType.size();j++) { for(int i=0;i<jcbOBXName.length;i++) { if (jcbOBXName[i].equals(listOBXDataType.get(j))) { jcbOBXCheck[i].setSelected(true); } } } jbGenerate.setEnabled(wasSuccessfullyParsed); } public void actionPerformed(ActionEvent e) { if ((v2MetaDataPath == null)&&(e.getSource() != jbDataDirectoryBrowse)) { JOptionPane.showMessageDialog(this, "First of all, you MUST set v2 meta resource.", "No v2 meta source", JOptionPane.ERROR_MESSAGE); return; } if (e.getSource() == jbDataDirectoryBrowse) { doPressDataDirectoryBrowse(); } if (e.getSource() == jbReset) { setInitialState(); } if (e.getSource() == jbClose) { if (frame != null) frame.dispose(); if (dialog != null) dialog.dispose(); } if (e.getSource() == jbGenerate) { doPressGenerate(); if (jbNext.isVisible()) jbNext.setEnabled(true); } if (e.getSource() == jbNext) { doPressNext(); } if (e.getSource() == jbInputFileBrowse) { doPressHL7MessageFileBrowse(); } if (e.getSource() == jbInputMessageTypeConfirm) { doPressHL7MessageTypeConfirm(); } if (e.getSource() == jbViewErrorMessages) { doPressViewErrorMessages(); } if ((e.getSource() == jbInputSCSFileBrowse)|| (e.getSource() == jbInputCSVFileBrowse)|| (e.getSource() == jbValidateSCSFileBrowse)) { doPressSCSOrCSVFileBrowse((JButton) e.getSource()); } // if (e.getSource() == jrHL7MessageFile) // String st = jtInputMessageType.getText(); // if (st == null) st = ""; // if ((wasSuccessfullyParsed)&&((st.trim().length() == 7)&&(st.substring(3,4).equals("^")))) // jtInputMessageType.setText(""); // partlyReset(); // jrOutputApparentOnly.setSelected(true); // jrOBXApparentOnly.setSelected(true); // if (e.getSource() == jrHL7MessageTypeOnly) // String st = jtInputFile.getText(); // if (st == null) st = ""; // if ((wasSuccessfullyParsed)&&(st.trim().length() > 7)) // jtInputFile.setText(""); // partlyReset(); // jrOutputApparentOnly.setSelected(true); // jrOBXApparentOnly.setSelected(true); if (e.getSource() == jrOBXApparentOnly) { } if (e.getSource() == jrOBXDataTypeSTOnly) { for(int i=0;i<jcbOBXCheck.length;i++) jcbOBXCheck[i].setSelected(false); jcbOBXCheck[0].setSelected(true); } if (e.getSource() instanceof JCheckBox) { int idx = -1; for(int i=0;i<jcbOBXCheck.length;i++) if (e.getSource() == jcbOBXCheck[i]) idx = i; if (idx < 0) return; boolean cTag = false; for(int j=0;j<listOBXDataType.size();j++) if (jcbOBXName[idx].equals(listOBXDataType.get(j))) cTag = true; if (cTag) { JOptionPane.showMessageDialog(this, "This data type can not set 'Unselected' because of already being included in the source message", "Ready set Data Type",JOptionPane.WARNING_MESSAGE); jcbOBXCheck[idx].setSelected(true); return; } } if (e.getSource() instanceof JRadioButton) setRadioButtonState(); } private String setV2DataPath(Object v2DataPath) { HL7V2MessageTree mt = null; boolean cTag = false; String msg = null; try { if (v2DataPath instanceof String) { String c = (String)v2DataPath; if (c.trim().equals("")) v2DataPath = null; //System.out.println("CCCC OK 1 : " + c); } if (v2DataPath == null) { MetaDataLoader loader = FileUtil.getV2ResourceMetaDataLoader(); if (loader == null) throw new HL7MessageTreeException("V2 Meta Data Loader creation failure"); else mt = new HL7V2MessageTree(loader); //System.out.println("CCCC OK 2 : ");// + loader.getPath()); cTag = true; } else { mt = new HL7V2MessageTree(v2DataPath); //System.out.println("CCCC OK 3 : "); cTag = true; } // if (v2DataPath instanceof String) // File dir = new File((String)v2DataPath); // if (dir.isDirectory()) // for (File sDir:dir.listFiles()) // if (!sDir.isDirectory()) continue; // try // mt.setVersion(sDir.getName()); // cTag = true; // catch(HL7MessageTreeException he) // msg = he.getMessage(); // continue; // break; } catch(HL7MessageTreeException he) { msg = he.getMessage(); } catch(Exception ee) { msg = ee.getMessage(); } if (cTag) { v2MetaDataPath = mt.getMetaDataLoader();//v2DataPath; //System.out.println("CCCC OK : " + v2MetaDataPath.getPath()); return "OK"; } //System.out.println("CCCC err : " + msg); return msg; } private void setupMainPanel(Object v2DataPathObject) throws IOException { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } boolean cTag = false; if ((v2DataPathObject != null)&&(v2DataPathObject instanceof String)) { String v2DataPath = (String) v2DataPathObject; if (v2DataPath.trim().equals("")) { v2DataPathObject = null; cTag = true; } else { v2DataPath = v2DataPath.trim(); MetaDataLoader loader = FileUtil.getV2ResourceMetaDataLoader(v2DataPath); if (loader != null) v2MetaDataPath = loader; else throw new IOException("Invalid V2 meta data directory or zip file : " + v2DataPath); // jcHL7Version = new JComboBox(); // jtDataDirectory = new JTextField(); // jtDataDirectory.setText(v2DataPath); // if (setV2DataPath(v2DataPath).equals("OK")) setHL7VersionComboBox(v2DataPath); // else throw new IOException("Invalid V2 meta data directory or zip file : " + v2DataPath); } } else cTag = true; if(cTag) { if (v2DataPathObject == null) { v2MetaDataPath = null; //MetaDataLoader loader = FileUtil.getV2ResourceMetaDataLoader(); //if (loader == null) throw new IOException("V2 Meta Data Loader creation failure"); //v2DataPathObject = loader; } else if (v2DataPathObject instanceof MetaDataLoader) { v2MetaDataPath = (MetaDataLoader) v2DataPathObject; } else throw new IOException("Invalid instance of v2 meta object : "); } jcHL7Version = new JComboBox(); jtDataDirectory = new JTextField(); if (v2MetaDataPath == null) { jtDataDirectory.setText(""); setHL7VersionComboBox(null); } else { jtDataDirectory.setText(v2MetaDataPath.getPath()); setHL7VersionComboBox(v2MetaDataPath); } setupMainPanel(); } private void setupMainPanel() { //jlPanelTitle = new JLabel("V2 Message Converter Main", JLabel.CENTER); jlPanelTitle = new JLabel("", JLabel.CENTER); optionSourcePanel = wrappingBorder("V2 Message Source" ,optionPanel_MessageOrType()); optionOutputPanel = wrappingBorder("Output File Option", constructOutputOptionPanel()); //inputSourcePanel = wrappingBorder("Input Source", inputV2Source()); inputFilesPanel = wrappingBorder("Output Files", inputOutputFiles()); optionOBXSelection = wrappingBorder("OBX Data Type Selection", optionOBXDataTypes()); generateButtonPanel = generateButtonPanel(); //this.setLayout(new GridLayout(0, 1)); this.setLayout(new BorderLayout()); constructMainPanel(); } private void constructMainPanel() { JPanel center = new JPanel(new BorderLayout()); center.add(new JLabel(""), BorderLayout.WEST); center.add(optionOutputPanel, BorderLayout.CENTER); center.add(new JLabel(""), BorderLayout.EAST); JPanel top = new JPanel(new BorderLayout()); //top.add(inputSourcePanel, BorderLayout.NORTH); top.add(center, BorderLayout.CENTER); top.add(inputFilesPanel, BorderLayout.SOUTH); JPanel mid = new JPanel(new BorderLayout()); mid.add(optionSourcePanel, BorderLayout.NORTH); mid.add(top, BorderLayout.CENTER); mid.add(optionOBXSelection, BorderLayout.SOUTH); setLayout(new BorderLayout(10, 10)); JPanel bottom = new JPanel(new BorderLayout()); bottom.add(wrappingBorder("V2 Meta Source" ,panel_DataDirectory()), BorderLayout.NORTH); bottom.add(mid, BorderLayout.CENTER); bottom.add(generateButtonPanel, BorderLayout.SOUTH); add(jlPanelTitle, BorderLayout.NORTH); add(bottom, BorderLayout.CENTER); //add(new JPanel(), BorderLayout.SOUTH); add(new JLabel(" "), BorderLayout.WEST); add(new JLabel(" "), BorderLayout.EAST); //optionOBXSelection.setEnabled(false); setInitialState(); this.setMinimumSize(getMinimumSize()); } private JPanel wrappingBorder(String borderTitle, JPanel aPanel) { //Border paneEdge = BorderFactory.createEmptyBorder(10,10,10,10); JPanel titledBorders = new JPanel(new BorderLayout()); //JPanel titledBorders = new JPanel(new GridLayout(1, 0)); //titledBorders.setBorder(paneEdge); TitledBorder titled = BorderFactory.createTitledBorder(borderTitle); titledBorders.add(aPanel, BorderLayout.CENTER); titledBorders.setBorder(titled); //titledBorders.add(Box.createRigidArea(new Dimension(0, 10))); return titledBorders; } private Object[] setupRadioButtonPanel(JRadioButton radioButton01, String buttonLabel01, String buttonCommand01, boolean selected01, JRadioButton radioButton02, String buttonLabel02, String buttonCommand02, boolean selected02, boolean vertical) { return setupRadioButtonPanel(radioButton01, buttonLabel01, buttonCommand01, selected01, radioButton02, buttonLabel02, buttonCommand02, selected02, null, null, null, false, vertical); } private Object[] setupRadioButtonPanel(JRadioButton radioButton01, String buttonLabel01, String buttonCommand01, boolean selected01, JRadioButton radioButton02, String buttonLabel02, String buttonCommand02, boolean selected02, JRadioButton radioButton03, String buttonLabel03, String buttonCommand03, boolean selected03, boolean vertical) { JPanel aPanel = new JPanel(new BorderLayout()); JPanel bPanel = new JPanel(new BorderLayout()); radioButton01 = new JRadioButton(buttonLabel01); radioButton01.setActionCommand(buttonCommand01); radioButton01.setSelected(selected01); radioButton02 = new JRadioButton(buttonLabel02); radioButton02.setActionCommand(buttonCommand02); radioButton02.setSelected(selected02); if (buttonLabel03 != null) { radioButton03 = new JRadioButton(buttonLabel03); radioButton03.setActionCommand(buttonCommand03); radioButton03.setSelected(false); } ButtonGroup group = new ButtonGroup(); group.add(radioButton01); group.add(radioButton02); if (buttonLabel03 != null) group.add(radioButton03); radioButton01.addActionListener(this); radioButton02.addActionListener(this); if (buttonLabel03 != null) radioButton03.addActionListener(this); if (buttonLabel03 == null) { if (vertical) { aPanel.add(radioButton01, BorderLayout.NORTH); aPanel.add(radioButton02, BorderLayout.CENTER); } else { aPanel.add(radioButton01, BorderLayout.WEST); aPanel.add(radioButton02, BorderLayout.CENTER); } } else { aPanel.add(radioButton01, BorderLayout.WEST); JPanel cPanel = new JPanel(new BorderLayout()); cPanel.add(radioButton02, BorderLayout.WEST); cPanel.add(radioButton03, BorderLayout.CENTER); aPanel.add(cPanel, BorderLayout.CENTER); } bPanel.add(aPanel, BorderLayout.NORTH); Object[] out = new Object[4]; out[0] = bPanel; out[1] = radioButton01; out[2] = radioButton02; if (buttonLabel03 != null) out[3] = radioButton03; return out; } private JPanel panel_DataDirectory() { JPanel bPanel = new JPanel(new BorderLayout()); //bPanel.add(jrHL7MessageTypeOnly, BorderLayout.WEST); Object[] out1 = inputFileNameCommon("V2 Meta Dir or Zip ", jtDataDirectory, jbDataDirectoryBrowse, "Browse", "Browse.."); bPanel.add((JPanel)out1[0], BorderLayout.CENTER); jtDataDirectory =(JTextField) out1[2]; jbDataDirectoryBrowse = (JButton) out1[3]; if (v2MetaDataPath == null) jtDataDirectory.setText(""); else jtDataDirectory.setText(v2MetaDataPath.getPath()); JPanel cPanel = new JPanel(new BorderLayout()); cPanel.add(bPanel, BorderLayout.CENTER); if (jcHL7Version == null) jcHL7Version = new JComboBox(); JPanel ePanel = new JPanel(new BorderLayout()); jlHL7VersionLabel = new JLabel(" Target Version ", JLabel.LEFT); ePanel.add(jlHL7VersionLabel, BorderLayout.WEST); ePanel.add(jcHL7Version, BorderLayout.CENTER); cPanel.add(ePanel, BorderLayout.SOUTH); return cPanel; } private JPanel optionPanel_MessageOrType() { // Object[] out = setupRadioButtonPanel(jrHL7MessageFile, "Message File", "File", true, // jrHL7MessageTypeOnly, "Message Type", "Type", false, false); // ((JPanel)out[0]).removeAll(); // jrHL7MessageFile = (JRadioButton) out[1]; // jrHL7MessageTypeOnly = (JRadioButton) out[2]; JPanel bPanel = new JPanel(new BorderLayout()); bPanel.add((new JLabel("")), BorderLayout.WEST); Object[] out1 = inputFileNameCommon("Message Type", jtInputMessageType, jbInputMessageTypeConfirm, "Start V2 Parsing", "Start V2 Parsing"); bPanel.add((JPanel)out1[0], BorderLayout.CENTER); jlInputMessageTypeLabel = (JLabel) out1[1]; jtInputMessageType =(JTextField) out1[2]; jbInputMessageTypeConfirm = (JButton) out1[3]; JPanel cPanel = new JPanel(new BorderLayout()); cPanel.add(bPanel, BorderLayout.CENTER); // File aFile = new File(v2MetaDataPath); // File[] files = aFile.listFiles(); // java.util.List<String> listVersionDir = new ArrayList<String>(); // jcHL7Version = new JComboBox(); // for (int i=0;i<files.length;i++) // File file = files[i]; // if(!file.isDirectory()) continue; // String dirName = file.getName(); // //System.out.println("VersionsXX = > " + dirName);// + " : " + dirName.substring(versionDirTag.length())); // if (dirName.toLowerCase().startsWith(versionDirTag.toLowerCase())) // listVersionDir.add(dirName.substring(versionDirTag.length())); // //System.out.println("Versions = > " + dirName + " : " + dirName.substring(versionDirTag.length())); // countV2Versions = listVersionDir.size(); // jcHL7Version = new JComboBox(listVersionDir.toArray()); // for(int i=0;i<jcHL7Version.getItemCount();i++) // String ver = (String) jcHL7Version.getItemAt(i); // if (ver.indexOf("2.4") >= 0) jcHL7Version.setSelectedIndex(i); // JPanel ePanel = new JPanel(new BorderLayout()); // String ss = ""; // if (listVersionDir.size() > 1) ss = "s"; // jlHL7VersionLabel = new JLabel(" Available Version"+ss+" ", JLabel.LEFT); // ePanel.add(jlHL7VersionLabel, BorderLayout.WEST); // ePanel.add(jcHL7Version, BorderLayout.CENTER); // cPanel.add(ePanel, BorderLayout.SOUTH); cPanel.add(optionStrictValidation(), BorderLayout.SOUTH); JPanel dPanel = new JPanel(new BorderLayout()); dPanel.add((new JLabel()), BorderLayout.WEST); Object[] out2 = inputFileNameCommon("Message File", jtInputFile, jbInputFileBrowse, "Browse..", "Browse"); dPanel.add((JPanel) out2[0], BorderLayout.CENTER); JPanel fPanel = new JPanel(new BorderLayout()); jlMultiMessageNote = new JLabel("This input v2 message file has multi v2 messages."); jlMultiMessageNote.setHorizontalAlignment(JLabel.TRAILING); fPanel.add(jlMultiMessageNote, BorderLayout.EAST); fPanel.add(new JLabel(""), BorderLayout.WEST); dPanel.add(fPanel, BorderLayout.NORTH); jlInputFileLabel = (JLabel) out2[1]; jtInputFile = (JTextField) out2[2]; jbInputFileBrowse = (JButton) out2[3]; cPanel.add(dPanel, BorderLayout.NORTH); return cPanel; } private JPanel constructOutputOptionPanel() { //Border paneEdge = BorderFactory.createEmptyBorder(0,10,10,10); JPanel aPanel = new JPanel(new BorderLayout()); JPanel bPanel = new JPanel(new BorderLayout()); bPanel.add(optionPanel_OutputFiles(), BorderLayout.CENTER); bPanel.add(new JLabel(" "), BorderLayout.WEST); aPanel.add(bPanel, BorderLayout.CENTER); aPanel.add(wrappingBorder("SCS File Option", optionPanel_SCSOption_WholeOrApparent()),BorderLayout.SOUTH); return aPanel; } private JPanel optionPanel_OutputFiles() { Object[] out = setupRadioButtonPanel(jrBoth, "Both", "Both", false, jrSCS, "SCS", "SCS", true, jrCSV, "CSV", "CSV", true, false); jrBoth = (JRadioButton) out[1]; jrSCS = (JRadioButton) out[2]; jrCSV = (JRadioButton) out[3]; JPanel north= (JPanel) out[0]; Object[] out2 = inputFileNameCommon(" Validating SCS for this CSV ", jtValidateSCSFile, jbValidateSCSFileBrowse, "Browse..", "Browse"); JPanel north2 = new JPanel(new BorderLayout()); north2.add((JPanel) out2[0], BorderLayout.NORTH); jlValidateSCSLabel = (JLabel) out2[1]; jtValidateSCSFile = (JTextField) out2[2]; jbValidateSCSFileBrowse = (JButton) out2[3]; north.add(north2, BorderLayout.CENTER); return north; } private JPanel optionPanel_SCSOption_WholeOrApparent() { Object[] out = setupRadioButtonPanel(jrOutputApparentOnly, "Apparent Segments only ", "Apparent", true, jrOutputWhole, "Whole Segments of this message type", "Whole", false, false); jrOutputApparentOnly = (JRadioButton) out[1]; jrOutputWhole = (JRadioButton) out[2]; return (JPanel) out[0]; } private Object[] inputFileNameCommon(String label, JTextField textField, JButton button, String buttonLabel, String buttonCommand) { JPanel aPanel = new JPanel(new BorderLayout()); JLabel jl = new JLabel(label, JLabel.LEFT); aPanel.add(jl, BorderLayout.WEST); textField = new JTextField(); aPanel.add(textField, BorderLayout.CENTER); button = new JButton(buttonLabel); button.setActionCommand(buttonCommand); button.addActionListener(this); aPanel.add(button, BorderLayout.EAST); Object[] out = new Object[4]; out[0] = aPanel; out[1] = jl; out[2] = textField; out[3] = button; return out; } private JPanel inputOutputFiles() { //JPanel aPanel = new JPanel(new GridLayout(0, 1)); JPanel aPanel = new JPanel(new BorderLayout()); Object[] out = inputFileNameCommon("SCS File ", jtInputSCSFile, jbInputSCSFileBrowse, "Browse..", "Browse"); aPanel.add((JPanel) out[0], BorderLayout.NORTH); jlInputSCSLabel = (JLabel) out[1]; jtInputSCSFile = (JTextField) out[2]; jbInputSCSFileBrowse = (JButton) out[3]; out = inputFileNameCommon("CSV File ", jtInputCSVFile, jbInputCSVFileBrowse, "Browse..", "Browse"); aPanel.add((JPanel) out[0], BorderLayout.CENTER); jlInputCSVLabel = (JLabel) out[1]; jtInputCSVFile = (JTextField) out[2]; jbInputCSVFileBrowse = (JButton) out[3]; //aPanel.add(inputFileNameCommon("CSV File ", jtInputCSVFile, jbInputCSVFileBrowse, "Browse..", "Browse"), BorderLayout.CENTER); return aPanel; } private JPanel optionStrictValidation() { Object[] out = setupRadioButtonPanel(jrStrictValidationYes, "Yes", "Yes", false, jrStrictValidationNo, "No", "No", true, false); jlStrictValidation = new JLabel("Strict Validation?", JLabel.LEFT); JPanel north1 = new JPanel(new BorderLayout()); north1.add(jlStrictValidation, BorderLayout.WEST); north1.add((JPanel)out[0], BorderLayout.CENTER); jbViewErrorMessages = new JButton("View Error Messages"); jbViewErrorMessages.addActionListener(this); north1.add(jbViewErrorMessages, BorderLayout.EAST); jrStrictValidationYes = (JRadioButton) out[1]; jrStrictValidationNo = (JRadioButton) out[2]; return north1; } private JPanel optionOBXDataTypes() { Object[] out = setupRadioButtonPanel(jrOBXApparentOnly, "Apparent Data Type only", "ApparentDT", true, jrOBXSelection, "Selecting Data Types", "Selecting", false, jrOBXDataTypeSTOnly, "ST Data Type only", "STOnly", false, false); JPanel north = wrappingBorder("OBX Option", (JPanel)out[0] ); jrOBXApparentOnly = (JRadioButton) out[1]; jrOBXSelection = (JRadioButton) out[2]; jrOBXDataTypeSTOnly = (JRadioButton) out[3]; out = setupRadioButtonPanel(jrGroupingYes, "Yes", "Yes", false, jrGroupingNo, "No", "No", true, false); jlGrouping1 = new JLabel("Want grouping? ", JLabel.LEFT); jlGrouping2 = new JLabel(" (If Yes, ST, TX and FT will be simplfied into ST.)", JLabel.LEFT); JPanel north1 = new JPanel(new FlowLayout(FlowLayout.LEADING)); north1.add(jlGrouping1);//, BorderLayout.WEST); //JPanel north12 = new JPanel(new BorderLayout()); north1.add((JPanel)out[0]);//, BorderLayout.CENTER); north1.add(jlGrouping2);//, BorderLayout.WEST); //north1.add(north12, BorderLayout.EAST); JPanel north2 = wrappingBorder("Grouping", north1); jrGroupingYes = (JRadioButton) out[1]; jrGroupingNo = (JRadioButton) out[2]; JPanel selectionOBX = new JPanel(new GridBagLayout()); int insetN = 1; Insets insets = new Insets(insetN, insetN, insetN, insetN); for(int i=0;i<jcbOBXName.length;i++) { String obxName = ""; if (jcbOBXName[i].length() == 2) obxName = jcbOBXName[i] + " "; else obxName = jcbOBXName[i]; jcbOBXCheck[i] = new JCheckBox(obxName); jcbOBXCheck[i].setSelected(false); jcbOBXCheck[i].setEnabled(false); jcbOBXCheck[i].addActionListener(this); int modeBase = 9; if ((i+1) == modeBase) selectionOBX.add(jcbOBXCheck[i], new GridBagConstraints((i % modeBase), (i / modeBase), 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0)); else selectionOBX.add(jcbOBXCheck[i], new GridBagConstraints((i % modeBase), (i / modeBase), 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0)); } //JScrollPane jsp = new JScrollPane(); //jsp.add(selectionOBX); JPanel obxMain = new JPanel(new BorderLayout()); obxMain.add(north, BorderLayout.NORTH); obxMain.add(north2, BorderLayout.CENTER); obxMain.add(selectionOBX, BorderLayout.SOUTH); return obxMain; } private JPanel generateButtonPanel() { jbGenerate = new JButton("Generate"); jbGenerate.setActionCommand("Generate"); jbGenerate.addActionListener(this); jbGenerate.setEnabled(true); jbReset = new JButton("Reset"); jbReset.setActionCommand("Reset"); jbReset.addActionListener(this); jbReset.setEnabled(true); jbNext = new JButton("Next"); jbNext.setActionCommand("Next"); jbNext.addActionListener(this); jbNext.setEnabled(true); jbClose = new JButton("Close"); jbClose.setActionCommand("Close"); jbClose.addActionListener(this); jbClose.setEnabled(true); JPanel east = new JPanel(new BorderLayout()); east.add(jbGenerate, BorderLayout.WEST); east.add(jbClose, BorderLayout.EAST); east.add(new JLabel(" "), BorderLayout.CENTER); JPanel west = new JPanel(new BorderLayout()); west.add(jbNext, BorderLayout.WEST); west.add(jbReset, BorderLayout.EAST); west.add(new JLabel(" "), BorderLayout.CENTER); JPanel south = new JPanel(new BorderLayout()); south.add(new JLabel(" "), BorderLayout.CENTER); south.add(east, BorderLayout.EAST); south.add(west, BorderLayout.WEST); return south; //JPanel aPanel = new JPanel(new GridLayout(1, 0)); //aPanel.add(jbGenerate); //aPanel.add(jbReset); //return aPanel; } private void doPressGenerate() { if (hasMultiMessages) doPressGenerateMultiMessage(); else doPressGenerateSingleMessage(); } private void doPressGenerateMultiMessage() { String fileSCS = jtInputSCSFile.getText(); String fileCSV = jtInputCSVFile.getText(); String fileSCSValidate = jtValidateSCSFile.getText(); if (fileSCS == null) fileSCS = ""; if (fileCSV == null) fileCSV = ""; if (fileSCSValidate == null) fileSCSValidate = ""; //System.out.println("DDDDDD : start"); if ((jrBoth.isSelected())||(jrSCS.isSelected())) { if (!doPressGenerateSingleMessage(v2Tree, fileSCS, "", "", !jrSCS.isSelected())) return; //System.out.println("DDDDDD : OK"); } if ((jrBoth.isSelected())||(jrCSV.isSelected())) { String scsVal = ""; if (jrBoth.isSelected()) scsVal = fileSCS; if (jrCSV.isSelected()) scsVal = fileSCSValidate; boolean strict = jrStrictValidationYes.isSelected(); String mType = jtInputMessageType.getText(); if (mType == null) mType = ""; mType = mType.trim(); String versionS = ((String)jcHL7Version.getSelectedItem()).trim(); ConvertFromV2ToCSV con = new ConvertFromV2ToCSV(v2MetaDataPath, jtInputFile.getText().trim(), mType, versionS, fileCSV, scsVal, strict); JOptionPane.showMessageDialog(this, con.getMessage(), con.getMessageTitle(), con.getErrorLevel()); } } public java.util.List<String> getErrorMessages() { return errorMessages; } private void doPressGenerateSingleMessage() { String fileSCS = jtInputSCSFile.getText(); String fileCSV = jtInputCSVFile.getText(); String fileSCSValidate = jtValidateSCSFile.getText(); if (fileSCS == null) fileSCS = ""; if (fileCSV == null) fileCSV = ""; if (fileSCSValidate == null) fileSCSValidate = ""; doPressGenerateSingleMessage(v2Tree, fileSCS, fileCSV, fileSCSValidate, false); } public boolean doPressGenerateSingleMessage(HL7V2MessageTree tree, String fileSCS, String fileCSV, String fileSCSValidate, boolean mute) { try { converter = new V2Converter(tree); } catch(HL7MessageTreeException he) { JOptionPane.showMessageDialog(this, he.getMessage(), "V2 Converter initialize error!",JOptionPane.ERROR_MESSAGE); return false; } java.util.List<String> listDataTypeOfOBX = new ArrayList<String>(); for(int i=0;i<jcbOBXCheck.length;i++) { if (jcbOBXCheck[i].isSelected()) { listDataTypeOfOBX.add(jcbOBXName[i].trim()); } } converter.process(fileSCS, fileCSV, jrOutputApparentOnly.isSelected(), jrGroupingYes.isSelected(), listDataTypeOfOBX, fileSCSValidate); if (converter.wasSuccessful()) { boolean validateResultSCS = true; boolean validateResultCSV = true; if ((!fileSCS.equals(""))&&(!converter.isSCSValid())) validateResultSCS = false; if ((!fileCSV.equals(""))&&(!converter.isCSVValid())) validateResultCSV = false; if ((validateResultSCS)&&(validateResultCSV)) { if (!mute) JOptionPane.showMessageDialog(this, "V2 Converter Process is successfully Complete!", "V2 Converter Process Complete!",JOptionPane.INFORMATION_MESSAGE); } else { java.util.List<Message> messages = converter.getValidationResults().getAllMessages(); if (messages.size() > 0) { errorMessages.add(" for (Message message:messages) errorMessages.add(message.toString()); if (mute) { validatorResults.addValidatorResults(converter.getValidationResults()); } else { ValidationMessageDialog dialogVal = null; if (frame != null) dialogVal = new ValidationMessageDialog(frame, "V2 Converter Validation Result", true); else if (dialog != null) dialogVal = new ValidationMessageDialog(dialog, "V2 Converter Validation Result", true); else { return false; } validatorResults.addValidatorResults(converter.getValidationResults()); dialogVal.setValidatorResults(validatorResults); dialogVal.setVisible(true); validatorResults = new ValidatorResults(); } } } } else { String errMsg = ""; if(converter.getErrorMessage().trim().equals("")) errMsg = "null message"; else errMsg = converter.getErrorMessage(); validatorResults = GeneralUtilities.addValidatorMessage(validatorResults, errMsg); errorMessages.add(" if (!mute) JOptionPane.showMessageDialog(this, errMsg, "V2 Converter Process error!!",JOptionPane.ERROR_MESSAGE); return false; } return true; } private void doPressDataDirectoryBrowse() { if (jcHL7Version.getItemCount() > 0) jcHL7Version.setEnabled(true); else jcHL7Version.setEnabled(false); String dataDir = jtDataDirectory.getText(); if ((dataDir == null)||(dataDir.trim().equals(""))) dataDir = ""; File fileD = DefaultSettings.getUserInputOfFileFromGUI(this, //FileUtil.getUIWorkingDirectoryPath(), dataDir, "*", "Finding v2 Meta Data Directory", false, false);//Config.OPEN_DIALOG_TITLE_FOR_HL7_V3_MESSAGE_FILE.replace("3", "2"), false, false); if (fileD == null) return; if (!fileD.isDirectory()) { if (!fileD.getName().toLowerCase().endsWith(".zip")) { JOptionPane.showMessageDialog(this, "This is Neither a directory nor a zip file : " + fileD.getAbsolutePath(), "Meta data directory finding error!",JOptionPane.ERROR_MESSAGE); return; } } //MetaDataLoader loader = FileUtil.getV2ResourceMetaDataLoader(dataDir); MetaDataLoader loader = FileUtil.getV2ResourceMetaDataLoader(fileD.getAbsolutePath()); if (loader == null) { JOptionPane.showMessageDialog(this, "This is Neither a V2 meta directory nor a V2 Meta zip file : " + fileD.getAbsolutePath(), "Meta data directory finding error!",JOptionPane.ERROR_MESSAGE); return; } v2MetaDataPath = loader; if (setHL7VersionComboBox(loader)) { //System.out.println("CCCC OK 7 : " + v2MetaDataPath.getPath() + ", " + dataDir); jtDataDirectory.setText(v2MetaDataPath.getPath()); setRadioButtonState(); } } private boolean setHL7VersionComboBox(MetaDataLoader loader) { jcHL7Version.removeAllItems(); if (loader == null) return true; String[] listVersionDir = loader.getVersions(); for (String dir:listVersionDir) jcHL7Version.addItem(dir); //jcHL7Version = new JComboBox(listVersionDir.toArray()); for(int i=0;i<jcHL7Version.getItemCount();i++) { String ver = (String) jcHL7Version.getItemAt(i); if (ver.indexOf("2.4") >= 0) jcHL7Version.setSelectedIndex(i); } return true; } // private boolean setHL7VersionComboBox(String pathValue) // File fileD = new File(pathValue); // if ((!fileD.exists())||(!fileD.isDirectory())) return false; // pathValue = fileD.getAbsolutePath(); // pathValue = pathValue.trim(); // if (setV2DataPath(pathValue).equals("OK")) {} //jtDataDirectory.setText(v2MetaDataPath); // else // JOptionPane.showMessageDialog(this, "This is NOT a V2 Meta data directory : " + fileD.getAbsolutePath(), "Meta data directory finding error!",JOptionPane.ERROR_MESSAGE); // return false; // jcHL7Version.setEnabled(true); // jcHL7Version.removeAllItems(); // String fileName = v2MetaDataPath.getPath(); // File aFile = new File(fileName); // java.util.List<String> listVersionDir = new ArrayList<String>(); // if (aFile.isDirectory()) // File[] files = aFile.listFiles(); // for (int i=0;i<files.length;i++) // File file = files[i]; // if (!file.isDirectory()) continue; // String dirName = file.getName(); // //System.out.println("VersionsXX = > " + dirName);// + " : " + dirName.substring(versionDirTag.length())); // if (dirName.toLowerCase().startsWith(versionDirTag.toLowerCase())) // listVersionDir.add(dirName.substring(versionDirTag.length())); // //System.out.println("Versions = > " + dirName + " : " + dirName.substring(versionDirTag.length())); // else // if (!fileName.toLowerCase().endsWith(".zip")) // JOptionPane.showMessageDialog(this, "Unidentified meta directory or file : " + fileName, "Meta data directory finding error!",JOptionPane.ERROR_MESSAGE); // return false; // java.util.List<String> keys = v2MetaDataPath.getMetaKeys(); // for(String key:keys) // int idx = key.toLowerCase().indexOf("version"); // if (idx < 0) continue; // key = key.substring(idx); // idx = key.indexOf("/"); // if (idx < 0) continue; // String vers = key.substring(0, idx); // vers = vers.trim(); // boolean cTag = false; // for (String dir:listVersionDir) // dir = dir.trim(); // if (dir.equalsIgnoreCase(vers)) cTag = true; // if (!cTag) listVersionDir.add(vers); // //countV2Versions = listVersionDir.size(); // for (String dir:listVersionDir) jcHL7Version.addItem(dir); // //jcHL7Version = new JComboBox(listVersionDir.toArray()); // for(int i=0;i<jcHL7Version.getItemCount();i++) // String ver = (String) jcHL7Version.getItemAt(i); // if (ver.indexOf("2.4") >= 0) jcHL7Version.setSelectedIndex(i); // return true; private void doPressHL7MessageFileBrowse() { File file = DefaultSettings.getUserInputOfFileFromGUI(this, //FileUtil.getUIWorkingDirectoryPath(), "*.*", Config.OPEN_DIALOG_TITLE_FOR_HL7_V3_MESSAGE_FILE.replace("3", "2"), false, false); if (file == null) return; String pathValue = file.getAbsolutePath(); if (organizeInputFile(pathValue)) { jtInputFile.setText(pathValue); setRadioButtonState(); } } private void doPressSCSOrCSVFileBrowse(JButton button) { String extension = ""; if (button == jbInputSCSFileBrowse) extension = Config.CSV_METADATA_FILE_DEFAULT_EXTENTION; else if (button == jbInputCSVFileBrowse) extension = Config.CSV_DATA_FILE_DEFAULT_EXTENSTION; else if (button == jbValidateSCSFileBrowse) extension = Config.CSV_METADATA_FILE_DEFAULT_EXTENTION; /* JFileChooser chooser = new JFileChooser(new File(FileUtil.getWorkingDirPath())); chooser.setFileFilter(new SingleFileFilter(extension)); int returnVal = chooser.showOpenDialog(this); String pathValue = ""; if(returnVal != JFileChooser.APPROVE_OPTION) return; pathValue = chooser.getSelectedFile().getAbsolutePath(); */ File file1 = DefaultSettings.getUserInputOfFileFromGUI(this, //FileUtil.getUIWorkingDirectoryPath(), extension, "Open " + extension + " File..", (button != jbValidateSCSFileBrowse), false); if (file1 == null) return; String pathValue = file1.getAbsolutePath(); for(int i=(pathValue.length()-1);i>=0;i { String achar = pathValue.substring(i, i+1); if (achar.equals(File.separator)) { pathValue = pathValue + extension; break; } if (achar.equals(".")) break; } if (!pathValue.toLowerCase().endsWith(extension.toLowerCase())) { JOptionPane.showMessageDialog(this, "File name must be ended with '" + extension + "'.", "Invalid File extension",JOptionPane.ERROR_MESSAGE); return; } File file = new File(pathValue); if (file.exists()) { if (button != jbValidateSCSFileBrowse) { int res = JOptionPane.showConfirmDialog(this, pathValue + " is already exist. Are you sure to overwrite it?", "Duplicated File Name", JOptionPane.YES_NO_OPTION); if (res != JOptionPane.YES_OPTION) return; } else { if (!file.isFile()) { JOptionPane.showMessageDialog(this, "This is not a file : " + pathValue, "Not a file",JOptionPane.ERROR_MESSAGE); return; } } } else { if (button == jbValidateSCSFileBrowse) { JOptionPane.showMessageDialog(this, "This file is not exist : " + pathValue, "Not exist file",JOptionPane.ERROR_MESSAGE); return; } } if (button == jbInputSCSFileBrowse) jtInputSCSFile.setText(pathValue); else if (button == jbInputCSVFileBrowse) jtInputCSVFile.setText(pathValue); else if (button == jbValidateSCSFileBrowse) jtValidateSCSFile.setText(pathValue); } private void doPressNext() { if (mainFrame == null) { JOptionPane.showMessageDialog(this, "This Frame diesn't connect to the MainFrame.", "Null MainFrame",JOptionPane.ERROR_MESSAGE); return; } if (converter == null) { JOptionPane.showMessageDialog(this, "Generating Process is not complete.", "Null MainFrame",JOptionPane.ERROR_MESSAGE); return; } if (converter.getSCSFileName().equals("")) { JOptionPane.showMessageDialog(this, "No SCS File was generated.", "No Output SCS File",JOptionPane.ERROR_MESSAGE); return; } /* int ans = JOptionPane.showConfirmDialog(this, "Do you want to edit SCS file?", "Editing SCS or MAP ", JOptionPane.YES_NO_CANCEL_OPTION); if (ans == JOptionPane.YES_OPTION) { CSVPanel cp = new CSVPanel(); try { ValidatorResults result = cp.setSaveFile(new File(converter.getSCSFileName()), true); mainFrame.addNewTab(cp); } catch (Exception ee) { JOptionPane.showMessageDialog(this, "Unexpected Exception(34) : " + ee.getMessage(), "Unexpected Exception",JOptionPane.ERROR_MESSAGE); return; } } else if (ans == JOptionPane.NO_OPTION) { gov.nih.nci.caadapter.ui.main.map.MappingPanel mp; try { mp = new gov.nih.nci.caadapter.ui.main.map.MappingPanel(converter.getSCSFileName(), null); mainFrame.addNewTab(mp); } catch (Exception ee) { JOptionPane.showMessageDialog(this, "Unexpected Exception(34) : " + ee.getMessage(), "Unexpected Exception",JOptionPane.ERROR_MESSAGE); return; } } else return; */ V2ConverterNextProcessDialog nextDialog = null; if (dialog != null) nextDialog = new V2ConverterNextProcessDialog(dialog); if (frame != null) nextDialog = new V2ConverterNextProcessDialog(frame); if (nextDialog == null) { JOptionPane.showMessageDialog(this, "With Neither dialog nor frame", "No parent component",JOptionPane.ERROR_MESSAGE); return; } DefaultSettings.centerWindow(nextDialog); nextDialog.setVisible(true); //System.out.println("VVVV v: " + nextDialog.wasClickedGoNext()); if (!nextDialog.wasClickedGoNext()) return; //System.out.println("VVVV a: "); if (nextDialog.wasSelectedSCS()) { CSVPanel cp = new CSVPanel(); //System.out.println("VVVV b: "); try { ValidatorResults result = cp.setSaveFile(new File(converter.getSCSFileName()), true); mainFrame.addNewTab(cp); } catch (Exception ee) { JOptionPane.showMessageDialog(this, "SCS Panel Exception : " + ee.getMessage(), "Unexpected Exception",JOptionPane.ERROR_MESSAGE); return; } } else if (nextDialog.wasSelectedMAP()) { gov.nih.nci.caadapter.ui.mapping.hl7.HL7MappingPanel mp = null; //System.out.println("VVVV c: "); try { if (nextDialog.getH3SFileName().equals("")) mp = new gov.nih.nci.caadapter.ui.mapping.hl7.HL7MappingPanel(converter.getSCSFileName(), null); else if (!nextDialog.getH3SFileName().equals("")) mp = new gov.nih.nci.caadapter.ui.mapping.hl7.HL7MappingPanel(converter.getSCSFileName(), nextDialog.getH3SFileName(), null); // mp = new gov.nih.nci.caadapter.ui.mapping.hl7.NewHL7MappingPanel(converter.getSCSFileName(), nextDialog.getH3SFileName(), null); mainFrame.addNewTab(mp); } catch (Exception ee) { JOptionPane.showMessageDialog(this, "Map Panel Exception : " + ee.getMessage(), "Unexpected Exception",JOptionPane.ERROR_MESSAGE); return; } } //System.out.println("VVVV d: "); if (dialog != null) dialog.dispose(); if (frame != null) frame.dispose(); } private void doPressViewErrorMessages() { //System.out.println("VVVV CCCCCCCCC1"); ValidationMessageDialog frm = null; if (frame != null) frm = new ValidationMessageDialog(frame, "V2 message parsing error list.", false); if (dialog != null) frm = new ValidationMessageDialog(dialog, "V2 message parsing error list.", false); ValidatorResults validatorResults = new ValidatorResults(); //System.out.println("VVVV CCCCCCCCC2"); for(String msg:v2Tree.getErrorMessageList()) { if (msg.startsWith("FAT")) validatorResults = GeneralUtilities.addValidatorMessageFatal(validatorResults, msg); else if (msg.startsWith("ERR")) validatorResults = GeneralUtilities.addValidatorMessage(validatorResults, msg); else if (msg.startsWith("WAN")) validatorResults = GeneralUtilities.addValidatorMessageWarning(validatorResults, msg); else if (msg.startsWith("OBS")) validatorResults = GeneralUtilities.addValidatorMessageInfo(validatorResults, msg); else validatorResults = GeneralUtilities.addValidatorMessageInfo(validatorResults, msg); } frm.setValidatorResults(validatorResults); frm.setVisible(true); } private void doPressHL7MessageTypeConfirm() { jbViewErrorMessages.setEnabled(false); String type = jtInputMessageType.getText(); if (type == null) type = ""; type = type.trim(); if (!type.equals("")) { if ((type.length() != 7)||(!type.substring(3, 4).equals("^"))) { JOptionPane.showMessageDialog(this, "Invalid Message Type : " + type, "Invalid Message Type", JOptionPane.ERROR_MESSAGE); //jtInputMessageType.setFocusable(true); return; } } String version = jcHL7Version.getSelectedItem().toString(); if (version == null) version = ""; version = version.trim(); if (version.length() < 3) { JOptionPane.showMessageDialog(this, "Invalid HL7 Version : " + version, "Invalid HL7 Version", JOptionPane.ERROR_MESSAGE); //jtInputMessageType.setFocusable(true); return; } try { parseV2Message(); } catch(HL7MessageTreeException he) { JOptionPane.showMessageDialog(this, he.getMessage(), "HL7 Message Parsing Error!", JOptionPane.ERROR_MESSAGE); return; } } private void parseV2Message() throws HL7MessageTreeException { wasSuccessfullyParsed = false; boolean strict = jrStrictValidationYes.isSelected(); String inputF = jtInputFile.getText(); if (inputF == null) inputF = ""; inputF = inputF.trim(); String mType = jtInputMessageType.getText(); if (mType == null) mType = ""; mType = mType.trim(); String versionS = ((String)jcHL7Version.getSelectedItem()).trim(); msgTypeOnly = false; try { if (strict) { if (!inputF.equals("")) { v2Tree = new HL7V2MessageTree(v2MetaDataPath); v2Tree.setVersion(versionS); if (oneMessageFile != null) v2Tree.parse(oneMessageFile.getAbsolutePath()); else v2Tree.parse(inputF); if ((inputF.length() == 7)||(inputF.substring(3, 4).equals("^"))) msgTypeOnly = true; } else { v2Tree = new HL7V2MessageTree(v2MetaDataPath); v2Tree.setVersion(versionS); v2Tree.parse(mType); msgTypeOnly = true; } } else { v2Tree = new HL7V2MessageTree(v2MetaDataPath); v2Tree.setVersion(versionS); v2Tree.setFlagDataValidation(false); if (!mType.equals("")) { if ((mType.length() != 7)||(!mType.substring(3, 4).equals("^"))) { throw new HL7MessageTreeException("Invalid Message Type : " + mType); } v2Tree.makeTreeHead(mType.substring(0, 3), mType.substring(4)); } if (oneMessageFile != null) v2Tree.parse(oneMessageFile.getAbsolutePath()); else v2Tree.parse(inputF); } } catch(HL7MessageTreeException he) { throw he; } catch(Exception ee) { ee.printStackTrace(); throw new HL7MessageTreeException("Un expected Exception - This may not be a HL7 V2 Message. : " + ee.getMessage()); } if (v2Tree.getErrorMessageList().size() > 0) { errorMessages.add(" for (String ss:v2Tree.getErrorMessageList()) errorMessages.add(ss); String errMsg = v2Tree.getErrorMessageList().get(0); if ((errMsg.startsWith("FAT"))||(errMsg.startsWith("ERR"))) { jbViewErrorMessages.setEnabled(true); JOptionPane.showMessageDialog(this, "Some errors were found. For view these messages, Press 'View Error Messages' button.", "Finding Errors", JOptionPane.INFORMATION_MESSAGE); } } wasSuccessfullyParsed = true; ElementNode node = null; try { node = v2Tree.nodeAddressSearch("OBX.1.2"); foundOBXSegment = true; } catch(HL7MessageTreeException he) { node = null; foundOBXSegment = false; } if (msgTypeOnly) { jtInputFile.setText(""); listOBXDataType = new ArrayList<String>(); listOBXDataType2 = new ArrayList<String>(); } else { //jtInputMessageType.setText(""); if (foundOBXSegment) listOBXDataType = searchOBXDataTypes(); } if (listOBXDataType.size() > 0) wasOBXUsed = true; else wasOBXUsed = false; setRadioButtonState(); } private boolean organizeInputFile(String pathValue) { String inputF = pathValue; if (!inputF.equals("")) { boolean isMessageStarted = false; boolean wasFirstMessageEnded = false; hasMultiMessages = false; oneMessage = ""; oneMessageFile = null; segmentsOBX = ""; java.util.List<String> listOBXDataType2 = new ArrayList<String>(); try { FileReader fr = new FileReader(inputF); BufferedReader br = new BufferedReader(fr); while(true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.equals("")) continue; if (!isMessageStarted) { if (line.startsWith("MSH")) isMessageStarted = true; else { JOptionPane.showMessageDialog(this, "This file does not start with 'MSH' segment. : " + inputF, "Not a v2 Messahe File.", JOptionPane.ERROR_MESSAGE); return false; } oneMessage = oneMessage + line + "\r"; continue; } if ((isMessageStarted)&&(line.startsWith("MSH"))) { wasFirstMessageEnded = true; hasMultiMessages = true; } if (line.startsWith("OBX")) { String sr = ""; String line2 = line; int idx = line2.indexOf("|"); if (idx < 0) continue; line2 = line2.substring(idx+1); idx = line2.indexOf("|"); if (idx < 0) continue; line2 = line2.substring(idx+1); idx = line2.indexOf("|"); if (idx < 0) continue; sr = line2.substring(0,idx).trim(); if (sr.equals("")) continue; boolean isThereSameDataType = false; for (String cx:listOBXDataType2) if (cx.equals(sr)) isThereSameDataType = true; if (!isThereSameDataType) { segmentsOBX = segmentsOBX + line + "\r"; listOBXDataType2.add(sr); } } if (!wasFirstMessageEnded) { if (line.startsWith("OBX")) { if (listOBXDataType2.size() < 1) oneMessage = oneMessage + "OBX|" + "\r"; } else oneMessage = oneMessage + line + "\r"; } } if (hasMultiMessages) { if (!segmentsOBX.equals("")) { StringTokenizer st = new StringTokenizer(oneMessage, "\r"); String str = ""; boolean wasOBXFound = false; while(st.hasMoreTokens()) { String stt = st.nextToken().trim(); if (stt.equals("")) continue; if ((stt.startsWith("OBX"))&&(!wasOBXFound)) { wasOBXFound = true; str = str + segmentsOBX; } else str = str + stt + "\r"; } if (!wasOBXFound) str = str + segmentsOBX; oneMessage = str; } oneMessageFile = new File(FileUtil.saveStringIntoTemporaryFile(oneMessage)); } fr.close(); br.close(); //System.out.println("New inputF file : " + inputF); } catch(IOException ie) { JOptionPane.showMessageDialog(this, "Error on message file reorganizing(" + inputF + ") : " + ie.getMessage(), "IOException", JOptionPane.ERROR_MESSAGE); return false; } } return true; } private java.util.List<String> searchOBXDataTypes() { java.util.List<String> list = new ArrayList<String>(); ElementNode node = v2Tree.getHeadNode(); boolean cTag = false; while(true) { node = v2Tree.nextTraverse(node); if (node == null) break; if (node == v2Tree.getHeadNode()) break; if (!((node.getLevel().equals(v2Tree.getLevelField()))&&(node.getSequence() == 2))) continue; if (!node.getUpperLink().getType().equals("OBX")) continue; cTag = false; String dt = node.getValue().trim(); for(int i=0;i<jcbOBXName.length;i++) if (dt.equals(jcbOBXName[i])) cTag = true; if (!cTag) continue; cTag = false; for(int i=0;i<list.size();i++) if (dt.equals(list.get(i))) cTag = true; if (!cTag) list.add(dt); } return list; } public void setNextButtonVisible() { buttonNextVisible = true; jbNext.setVisible(buttonNextVisible); } public void setCloseButtonVisible() { buttonNextVisible = true; jbClose.setVisible(buttonNextVisible); } public Dimension getMinimumSize() { return minimum; } public JFrame setFrame(JFrame frame) { frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(this, BorderLayout.CENTER); frame.addWindowListener(new FrameCloseExit(frame)); frame.setMinimumSize(getMinimumSize()); this.frame = frame; this.dialog = null; return frame; } public JDialog setDialog(JDialog dialog) { dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add(this, BorderLayout.CENTER); dialog.addWindowListener(new DialogCloseExit(dialog)); dialog.setMinimumSize(getMinimumSize()); this.frame = null; this.dialog = dialog; return dialog; } public JDialog setupDialogBasedOnMainFrame(AbstractMainFrame mFrame) throws HeadlessException { JDialog dialog = new JDialog(mFrame, "V2 Converting to SCS and CSV"); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add(this, BorderLayout.CENTER); dialog.addWindowListener(new DialogCloseExit(dialog)); dialog.setMinimumSize(getMinimumSize()); this.frame = null; this.dialog = dialog; mainFrame = mFrame; return dialog; } class FrameCloseExit extends WindowAdapter { JFrame tt; FrameCloseExit(JFrame st) { tt = st; } public void windowClosing(WindowEvent e) { tt.dispose(); } } class DialogCloseExit extends WindowAdapter { JDialog tt; DialogCloseExit(JDialog st) { tt = st; } public void windowClosing(WindowEvent e) { tt.dispose(); } } public static void main(String arg[]) { String dataPath = ""; MetaDataLoader loader = null; String message = null; if (arg.length == 0) { loader = FileUtil.getV2ResourceMetaDataLoader(); message = "No v2 Resource zip file."; } else { loader = FileUtil.getV2ResourceMetaDataLoader(arg[0]); message = "Invalid v2 meta resource directory or zip file : " + arg[0]; } if (loader == null) { System.out.println(message); return; } try { V2ConverterToSCSPanel panel = new V2ConverterToSCSPanel(loader); JFrame frame = panel.setFrame(new JFrame("V2 Converter")); frame.setSize(panel.getMinimumSize()); frame.setVisible(true); } catch(IOException he) { System.out.println("Error : " + he.getMessage()); } // JFrame frame = (new V2ConverterToSCSPanel()).setFrame(new JFrame("V2 Converter")); // frame.setSize(500, 715); // frame.setVisible(true); } }
package fr.tcpmfa.engine; import java.sql.Time; import java.util.ArrayList; import java.util.Iterator; import fr.tcpmfa.util.Coordinate; public class WaveEnnemy extends ArrayList<Ennemy> { private static final long serialVersionUID = 3391625254887809314L; private static final int NBRENNEMY = 5; private static int count; private ArrayList<Ennemy> reserve; private int countDown; public WaveEnnemy(Game game, Point startPoint){ count++; this.reserve = new ArrayList<Ennemy>(); for(int i = 0; i < NBRENNEMY ; i++){ Ennemy ennemy = Ennemy.generateRandomEnnemy(); ennemy.setCheckPoint(startPoint.getCheckPoint()); ennemy.setCoord(new Coordinate(startPoint.getX(), startPoint.getY())); ennemy.setGame(game); ennemy.setName(ennemy.getName() + "-" + this.reserve.size()); this.reserve.add(ennemy); this.countDown = 0; System.out.println("Add to resserve"); } } public static int getCount(){ return count; } public Time timeBetween(){ return null; } public void act(){ System.out.println(" Iterator<Ennemy> it = this.iterator(); while (it.hasNext()) { Ennemy ennemy = it.next(); ennemy.act(); } if(!(this.reserve.isEmpty())){ System.out.println("CountDown = " + this.countDown + ", nbr reserve : " + this.reserve.size()); if(this.reserve.isEmpty()) System.out.println("Vide !"); if(this.countDown == 0 ){ System.out.println("Add from reserve"); this.add(this.reserve.remove(0)); this.countDown = 100; } else this.countDown } } }
package org.flymine.dataconversion; import java.io.FileReader; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.HashSet; import java.util.Arrays; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.ArrayList; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.InterMineException; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.xml.full.ItemHelper; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.dataconversion.ItemReader; import org.intermine.dataconversion.ItemWriter; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.FieldNameAndValue; import org.intermine.dataconversion.ItemPrefetchDescriptor; import org.intermine.dataconversion.ItemPrefetchConstraintDynamic; import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl; import org.intermine.dataconversion.ObjectStoreItemReader; import org.intermine.dataconversion.ObjectStoreItemWriter; import org.intermine.util.XmlUtil; import org.apache.log4j.Logger; /** * Convert Ensembl data in fulldata Item format conforming to a source OWL definition * to fulldata Item format conforming to InterMine OWL definition. * * @author Andrew Varley * @author Mark Woodbridge */ public class EnsemblDataTranslator extends DataTranslator { protected static final Logger LOG = Logger.getLogger(EnsemblDataTranslator.class); private Item ensemblDb; private Reference ensemblRef; private Item emblDb; private Reference emblRef; private Item tremblDb; private Reference tremblRef; private Item swissprotDb; private Reference swissprotRef; private Item flybaseDb; private Reference flybaseRef; private Map supercontigs = new HashMap(); private Map scLocs = new HashMap(); private Map exonLocs = new HashMap(); private Map exons = new HashMap(); private Map flybaseIds = new HashMap(); private String orgAbbrev; private Item organism; private Reference orgRef; private Map proteins = new HashMap(); private Map proteinIds = new HashMap(); private Set proteinSynonyms = new HashSet(); /** * @see DataTranslator#DataTranslator */ public EnsemblDataTranslator(ItemReader srcItemReader, OntModel model, String ns, String orgAbbrev) { super(srcItemReader, model, ns); this.orgAbbrev = orgAbbrev; } /** * @see DataTranslator#translate */ public void translate(ItemWriter tgtItemWriter) throws ObjectStoreException, InterMineException { tgtItemWriter.store(ItemHelper.convert(getOrganism())); tgtItemWriter.store(ItemHelper.convert(getEnsemblDb())); tgtItemWriter.store(ItemHelper.convert(getEmblDb())); tgtItemWriter.store(ItemHelper.convert(getTremblDb())); tgtItemWriter.store(ItemHelper.convert(getSwissprotDb())); super.translate(tgtItemWriter); Iterator i = createSuperContigs().iterator(); while (i.hasNext()) { Item supercontig = (Item) i.next(); if (supercontig.hasAttribute("identifier")) { Item synonym = createSynonym(supercontig.getIdentifier(), "identifier", supercontig.getAttribute("identifier").getValue(), getEnsemblRef()); addReferencedItem(supercontig, synonym, "synonyms", true, "subject", false); tgtItemWriter.store(ItemHelper.convert(synonym)); } tgtItemWriter.store(ItemHelper.convert(supercontig)); } i = exons.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = exonLocs.values().iterator(); while (i.hasNext()) { Iterator j = ((Collection) i.next()).iterator(); while (j.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) j.next())); } } i = proteins.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } i = proteinSynonyms.iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } if (flybaseDb != null) { tgtItemWriter.store(ItemHelper.convert(flybaseDb)); } } /** * @see DataTranslator#translateItem */ protected Collection translateItem(Item srcItem) throws ObjectStoreException, InterMineException { Collection result = new HashSet(); String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName()); String className = XmlUtil.getFragmentFromURI(srcItem.getClassName()); Collection translated = super.translateItem(srcItem); if (translated != null) { for (Iterator i = translated.iterator(); i.hasNext();) { boolean storeTgtItem = true; Item tgtItem = (Item) i.next(); if ("karyotype".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); if (tgtItem.hasAttribute("identifier")) { Item synonym = createSynonym(tgtItem.getIdentifier(), "name", tgtItem.getAttribute("identifier").getValue(), getEnsemblRef()); addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false); result.add(synonym); } Item location = createLocation(srcItem, tgtItem, "chromosome", "chr", true); location.addAttribute(new Attribute("strand", "0")); result.add(location); } else if ("exon".equals(className)) { tgtItem.addReference(getOrgRef()); Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs); if (stableId != null) { moveField(stableId, tgtItem, "stable_id", "identifier"); } addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); // more than one item representing same exon -> store up in map Item location = createLocation(srcItem, tgtItem, "contig", "contig", true); if (srcItem.hasAttribute("nonUniqueId")) { storeTgtItem = false; processExon(srcItem, tgtItem, location); } else { addToLocations(srcItem.getIdentifier(), location); } } else if ("simple_feature".equals(className)) { tgtItem.addReference(getOrgRef()); tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier())); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); result.add(createAnalysisResult(srcItem, tgtItem)); result.add(createLocation(srcItem, tgtItem, "contig", "contig", true)); } else if ("repeat_feature".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); result.add(createAnalysisResult(srcItem, tgtItem)); result.add(createLocation(srcItem, tgtItem, "contig", "contig", true)); promoteField(tgtItem, srcItem, "consensus", "repeat_consensus", "repeat_consensus"); promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class"); promoteField(tgtItem, srcItem, "identifier", "repeat_consensus", "repeat_name"); } else if ("gene".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); // gene name should be its stable id (or identifier if none) Item stableId = null; stableId = getStableId("gene", srcItem.getIdentifier(), srcNs); if (stableId != null) { moveField(stableId, tgtItem, "stable_id", "identifier"); } if (!tgtItem.hasAttribute("identifier")) { tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier())); } // display_xref is gene name (?) //promoteField(tgtItem, srcItem, "name", "display_xref", "display_label"); result.addAll(setGeneSynonyms(srcItem, tgtItem, srcNs)); // if no organismDbId set to be same as identifier if (!tgtItem.hasAttribute("organismDbId")) { tgtItem.addAttribute(new Attribute("organismDbId", tgtItem.getAttribute("identifier").getValue())); } } else if ("contig".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); if (tgtItem.hasAttribute("identifier")) { Item synonym = createSynonym(tgtItem.getIdentifier(), "identifier", tgtItem.getAttribute("identifier").getValue(), getEnsemblRef()); addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false); result.add(synonym); } } else if ("transcript".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); Item geneRelation = createItem(tgtNs + "SimpleRelation", ""); addReferencedItem(tgtItem, geneRelation, "objects", true, "subject", false); moveField(srcItem, geneRelation, "gene", "object"); result.add(geneRelation); String translationId = srcItem.getReference("translation").getRefId(); String proteinId = getChosenProteinId(translationId, srcNs); // if no SwissProt or trembl accession found there will not be a protein if (proteinId != null) { tgtItem.addReference(new Reference("protein", proteinId)); Item transRelation = createItem(tgtNs + "SimpleRelation", ""); transRelation.addReference(new Reference("subject", proteinId)); addReferencedItem(tgtItem, transRelation, "subjects", true, "object", false); result.add(transRelation); } else { tgtItem.removeReference("protein"); } // set transcript identifier to be ensembl stable id if (!tgtItem.hasAttribute("identifier")) { Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs); if (stableId != null) { moveField(stableId, tgtItem, "stable_id", "identifier"); } else { tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier())); } } // stable_ids become syonyms, need ensembl Database as source } else if (className.endsWith("_stable_id")) { if (className.endsWith("translation_stable_id")) { storeTgtItem = false; } else { tgtItem.addReference(getEnsemblRef()); tgtItem.addAttribute(new Attribute("type", "identifier")); } } else if ("chromosome".equals(className)) { tgtItem.addReference(getOrgRef()); addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false); if (tgtItem.hasAttribute("identifier")) { Item synonym = createSynonym(tgtItem.getIdentifier(), "name", tgtItem.getAttribute("identifier").getValue(), getEnsemblRef()); addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false); result.add(synonym); } } else if ("translation".equals(className)) { // if protein can be created it will be put in proteins collection and stored // at end of translation getProteinByPrimaryAccession(srcItem, srcNs); storeTgtItem = false; } if (storeTgtItem) { result.add(tgtItem); } } // assembly maps to null but want to create location on a supercontig } else if ("assembly".equals(className)) { Item sc = getSuperContig(srcItem.getAttribute("superctg_name").getValue(), srcItem.getReference("chromosome").getRefId(), Integer.parseInt(srcItem.getAttribute("chr_start").getValue()), Integer.parseInt(srcItem.getAttribute("chr_end").getValue()), srcItem.getAttribute("superctg_ori").getValue()); // locate contig on supercontig Item location = createLocation(srcItem, sc, "contig", "superctg", false); result.add(location); } return result; } /** * Translate a "located" Item into an Item and a location * @param srcItem the source Item * @param tgtItem the target Item (after translation) * @param idPrefix the id prefix for this class * @param locPrefix the start, end and strand prefix for this class * @param srcItemIsChild true if srcItem should be subject of Location * @return the location */ protected Item createLocation(Item srcItem, Item tgtItem, String idPrefix, String locPrefix, boolean srcItemIsChild) { String namespace = XmlUtil.getNamespaceFromURI(tgtItem.getClassName()); Item location = createItem(namespace + "Location", ""); moveField(srcItem, location, locPrefix + "_start", "start"); moveField(srcItem, location, locPrefix + "_end", "end"); location.addAttribute(new Attribute("startIsPartial", "false")); location.addAttribute(new Attribute("endIsPartial", "false")); if (srcItem.hasAttribute(locPrefix + "_strand")) { moveField(srcItem, location, locPrefix + "_strand", "strand"); } if (srcItem.hasAttribute("phase")) { moveField(srcItem, location, "phase", "phase"); } if (srcItem.hasAttribute("end_phase")) { moveField(srcItem, location, "end_phase", "endPhase"); } if (srcItem.hasAttribute(locPrefix + "_ori")) { moveField(srcItem, location, locPrefix + "_ori", "strand"); } if (srcItemIsChild) { addReferencedItem(tgtItem, location, "objects", true, "subject", false); moveField(srcItem, location, idPrefix, "object"); } else { addReferencedItem(tgtItem, location, "subjects", true, "object", false); moveField(srcItem, location, idPrefix, "subject"); } return location; } /** * Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem * analysis reference and score to new AnalysisResult. * @param srcItem item in src namespace to move fields from * @param tgtItem item that will reference AnalysisResult * @return new AnalysisResult item */ protected Item createAnalysisResult(Item srcItem, Item tgtItem) { Item result = createItem(tgtNs + "ComputationalResult", ""); moveField(srcItem, result, "analysis", "analysis"); moveField(srcItem, result, "score", "score"); result.addReference(getEnsemblRef()); ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[] {result.getIdentifier(), getEnsemblDb().getIdentifier()})); tgtItem.addCollection(evidence); return result; } private Item getSuperContig(String name, String chrId, int start, int end, String strand) { Item supercontig = (Item) supercontigs.get(name); if (supercontig == null) { supercontig = createItem(tgtNs + "Supercontig", ""); Item chrLoc = createItem(tgtNs + "Location", ""); chrLoc.addAttribute(new Attribute("start", "" + Integer.MAX_VALUE)); chrLoc.addAttribute(new Attribute("end", "" + Integer.MIN_VALUE)); chrLoc.addAttribute(new Attribute("startIsPartial", "false")); chrLoc.addAttribute(new Attribute("endIsPartial", "false")); chrLoc.addAttribute(new Attribute("strand", strand)); chrLoc.addReference(new Reference("subject", supercontig.getIdentifier())); chrLoc.addReference(new Reference("object", chrId)); supercontig.addAttribute(new Attribute("identifier", name)); ReferenceList subjects = new ReferenceList(); subjects.setName("subjects"); supercontig.addCollection(subjects); supercontig.addCollection(new ReferenceList("objects", new ArrayList(Collections.singletonList(chrLoc.getIdentifier())))); addReferencedItem(supercontig, getEnsemblDb(), "evidence", true, "", false); supercontig.addReference(getOrgRef()); supercontigs.put(name, supercontig); scLocs.put(name, chrLoc); } Item chrLoc = (Item) scLocs.get(name); if (Integer.parseInt(chrLoc.getAttribute("start").getValue()) > start) { chrLoc.getAttribute("start").setValue("" + start); } if (Integer.parseInt(chrLoc.getAttribute("end").getValue()) < end) { chrLoc.getAttribute("end").setValue("" + end); } return supercontig; } private Collection createSuperContigs() { Set results = new HashSet(); Iterator i = supercontigs.values().iterator(); while (i.hasNext()) { Item sc = (Item) i.next(); results.add(sc); results.add((Item) scLocs.get(sc.getAttribute("identifier").getValue())); } return results; } private String getChosenProteinId(String id, String srcNs) throws ObjectStoreException { String chosenId = (String) proteinIds.get(id); if (chosenId == null) { Item translation = ItemHelper.convert(srcItemReader.getItemById(id)); Item protein = getProteinByPrimaryAccession(translation, srcNs); if (protein != null) { chosenId = protein.getIdentifier(); proteinIds.put(id, chosenId); } } return chosenId; } private Item getProteinByPrimaryAccession(Item translation, String srcNs) throws ObjectStoreException { Item protein = createItem(tgtNs + "Protein", ""); Set synonyms = new HashSet(); String value = translation.getIdentifier(); Set constraints = new HashSet(); constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, srcNs + "object_xref", false)); constraints.add(new FieldNameAndValue("ensembl", value, true)); Iterator objectXrefs = srcItemReader.getItemsByDescription(constraints).iterator(); // set specific ids and add synonyms String swissProtId = null; String tremblId = null; while (objectXrefs.hasNext()) { Item objectXref = ItemHelper.convert( (org.intermine.model.fulldata.Item) objectXrefs.next()); Item xref = ItemHelper.convert(srcItemReader .getItemById(objectXref.getReference("xref").getRefId())); String accession = null; String dbname = null; if (xref != null) { accession = xref.getAttribute("dbprimary_acc").getValue(); Item externalDb = ItemHelper.convert(srcItemReader .getItemById(xref.getReference("external_db").getRefId())); if (externalDb != null) { dbname = externalDb.getAttribute("db_name").getValue(); } } //LOG.error("processing: " + accession + ", " + dbname); if (accession != null && !accession.equals("") && dbname != null && !dbname.equals("")) { if (dbname.equals("SWISSPROT")) { swissProtId = accession; Item synonym = createSynonym(protein.getIdentifier(), "accession", accession, getSwissprotRef()); addReferencedItem(protein, synonym, "synonyms", true, "subject", false); synonyms.add(synonym); } else if (dbname.equals("SPTREMBL")) { tremblId = accession; Item synonym = createSynonym(protein.getIdentifier(), "accession", accession, getTremblRef()); addReferencedItem(protein, synonym, "synonyms", true, "subject", false); synonyms.add(synonym); } else if (dbname.equals("protein_id") || dbname.equals("prediction_SPTREMBL")) { Item synonym = createSynonym(protein.getIdentifier(), "identifier", accession, getEmblRef()); addReferencedItem(protein, synonym, "synonyms", true, "subject", false); synonyms.add(synonym); } } } // we have a set of synonyms, if we don't want to create a protein these will be discarded // we want to create a Protein only if there is Swiss-Prot or Trembl id // set of synonyms will be discarded if no protein created // TODO: sort out how we wish to model translations/proteins in genomic model String primaryAcc = null; if (swissProtId != null) { primaryAcc = swissProtId; } else if (tremblId != null) { primaryAcc = tremblId; } // try to find a protein with this accession, otherwise create if an accession Item chosenProtein = (Item) proteins.get(primaryAcc); if (chosenProtein == null && primaryAcc != null) { protein.addAttribute(new Attribute("primaryAccession", primaryAcc)); addReferencedItem(protein, getEnsemblDb(), "evidence", true, "", false); // set up additional references/collections protein.addReference(getOrgRef()); if (translation.hasReference("start_exon")) { protein.addReference(new Reference("startExon", translation.getReference("start_exon").getRefId())); } if (translation.hasReference("end_exon")) { protein.addReference(new Reference("endExon", translation.getReference("end_exon").getRefId())); } proteins.put(primaryAcc, protein); proteinSynonyms.addAll(synonyms); chosenProtein = protein; } // add mapping between this translation and target protein if (chosenProtein != null) { proteinIds.put(translation.getIdentifier(), chosenProtein.getIdentifier()); } else { LOG.info("no protein created for translation: " + translation.getIdentifier()); } return chosenProtein; } /** * Find external database accession numbers in ensembl to set as Synonyms * @param srcItem it in source format ensembl:gene * @param tgtItem translate item flymine:Gene * @param srcNs namespace of source model * @return a set of Synonyms * @throws ObjectStoreException if problem retrieving items */ protected Set setGeneSynonyms(Item srcItem, Item tgtItem, String srcNs) throws ObjectStoreException { // additional gene information is in xref table only accessible via translation Set synonyms = new HashSet(); // get transcript Set constraints = new HashSet(); constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, srcNs + "transcript", false)); constraints.add(new FieldNameAndValue("gene", srcItem.getIdentifier(), true)); Item transcript = ItemHelper.convert((org.intermine.model.fulldata.Item) srcItemReader .getItemsByDescription(constraints).iterator().next()); String translationId = transcript.getReference("translation").getRefId(); // find xrefs constraints = new HashSet(); constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, srcNs + "object_xref", false)); constraints.add(new FieldNameAndValue("ensembl", translationId, true)); Iterator objectXrefs = srcItemReader.getItemsByDescription(constraints).iterator(); while (objectXrefs.hasNext()) { Item objectXref = ItemHelper.convert( (org.intermine.model.fulldata.Item) objectXrefs.next()); Item xref = ItemHelper.convert(srcItemReader .getItemById(objectXref.getReference("xref").getRefId())); String accession = null; String dbname = null; if (xref != null) { if (xref.hasAttribute("dbprimary_acc")) { accession = xref.getAttribute("dbprimary_acc").getValue(); Reference dbRef = xref.getReference("external_db"); if (dbRef != null && dbRef.getRefId() != null) { Item externalDb = ItemHelper.convert(srcItemReader .getItemById(dbRef.getRefId())); if (externalDb != null) { dbname = externalDb.getAttribute("db_name").getValue(); } } } } if (accession != null && !accession.equals("") && dbname != null && !dbname.equals("")) { if (dbname.equals("flybase_gene") || dbname.equals("flybase_symbol")) { Item synonym = createItem(tgtNs + "Synonym", ""); addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false); synonym.addAttribute(new Attribute("value", accession)); if (dbname.equals("flybase_symbol")) { synonym.addAttribute(new Attribute("type", "name")); tgtItem.addAttribute(new Attribute("name", accession)); } else { // flybase_gene synonym.addAttribute(new Attribute("type", "identifier")); // temporary fix to deal with broken FlyBase identfiers in ensembl String value = accession; Set idSet = (Set) flybaseIds.get(accession); if (idSet == null) { idSet = new HashSet(); } else { value += "_flymine_" + idSet.size(); } idSet.add(value); flybaseIds.put(accession, idSet); tgtItem.addAttribute(new Attribute("organismDbId", value)); } synonym.addReference(getFlyBaseRef()); synonyms.add(synonym); } } } return synonyms; } // keep exon with the lowest identifier private void processExon(Item srcItem, Item exon, Item loc) { String nonUniqueId = srcItem.getAttribute("nonUniqueId").getValue(); if (exons.containsKey(nonUniqueId)) { Item chosenExon = null; Item otherExon = null; String oldIdentifier = ((Item) exons.get(nonUniqueId)).getIdentifier(); if (Integer.parseInt(oldIdentifier.substring(oldIdentifier.indexOf("_") + 1)) > Integer.parseInt(exon.getIdentifier() .substring(exon.getIdentifier().indexOf("_") + 1))) { chosenExon = exon; otherExon = (Item) exons.get(nonUniqueId); } else { chosenExon = (Item) exons.get(nonUniqueId); otherExon = exon; } // exon in map needs all locations in objects collection Set objects = new HashSet(); objects.addAll(chosenExon.getCollection("objects").getRefIds()); objects.addAll(otherExon.getCollection("objects").getRefIds()); objects.add(loc.getIdentifier()); chosenExon.addCollection(new ReferenceList("objects", new ArrayList(objects))); // all locs need chosen exon as subject addToLocations(nonUniqueId, loc); Iterator iter = ((Collection) exonLocs.get(nonUniqueId)).iterator(); while (iter.hasNext()) { Item location = (Item) iter.next(); location.addReference(new Reference("subject", chosenExon.getIdentifier())); } exons.put(nonUniqueId, chosenExon); } else { exons.put(nonUniqueId, exon); addToLocations(nonUniqueId, loc); } } private void addToLocations(String nonUniqueId, Item location) { Set locs = (Set) exonLocs.get(nonUniqueId); if (locs == null) { locs = new HashSet(); exonLocs.put(nonUniqueId, locs); } locs.add(location); } // ensemblType should be part of name before _stable_id private Item getStableId(String ensemblType, String identifier, String srcNs) throws ObjectStoreException { //String value = identifier.substring(identifier.indexOf("_") + 1); String value = identifier; Set constraints = new HashSet(); constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, srcNs + ensemblType + "_stable_id", false)); constraints.add(new FieldNameAndValue(ensemblType, value, true)); Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator(); if (stableIds.hasNext()) { return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next()); } else { return null; } } private Item createSynonym(String subjectId, String type, String value, Reference ref) { Item synonym = createItem(tgtNs + "Synonym", ""); synonym.addReference(new Reference("subject", subjectId)); synonym.addAttribute(new Attribute("type", type)); synonym.addAttribute(new Attribute("value", value)); synonym.addReference(ref); return synonym; } private Item getEnsemblDb() { if (ensemblDb == null) { ensemblDb = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", "ensembl"); Attribute url = new Attribute("url", "http: ensemblDb.addAttribute(title); ensemblDb.addAttribute(url); } return ensemblDb; } private Reference getEnsemblRef() { if (ensemblRef == null) { ensemblRef = new Reference("source", getEnsemblDb().getIdentifier()); } return ensemblRef; } private Item getEmblDb() { if (emblDb == null) { emblDb = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", "embl"); Attribute url = new Attribute("url", "http: emblDb.addAttribute(title); emblDb.addAttribute(url); } return emblDb; } private Reference getEmblRef() { if (emblRef == null) { emblRef = new Reference("source", getEmblDb().getIdentifier()); } return emblRef; } private Item getSwissprotDb() { if (swissprotDb == null) { swissprotDb = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", "Swiss-Prot"); Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/"); swissprotDb.addAttribute(title); swissprotDb.addAttribute(url); } return swissprotDb; } private Reference getSwissprotRef() { if (swissprotRef == null) { swissprotRef = new Reference("source", getSwissprotDb().getIdentifier()); } return swissprotRef; } private Item getTremblDb() { if (tremblDb == null) { tremblDb = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", "TrEMBL"); Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/"); tremblDb.addAttribute(title); tremblDb.addAttribute(url); } return tremblDb; } private Reference getTremblRef() { if (tremblRef == null) { tremblRef = new Reference("source", getTremblDb().getIdentifier()); } return tremblRef; } private Item getFlyBaseDb() { if (flybaseDb == null) { flybaseDb = createItem(tgtNs + "Database", ""); Attribute title = new Attribute("title", "FlyBase"); Attribute url = new Attribute("url", "http: flybaseDb.addAttribute(title); flybaseDb.addAttribute(url); } return flybaseDb; } private Reference getFlyBaseRef() { if (flybaseRef == null) { flybaseRef = new Reference("source", getFlyBaseDb().getIdentifier()); } return flybaseRef; } private Item getOrganism() { if (organism == null) { organism = createItem(tgtNs + "Organism", ""); Attribute a1 = new Attribute("abbreviation", orgAbbrev); organism.addAttribute(a1); } return organism; } private Reference getOrgRef() { if (orgRef == null) { orgRef = new Reference("organism", getOrganism().getIdentifier()); } return orgRef; } /** * Main method * @param args command line arguments * @throws Exception if something goes wrong */ public static void main (String[] args) throws Exception { String srcOsName = args[0]; String tgtOswName = args[1]; String modelName = args[2]; String format = args[3]; String namespace = args[4]; String orgAbbrev = args[5]; Map paths = new HashMap(); ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus"); desc.addConstraint(new ItemPrefetchConstraintDynamic("repeat_consensus", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); paths.put("http://www.flymine.org/model/ensembl#repeat_feature", Collections.singleton(desc)); HashSet descSet = new HashSet(); //desc = new ItemPrefetchDescriptor("transcript.display_xref"); //desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", //ObjectStoreItemPathFollowingImpl.IDENTIFIER)); //descSet.add(desc); desc = new ItemPrefetchDescriptor( "(transcript.translation"); desc.addConstraint(new ItemPrefetchConstraintDynamic("translation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descSet.add(desc); ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl)"); desc2.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "ensembl")); desc2.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#object_xref", false)); desc.addPath(desc2); ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl).xref"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("xref", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); ItemPrefetchDescriptor desc4 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl).xref.external_db"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("external_db", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3.addPath(desc4); desc = new ItemPrefetchDescriptor("(transcript <- transcript_stable_id.transcript)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "transcript")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#transcript_stable_id", false)); descSet.add(desc); paths.put("http://www.flymine.org/model/ensembl#transcript", descSet); descSet = new HashSet(); //desc = new ItemPrefetchDescriptor("gene.display_xref"); //desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", //ObjectStoreItemPathFollowingImpl.IDENTIFIER)); //descSet.add(desc); desc = new ItemPrefetchDescriptor("(gene <- gene_stable_id.gene)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "gene")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#gene_stable_id", false)); descSet.add(desc); desc = new ItemPrefetchDescriptor("(gene <- transcript.gene)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "gene")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#transcript", false)); desc2 = new ItemPrefetchDescriptor( "(gene <- transcript.gene).translation"); descSet.add(desc); desc2.addConstraint(new ItemPrefetchConstraintDynamic("translation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); desc3 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl)"); desc3.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "ensembl")); desc3.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#object_xref", false)); desc2.addPath(desc3); desc4 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl).xref"); desc4.addConstraint(new ItemPrefetchConstraintDynamic("xref", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3.addPath(desc4); ItemPrefetchDescriptor desc5 = new ItemPrefetchDescriptor( "((gene <- transcript.gene).translation <- object_xref.ensembl).xref.external_db"); desc5.addConstraint(new ItemPrefetchConstraintDynamic("external_db", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc4.addPath(desc5); paths.put("http://www.flymine.org/model/ensembl#gene", descSet); desc = new ItemPrefetchDescriptor("contig.dna"); desc.addConstraint(new ItemPrefetchConstraintDynamic("dna", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); paths.put("http://www.flymine.org/model/ensembl#contig", Collections.singleton(desc)); descSet = new HashSet(); desc = new ItemPrefetchDescriptor("(translation <- object_xref.ensembl)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "ensembl")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#object_xref", false)); desc2 = new ItemPrefetchDescriptor( "(translation <- object_xref.ensembl).xref"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("xref", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc3 = new ItemPrefetchDescriptor("(translation <- object_xref.ensembl).xref.external_db"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("external_db", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); desc.addPath(desc2); descSet.add(desc); desc = new ItemPrefetchDescriptor("(translation <- translation_stable_id.translation)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "translation")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#translation_stable_id", false)); descSet.add(desc); paths.put("http://www.flymine.org/model/ensembl#translation", descSet); desc = new ItemPrefetchDescriptor("(exon <- exon_stable_id.exon)"); desc.addConstraint(new ItemPrefetchConstraintDynamic( ObjectStoreItemPathFollowingImpl.IDENTIFIER, "exon")); desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME, "http://www.flymine.org/model/ensembl#exon_stable_id", false)); paths.put("http://www.flymine.org/model/ensembl#exon", Collections.singleton(desc)); ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName); ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths); ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName); ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt); OntModel model = ModelFactory.createOntologyModel(); model.read(new FileReader(new File(modelName)), null, format); DataTranslator dt = new EnsemblDataTranslator(srcItemReader, model, namespace, orgAbbrev); model = null; dt.translate(tgtItemWriter); tgtItemWriter.close(); } }
package net.coobird.thumbnailator; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.coobird.thumbnailator.filters.ImageFilter; import net.coobird.thumbnailator.filters.Pipeline; import net.coobird.thumbnailator.filters.Rotation; import net.coobird.thumbnailator.filters.Watermark; import net.coobird.thumbnailator.geometry.AbsoluteSize; import net.coobird.thumbnailator.geometry.Coordinate; import net.coobird.thumbnailator.geometry.Position; import net.coobird.thumbnailator.geometry.Positions; import net.coobird.thumbnailator.geometry.Region; import net.coobird.thumbnailator.geometry.Size; import net.coobird.thumbnailator.name.Rename; import net.coobird.thumbnailator.resizers.BicubicResizer; import net.coobird.thumbnailator.resizers.BilinearResizer; import net.coobird.thumbnailator.resizers.ProgressiveBilinearResizer; import net.coobird.thumbnailator.resizers.Resizer; import net.coobird.thumbnailator.resizers.Resizers; import net.coobird.thumbnailator.resizers.configurations.AlphaInterpolation; import net.coobird.thumbnailator.resizers.configurations.Antialiasing; import net.coobird.thumbnailator.resizers.configurations.Dithering; import net.coobird.thumbnailator.resizers.configurations.Rendering; import net.coobird.thumbnailator.resizers.configurations.ScalingMode; import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask; import net.coobird.thumbnailator.tasks.io.BufferedImageSink; import net.coobird.thumbnailator.tasks.io.BufferedImageSource; import net.coobird.thumbnailator.tasks.io.FileImageSink; import net.coobird.thumbnailator.tasks.io.FileImageSource; import net.coobird.thumbnailator.tasks.io.ImageSource; import net.coobird.thumbnailator.tasks.io.InputStreamImageSource; import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink; import net.coobird.thumbnailator.tasks.io.URLImageSource; import net.coobird.thumbnailator.util.ThumbnailatorUtils; public final class Thumbnails { /** * This class is not intended to be instantiated. */ private Thumbnails() {} private static void validateDimensions(int width, int height) { if (width <= 0 && height <= 0) { throw new IllegalArgumentException( "Destination image dimensions must not be less than " + "0 pixels." ); } else if (width <= 0 || height <= 0) { String dimension = width == 0 ? "width" : "height"; throw new IllegalArgumentException( "Destination image " + dimension + " must not be " + "less than or equal to 0 pixels." ); } } private static void checkForNull(Object o, String message) { if (o == null) { throw new NullPointerException(message); } } private static void checkForEmpty(Object[] o, String message) { if (o.length == 0) { throw new IllegalArgumentException(message); } } private static void checkForEmpty(Iterable<?> o, String message) { if (!o.iterator().hasNext()) { throw new IllegalArgumentException(message); } } public static Builder<File> of(String... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.ofStrings(Arrays.asList(files)); } public static Builder<File> of(File... files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty array for input files."); return Builder.ofFiles(Arrays.asList(files)); } public static Builder<URL> of(URL... urls) { checkForNull(urls, "Cannot specify null for input URLs."); checkForEmpty(urls, "Cannot specify an empty array for input URLs."); return Builder.ofUrls(Arrays.asList(urls)); } public static Builder<? extends InputStream> of(InputStream... inputStreams) { checkForNull(inputStreams, "Cannot specify null for InputStreams."); checkForEmpty(inputStreams, "Cannot specify an empty array for InputStreams."); return Builder.ofInputStreams(Arrays.asList(inputStreams)); } public static Builder<BufferedImage> of(BufferedImage... images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty array for images."); return Builder.ofBufferedImages(Arrays.asList(images)); } @Deprecated public static Builder<File> fromFilenames(Collection<String> files) { return fromFilenames((Iterable<String>)files); } @Deprecated public static Builder<File> fromFiles(Collection<File> files) { return fromFiles((Iterable<File>)files); } @Deprecated public static Builder<URL> fromURLs(Collection<URL> urls) { return fromURLs((Iterable<URL>)urls); } @Deprecated public static Builder<InputStream> fromInputStreams(Collection<? extends InputStream> inputStreams) { return fromInputStreams((Iterable<? extends InputStream>)inputStreams); } @Deprecated public static Builder<BufferedImage> fromImages(Collection<BufferedImage> images) { return fromImages((Iterable<BufferedImage>)images); } public static Builder<File> fromFilenames(Iterable<String> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return Builder.ofStrings(files); } public static Builder<File> fromFiles(Iterable<File> files) { checkForNull(files, "Cannot specify null for input files."); checkForEmpty(files, "Cannot specify an empty collection for input files."); return Builder.ofFiles(files); } public static Builder<URL> fromURLs(Iterable<URL> urls) { checkForNull(urls, "Cannot specify null for input URLs."); checkForEmpty(urls, "Cannot specify an empty collection for input URLs."); return Builder.ofUrls(urls); } public static Builder<InputStream> fromInputStreams(Iterable<? extends InputStream> inputStreams) { checkForNull(inputStreams, "Cannot specify null for InputStreams."); checkForEmpty(inputStreams, "Cannot specify an empty collection for InputStreams."); return Builder.ofInputStreams(inputStreams); } public static Builder<BufferedImage> fromImages(Iterable<BufferedImage> images) { checkForNull(images, "Cannot specify null for images."); checkForEmpty(images, "Cannot specify an empty collection for images."); return Builder.ofBufferedImages(images); } /** * A builder interface for Thumbnailator. * <p> * An instance of this class is obtained by calling one of: * <ul> * <li>{@link Thumbnails#of(BufferedImage...)}</li> * <li>{@link Thumbnails#of(File...)}</li> * <li>{@link Thumbnails#of(String...)}</li> * <li>{@link Thumbnails#of(InputStream...)}</li> * <li>{@link Thumbnails#of(URL...)}</li> * <li>{@link Thumbnails#fromImages(Iterable)}</li> * <li>{@link Thumbnails#fromFiles(Iterable)}</li> * <li>{@link Thumbnails#fromFilenames(Iterable)}</li> * <li>{@link Thumbnails#fromInputStreams(Iterable)}</li> * <li>{@link Thumbnails#fromURLs(Iterable)}</li> * </ul> * * @author coobird * */ public static class Builder<T> { private final Iterable<ImageSource<T>> sources; private Builder(Iterable<ImageSource<T>> sources) { this.sources = sources; statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); } private static final class StringImageSourceIterator implements Iterable<ImageSource<File>> { private final Iterable<String> filenames; private StringImageSourceIterator(Iterable<String> filenames) { this.filenames = filenames; } public Iterator<ImageSource<File>> iterator() { return new Iterator<ImageSource<File>>() { Iterator<String> iter = filenames.iterator(); public boolean hasNext() { return iter.hasNext(); } public ImageSource<File> next() { return new FileImageSource(iter.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } private static final class FileImageSourceIterator implements Iterable<ImageSource<File>> { private final Iterable<File> files; private FileImageSourceIterator(Iterable<File> files) { this.files = files; } public Iterator<ImageSource<File>> iterator() { return new Iterator<ImageSource<File>>() { Iterator<File> iter = files.iterator(); public boolean hasNext() { return iter.hasNext(); } public ImageSource<File> next() { return new FileImageSource(iter.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } private static final class URLImageSourceIterator implements Iterable<ImageSource<URL>> { private final Iterable<URL> urls; private URLImageSourceIterator(Iterable<URL> urls) { this.urls = urls; } public Iterator<ImageSource<URL>> iterator() { return new Iterator<ImageSource<URL>>() { Iterator<URL> iter = urls.iterator(); public boolean hasNext() { return iter.hasNext(); } public ImageSource<URL> next() { return new URLImageSource(iter.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } private static final class InputStreamImageSourceIterator implements Iterable<ImageSource<InputStream>> { private final Iterable<? extends InputStream> inputStreams; private InputStreamImageSourceIterator(Iterable<? extends InputStream> inputStreams) { this.inputStreams = inputStreams; } public Iterator<ImageSource<InputStream>> iterator() { return new Iterator<ImageSource<InputStream>>() { Iterator<? extends InputStream> iter = inputStreams.iterator(); public boolean hasNext() { return iter.hasNext(); } public ImageSource<InputStream> next() { return new InputStreamImageSource(iter.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } private static final class BufferedImageImageSourceIterator implements Iterable<ImageSource<BufferedImage>> { private final Iterable<BufferedImage> image; private BufferedImageImageSourceIterator(Iterable<BufferedImage> images) { this.image = images; } public Iterator<ImageSource<BufferedImage>> iterator() { return new Iterator<ImageSource<BufferedImage>>() { Iterator<BufferedImage> iter = image.iterator(); public boolean hasNext() { return iter.hasNext(); } public ImageSource<BufferedImage> next() { return new BufferedImageSource(iter.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } private static Builder<File> ofStrings(Iterable<String> filenames) { Iterable<ImageSource<File>> iter = new StringImageSourceIterator(filenames); return new Builder<File>(iter); } private static Builder<File> ofFiles(Iterable<File> files) { Iterable<ImageSource<File>> iter = new FileImageSourceIterator(files); return new Builder<File>(iter); } private static Builder<URL> ofUrls(Iterable<URL> urls) { Iterable<ImageSource<URL>> iter = new URLImageSourceIterator(urls); return new Builder<URL>(iter); } private static Builder<InputStream> ofInputStreams(Iterable<? extends InputStream> inputStreams) { Iterable<ImageSource<InputStream>> iter = new InputStreamImageSourceIterator(inputStreams); return new Builder<InputStream>(iter); } private static Builder<BufferedImage> ofBufferedImages(Iterable<BufferedImage> images) { Iterable<ImageSource<BufferedImage>> iter = new BufferedImageImageSourceIterator(images); return new Builder<BufferedImage>(iter); } private final class BufferedImageIterable implements Iterable<BufferedImage> { public Iterator<BufferedImage> iterator() { return new Iterator<BufferedImage>() { Iterator<ImageSource<T>> sourceIter = sources.iterator(); public boolean hasNext() { return sourceIter.hasNext(); } public BufferedImage next() { ImageSource<T> source = sourceIter.next(); BufferedImageSink destination = new BufferedImageSink(); try { Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); } catch (IOException e) { return null; } return destination.getSink(); } public void remove() { throw new UnsupportedOperationException( "Cannot remove elements from this iterator." ); } }; } } /** * Status of each property. * * @author coobird * */ private static enum Status { OPTIONAL, READY, NOT_READY, ALREADY_SET, CANNOT_SET, } /** * Interface used by {@link Properties}. * * @author coobird * */ private static interface Property { public String getName(); } /** * Enum of properties which can be set by this builder. * * @author coobird * */ private static enum Properties implements Property { SIZE("size"), WIDTH("width"), HEIGHT("height"), SCALE("scale"), IMAGE_TYPE("imageType"), SCALING_MODE("scalingMode"), ALPHA_INTERPOLATION("alphaInterpolation"), ANTIALIASING("antialiasing"), DITHERING("dithering"), RENDERING("rendering"), KEEP_ASPECT_RATIO("keepAspectRatio"), OUTPUT_FORMAT("outputFormat"), OUTPUT_FORMAT_TYPE("outputFormatType"), OUTPUT_QUALITY("outputQuality"), RESIZER("resizer"), SOURCE_REGION("sourceRegion"), ; private final String name; private Properties(String name) { this.name = name; } public String getName() { return name; } } /** * Map to keep track of whether a property has been properly set or not. */ private final Map<Properties, Status> statusMap = new HashMap<Properties, Status>(); /** * Populates the property map. */ { statusMap.put(Properties.SIZE, Status.NOT_READY); statusMap.put(Properties.WIDTH, Status.OPTIONAL); statusMap.put(Properties.HEIGHT, Status.OPTIONAL); statusMap.put(Properties.SCALE, Status.NOT_READY); statusMap.put(Properties.SOURCE_REGION, Status.OPTIONAL); statusMap.put(Properties.IMAGE_TYPE, Status.OPTIONAL); statusMap.put(Properties.SCALING_MODE, Status.OPTIONAL); statusMap.put(Properties.ALPHA_INTERPOLATION, Status.OPTIONAL); statusMap.put(Properties.ANTIALIASING, Status.OPTIONAL); statusMap.put(Properties.DITHERING, Status.OPTIONAL); statusMap.put(Properties.RENDERING, Status.OPTIONAL); statusMap.put(Properties.KEEP_ASPECT_RATIO, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_FORMAT_TYPE, Status.OPTIONAL); statusMap.put(Properties.OUTPUT_QUALITY, Status.OPTIONAL); statusMap.put(Properties.RESIZER, Status.OPTIONAL); } /** * Updates the property status map. * * @param property The property to update. * @param newStatus The new status. */ private void updateStatus(Properties property, Status newStatus) { if (statusMap.get(property) == Status.ALREADY_SET) { throw new IllegalStateException( property.getName() + " is already set."); } if (statusMap.get(property) == Status.CANNOT_SET) { throw new IllegalStateException( property.getName() + " cannot be set."); } statusMap.put(property, newStatus); } /** * An constant used to indicate that the imageType has not been * specified. When this constant is encountered, one should use the * {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE} as the value for * imageType. */ private static int IMAGE_TYPE_UNSPECIFIED = -1; private static final int DIMENSION_NOT_SPECIFIED = -1; /* * Defines the fields for the builder interface, and assigns the * default values. */ private int width = DIMENSION_NOT_SPECIFIED; private int height = DIMENSION_NOT_SPECIFIED; private double scale = Double.NaN; private Region sourceRegion; private int imageType = IMAGE_TYPE_UNSPECIFIED; private boolean keepAspectRatio = true; private String outputFormat = ThumbnailParameter.ORIGINAL_FORMAT; private String outputFormatType = ThumbnailParameter.DEFAULT_FORMAT_TYPE; private float outputQuality = ThumbnailParameter.DEFAULT_QUALITY; private ScalingMode scalingMode = ScalingMode.PROGRESSIVE_BILINEAR; private AlphaInterpolation alphaInterpolation = AlphaInterpolation.DEFAULT; private Dithering dithering = Dithering.DEFAULT; private Antialiasing antialiasing = Antialiasing.DEFAULT; private Rendering rendering = Rendering.DEFAULT; private Resizer resizer = Resizers.PROGRESSIVE; /** * The {@link ImageFilter}s that should be applied when creating the * thumbnail. */ private Pipeline filterPipeline = new Pipeline(); public Builder<T> size(int width, int height) { updateStatus(Properties.SIZE, Status.ALREADY_SET); updateStatus(Properties.SCALE, Status.CANNOT_SET); validateDimensions(width, height); this.width = width; this.height = height; return this; } public Builder<T> width(int width) { if (statusMap.get(Properties.SIZE) != Status.CANNOT_SET) { updateStatus(Properties.SIZE, Status.CANNOT_SET); } if (statusMap.get(Properties.SCALE) != Status.CANNOT_SET) { updateStatus(Properties.SCALE, Status.CANNOT_SET); } updateStatus(Properties.WIDTH, Status.ALREADY_SET); validateDimensions(width, Integer.MAX_VALUE); this.width = width; return this; } public Builder<T> height(int height) { if (statusMap.get(Properties.SIZE) != Status.CANNOT_SET) { updateStatus(Properties.SIZE, Status.CANNOT_SET); } if (statusMap.get(Properties.SCALE) != Status.CANNOT_SET) { updateStatus(Properties.SCALE, Status.CANNOT_SET); } updateStatus(Properties.HEIGHT, Status.ALREADY_SET); validateDimensions(Integer.MAX_VALUE, height); this.height = height; return this; } public Builder<T> forceSize(int width, int height) { updateStatus(Properties.SIZE, Status.ALREADY_SET); updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET); updateStatus(Properties.SCALE, Status.CANNOT_SET); validateDimensions(width, height); this.width = width; this.height = height; this.keepAspectRatio = false; return this; } public Builder<T> scale(double scale) { updateStatus(Properties.SCALE, Status.ALREADY_SET); updateStatus(Properties.SIZE, Status.CANNOT_SET); updateStatus(Properties.KEEP_ASPECT_RATIO, Status.CANNOT_SET); if (scale <= 0) { throw new IllegalArgumentException( "The scaling factor is equal to or less than 0." ); } this.scale = scale; return this; } public Builder<T> sourceRegion(Region sourceRegion) { if (sourceRegion == null) { throw new NullPointerException("Region cannot be null."); } updateStatus(Properties.SOURCE_REGION, Status.ALREADY_SET); this.sourceRegion = sourceRegion; return this; } public Builder<T> sourceRegion(Position position, Size size) { if (position == null) { throw new NullPointerException("Position cannot be null."); } if (size == null) { throw new NullPointerException("Size cannot be null."); } return sourceRegion(new Region(position, size)); } public Builder<T> sourceRegion(int x, int y, int width, int height) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException( "Width and height must be greater than 0." ); } return sourceRegion( new Coordinate(x, y), new AbsoluteSize(width, height) ); } public Builder<T> sourceRegion(Position position, int width, int height) { if (position == null) { throw new NullPointerException("Position cannot be null."); } if (width <= 0 || height <= 0) { throw new IllegalArgumentException( "Width and height must be greater than 0." ); } return sourceRegion( position, new AbsoluteSize(width, height) ); } public Builder<T> sourceRegion(Rectangle region) { if (region == null) { throw new NullPointerException("Region cannot be null."); } return sourceRegion( new Coordinate(region.x, region.y), new AbsoluteSize(region.getSize()) ); } public Builder<T> imageType(int type) { updateStatus(Properties.IMAGE_TYPE, Status.ALREADY_SET); imageType = type; return this; } public Builder<T> scalingMode(ScalingMode config) { checkForNull(config, "Scaling mode is null."); updateStatus(Properties.SCALING_MODE, Status.ALREADY_SET); updateStatus(Properties.RESIZER, Status.CANNOT_SET); scalingMode = config; return this; } public Builder<T> resizer(Resizer resizer) { checkForNull(resizer, "Resizer is null."); updateStatus(Properties.RESIZER, Status.ALREADY_SET); updateStatus(Properties.SCALING_MODE, Status.CANNOT_SET); this.resizer = resizer; return this; } public Builder<T> alphaInterpolation(AlphaInterpolation config) { checkForNull(config, "Alpha interpolation is null."); updateStatus(Properties.ALPHA_INTERPOLATION, Status.ALREADY_SET); alphaInterpolation = config; return this; } public Builder<T> dithering(Dithering config) { checkForNull(config, "Dithering is null."); updateStatus(Properties.DITHERING, Status.ALREADY_SET); dithering = config; return this; } public Builder<T> antialiasing(Antialiasing config) { checkForNull(config, "Antialiasing is null."); updateStatus(Properties.ANTIALIASING, Status.ALREADY_SET); antialiasing = config; return this; } public Builder<T> rendering(Rendering config) { checkForNull(config, "Rendering is null."); updateStatus(Properties.RENDERING, Status.ALREADY_SET); rendering = config; return this; } public Builder<T> keepAspectRatio(boolean keep) { if (statusMap.get(Properties.SCALE) == Status.ALREADY_SET) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio if the scaling factor has " + "already been specified."); } if (statusMap.get(Properties.SIZE) == Status.NOT_READY) { throw new IllegalStateException("Cannot specify whether to " + "keep the aspect ratio unless the size parameter has " + "already been specified."); } if ((statusMap.get(Properties.WIDTH) == Status.ALREADY_SET || statusMap.get(Properties.HEIGHT) == Status.ALREADY_SET) && !keep ) { throw new IllegalStateException("The aspect ratio must be " + "preserved when the width and/or height parameter " + "has already been specified."); } updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET); keepAspectRatio = keep; return this; } public Builder<T> outputQuality(float quality) { if (quality < 0.0f || quality > 1.0f) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0f and " + "1.0f, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = quality; return this; } public Builder<T> outputQuality(double quality) { if (quality < 0.0d || quality > 1.0d) { throw new IllegalArgumentException( "The quality setting must be in the range 0.0d and " + "1.0d, inclusive." ); } updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET); outputQuality = (float)quality; if (outputQuality < 0.0f) { outputQuality = 0.0f; } else if (outputQuality > 1.0f) { outputQuality = 1.0f; } return this; } public Builder<T> outputFormat(String format) { if (!ThumbnailatorUtils.isSupportedOutputFormat(format)) { throw new IllegalArgumentException( "Specified format is not supported: " + format ); } updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET); outputFormat = format; return this; } public Builder<T> outputFormatType(String formatType) { /* * If the output format is the original format, and the format type * is being specified, it's going to be likely that the specified * type will not be present in all the formats, so we'll disallow * it. (e.g. setting type to "JPEG", and if the original formats * were JPEG and PNG, then we'd have a problem. */ if (formatType != ThumbnailParameter.DEFAULT_FORMAT_TYPE && outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalArgumentException( "Cannot set the format type if a specific output " + "format has not been specified." ); } if (!ThumbnailatorUtils.isSupportedOutputFormatType(outputFormat, formatType)) { throw new IllegalArgumentException( "Specified format type (" + formatType + ") is not " + " supported for the format: " + outputFormat ); } /* * If the output format type is set, then we'd better make the * output format unchangeable, or else we'd risk having a type * that is not part of the output format. */ updateStatus(Properties.OUTPUT_FORMAT_TYPE, Status.ALREADY_SET); if (!statusMap.containsKey(Properties.OUTPUT_FORMAT)) { updateStatus(Properties.OUTPUT_FORMAT, Status.CANNOT_SET); } outputFormatType = formatType; return this; } /** * Sets the watermark to apply on the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param w The watermark to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> watermark(Watermark w) { if (w == null) { throw new NullPointerException("Watermark is null."); } filterPipeline.add(w); return this; } /** * Sets the image of the watermark to apply on the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%, and the position is set to center of the * thumbnail: * <p> * <pre> watermark(Positions.CENTER, image, 0.5f); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image) { return watermark(Positions.CENTER, image, 0.5f); } /** * Sets the image and opacity of the watermark to apply on * the thumbnail. * <p> * This method is a convenience method for the * {@link #watermark(Position, BufferedImage, float)} method, where * the opacity is 50%: * <p> * <pre> watermark(Positions.CENTER, image, opacity); * </pre> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(BufferedImage image, float opacity) { return watermark(Positions.CENTER, image, opacity); } /** * Sets the image and opacity and position of the watermark to apply on * the thumbnail. * <p> * This method can be called multiple times to apply multiple * watermarks. * <p> * If multiple watermarks are to be applied, the watermarks will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param position The position of the watermark. * @param image The image of the watermark. * @param opacity The opacity of the watermark. * <p> * The value should be between {@code 0.0f} and * {@code 1.0f}, where {@code 0.0f} is completely * transparent, and {@code 1.0f} is completely * opaque. * @return Reference to this object. */ public Builder<T> watermark(Position position, BufferedImage image, float opacity) { filterPipeline.add(new Watermark(position, image, opacity)); return this; } /* * rotation */ /** * Sets the amount of rotation to apply to the thumbnail. * <p> * The thumbnail will be rotated clockwise by the angle specified. * <p> * This method can be called multiple times to apply multiple * rotations. * <p> * If multiple rotations are to be applied, the rotations will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param angle Angle in degrees. * @return Reference to this object. */ public Builder<T> rotate(double angle) { filterPipeline.add(Rotation.newRotator(angle)); return this; } /* * other filters */ /** * Adds a {@link ImageFilter} to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filter An image filter to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilter(ImageFilter filter) { if (filter == null) { throw new NullPointerException("Filter is null."); } filterPipeline.add(filter); return this; } /** * Adds multiple {@link ImageFilter}s to apply to the thumbnail. * <p> * This method can be called multiple times to apply multiple * filters. * <p> * If multiple filters are to be applied, the filters will be * applied in the order that this method is called. * <p> * Calling this method to set this parameter is optional. * * @param filters A list of filters to apply to the thumbnail. * @return Reference to this object. */ public Builder<T> addFilters(List<ImageFilter> filters) { if (filters == null) { throw new NullPointerException("Filters is null."); } filterPipeline.addAll(filters); return this; } private void checkReadiness() { for (Map.Entry<Properties, Status> s : statusMap.entrySet()) { if (s.getValue() == Status.NOT_READY) { throw new IllegalStateException(s.getKey().getName() + " is not set."); } } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @return The {@link Resizer} which is suitable for the * current builder state. */ private Resizer makeResizer() { /* * If the scalingMode has been set, then use scalingMode to obtain * a resizer, else, use the resizer field. */ if (statusMap.get(Properties.SCALING_MODE) == Status.ALREADY_SET) { return makeResizer(scalingMode); } else { return this.resizer; } } /** * Returns a {@link Resizer} which is suitable for the current * builder state. * * @param mode The scaling mode to use to create thumbnails. * @return The {@link Resizer} which is suitable for the * specified scaling mode and builder state. */ private Resizer makeResizer(ScalingMode mode) { Map<RenderingHints.Key, Object> hints = new HashMap<RenderingHints.Key, Object>(); hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation.getValue()); hints.put(RenderingHints.KEY_DITHERING, dithering.getValue()); hints.put(RenderingHints.KEY_ANTIALIASING, antialiasing.getValue()); hints.put(RenderingHints.KEY_RENDERING, rendering.getValue()); if (mode == ScalingMode.BILINEAR) { return new BilinearResizer(hints); } else if (mode == ScalingMode.BICUBIC) { return new BicubicResizer(hints); } else if (mode == ScalingMode.PROGRESSIVE_BILINEAR) { return new ProgressiveBilinearResizer(hints); } else { return new ProgressiveBilinearResizer(hints); } } /** * Returns a {@link ThumbnailParameter} from the current builder state. * * @return A {@link ThumbnailParameter} from the current * builder state. */ private ThumbnailParameter makeParam() { Resizer resizer = makeResizer(); int imageTypeToUse = imageType; if (imageType == IMAGE_TYPE_UNSPECIFIED) { imageTypeToUse = ThumbnailParameter.ORIGINAL_IMAGE_TYPE; } if (Double.isNaN(scale)) { // If the dimensions were specified, do the following. // Check that at least one dimension is specified. // If it's not, it's a bug. if ( width == DIMENSION_NOT_SPECIFIED && height == DIMENSION_NOT_SPECIFIED ) { throw new IllegalStateException( "The width or height must be specified. If this " + "exception is thrown, it is due to a bug in the " + "Thumbnailator library." ); } // Set the unspecified dimension to a default value. if (width == DIMENSION_NOT_SPECIFIED) { width = Integer.MAX_VALUE; } if (height == DIMENSION_NOT_SPECIFIED) { height = Integer.MAX_VALUE; } return new ThumbnailParameter( new Dimension(width, height), sourceRegion, keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } else { // If the scaling factor was specified return new ThumbnailParameter( scale, sourceRegion, keepAspectRatio, outputFormat, outputFormatType, outputQuality, imageTypeToUse, filterPipeline.getFilters(), resizer ); } } /** * Create the thumbnails and return as a {@link Iterable} of * {@link BufferedImage}s. * <p> * For situations where multiple thumbnails are being generated, this * method is preferred over the {@link #asBufferedImages()} method, * as (1) the processing does not have to complete before the method * returns and (2) the thumbnails can be retrieved one at a time, * potentially reducing the number of thumbnails which need to be * retained in the heap memory, potentially reducing the chance of * {@link OutOfMemoryError}s from occurring. * <p> * If an {@link IOException} occurs during the processing of the * thumbnail, the {@link Iterable} will return a {@code null} for that * element. * * @return An {@link Iterable} which will provide an * {@link Iterator} which returns thumbnails as * {@link BufferedImage}s. */ public Iterable<BufferedImage> iterableBufferedImages() { checkReadiness(); /* * TODO To get the precise error information, there would have to * be an event notification mechanism. */ return new BufferedImageIterable(); } /** * Create the thumbnails and return as a {@link List} of * {@link BufferedImage}s. * <p> * <h3>Note about performance</h3> * If there are many thumbnails generated at once, it is possible that * the Java virtual machine's heap space will run out and an * {@link OutOfMemoryError} could result. * <p> * If many thumbnails are being processed at once, then using the * {@link #iterableBufferedImages()} method would be preferable. * * @return A list of thumbnails. * @throws IOException If an problem occurred during * the reading of the original * images. */ public List<BufferedImage> asBufferedImages() throws IOException { checkReadiness(); List<BufferedImage> thumbnails = new ArrayList<BufferedImage>(); // Create thumbnails for (ImageSource<T> source : sources) { BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); thumbnails.add(destination.getSink()); } return thumbnails; } public BufferedImage asBufferedImage() throws IOException { checkReadiness(); Iterator<ImageSource<T>> iter = sources.iterator(); ImageSource<T> source = iter.next(); if (iter.hasNext()) { throw new IllegalArgumentException("Cannot create one thumbnail from multiple original images."); } BufferedImageSink destination = new BufferedImageSink(); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination) ); return destination.getSink(); } /** * Creates the thumbnails and stores them to the files, and returns * a {@link List} of {@link File}s to the thumbnails. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * <p> * If the destination file already exists, then the file will be * overwritten. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @return A list of {@link File}s of the thumbnails * which were created. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public List<File> asFiles(Iterable<File> iterable) throws IOException { return asFiles(iterable, true); } /** * Creates the thumbnails and stores them to the files, and returns * a {@link List} of {@link File}s to the thumbnails. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @param allowOverwrite Whether or not to overwrite the destination * file if it already exists. * @return A list of {@link File}s of the thumbnails * which were created. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. * @since 0.3.7 */ public List<File> asFiles(Iterable<File> iterable, boolean allowOverwrite) throws IOException { checkReadiness(); if (iterable == null) { throw new NullPointerException("File name iterable is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); Iterator<File> filenameIter = iterable.iterator(); for (ImageSource<T> source : sources) { if (!filenameIter.hasNext()) { throw new IndexOutOfBoundsException( "Not enough file names provided by iterator." ); } FileImageSink destination = new FileImageSink(filenameIter.next(), allowOverwrite); try { Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(param, source, destination) ); destinationFiles.add(destination.getSink()); } catch (IllegalArgumentException e) { } } return destinationFiles; } /** * Creates the thumbnails and stores them to the files. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. */ public void toFiles(Iterable<File> iterable) throws IOException { asFiles(iterable); } /** * Creates the thumbnails and stores them to the files. * <p> * The file names for the thumbnails are obtained from the given * {@link Iterable}. * * @param iterable An {@link Iterable} which returns an * {@link Iterator} which returns file names * which should be assigned to each thumbnail. * @param allowOverwrite Whether or not to overwrite the destination * file if it already exists. * @throws IOException If a problem occurs while reading the * original images or writing the thumbnails * to files. * @since 0.3.7 */ public void toFiles(Iterable<File> iterable, boolean allowOverwrite) throws IOException { asFiles(iterable, allowOverwrite); } public List<File> asFiles(Rename rename) throws IOException { return asFiles(rename, true); } public List<File> asFiles(Rename rename, boolean allowOverwrite) throws IOException { checkReadiness(); if (rename == null) { throw new NullPointerException("Rename is null."); } List<File> destinationFiles = new ArrayList<File>(); ThumbnailParameter param = makeParam(); for (ImageSource<T> source : sources) { if (!(source instanceof FileImageSource)) { throw new IllegalStateException("Cannot create thumbnails to files if original images are not from files."); } File f = ((FileImageSource)source).getSource(); File destinationFile = new File(f.getParent(), rename.apply(f.getName())); FileImageSink destination = new FileImageSink(destinationFile, allowOverwrite); try { Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(param, source, destination) ); destinationFiles.add(destination.getSink()); } catch (IllegalArgumentException e) { } } return destinationFiles; } public void toFiles(Rename rename) throws IOException { asFiles(rename); } public void toFiles(Rename rename, boolean allowOverwrite) throws IOException { asFiles(rename, allowOverwrite); } public void toFile(File outFile) throws IOException { toFile(outFile, true); } public void toFile(File outFile, boolean allowOverwrite) throws IOException { checkReadiness(); Iterator<ImageSource<T>> iter = sources.iterator(); ImageSource<T> source = iter.next(); if (iter.hasNext()) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } FileImageSink destination = new FileImageSink(outFile, allowOverwrite); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination) ); } public void toFile(String outFilepath) throws IOException { toFile(outFilepath, true); } public void toFile(String outFilepath, boolean allowOverwrite) throws IOException { checkReadiness(); Iterator<ImageSource<T>> iter = sources.iterator(); ImageSource<T> source = iter.next(); if (iter.hasNext()) { throw new IllegalArgumentException("Cannot output multiple thumbnails to one file."); } FileImageSink destination = new FileImageSink(outFilepath, allowOverwrite); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination) ); } public void toOutputStream(OutputStream os) throws IOException { checkReadiness(); Iterator<ImageSource<T>> iter = sources.iterator(); ImageSource<T> source = iter.next(); if (iter.hasNext()) { throw new IllegalArgumentException("Cannot output multiple thumbnails to a single OutputStream."); } /* * if the image is from a BufferedImage, then we require that the * output format be set. (or else, we can't tell what format to * output as!) */ if (source instanceof BufferedImageSource) { if (outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalStateException( "Output format not specified." ); } } OutputStreamImageSink destination = new OutputStreamImageSink(os); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, OutputStream>(makeParam(), source, destination) ); } public void toOutputStreams(Iterable<? extends OutputStream> iterable) throws IOException { checkReadiness(); if (iterable == null) { throw new NullPointerException("OutputStream iterable is null."); } Iterator<? extends OutputStream> osIter = iterable.iterator(); for (ImageSource<T> source : sources) { /* * if the image is from a BufferedImage, then we require that the * output format be set. (or else, we can't tell what format to * output as!) */ if (source instanceof BufferedImageSource) { if (outputFormat == ThumbnailParameter.ORIGINAL_FORMAT) { throw new IllegalStateException( "Output format not specified." ); } } if (!osIter.hasNext()) { throw new IndexOutOfBoundsException( "Not enough file names provided by iterator." ); } OutputStreamImageSink destination = new OutputStreamImageSink(osIter.next()); Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<T, OutputStream>(makeParam(), source, destination) ); } } } }
package de.thecode.android.tazreader.data; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.LabeledIntent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.net.Uri; import android.text.TextUtils; import com.commonsware.cwac.provider.StreamProvider; import com.dd.plist.NSArray; import com.dd.plist.NSDictionary; import com.dd.plist.NSObject; import com.dd.plist.NSString; import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListParser; import de.thecode.android.tazreader.BuildConfig; import de.thecode.android.tazreader.R; import de.thecode.android.tazreader.data.Paper.Plist.Page.Article; import de.thecode.android.tazreader.utils.PlistHelper; import de.thecode.android.tazreader.utils.ReadableException; import de.thecode.android.tazreader.utils.StorageManager; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.json.JSONArray; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import timber.log.Timber; @Entity(tableName = "PAPER") public class Paper extends Downloadable { public static final String STORE_KEY_BOOKMARKS = "bookmarks"; public static final String STORE_KEY_CURRENTPOSITION = "currentPosition"; public static final String STORE_KEY_POSITION_IN_ARTICLE = "positionInArticle"; public static final String STORE_KEY_RESOURCE_PARTNER = "resource"; public static final String STORE_KEY_AUTO_DOWNLOADED = "auto_download"; public static final String CONTENT_PLIST_FILENAME = "content.plist"; @NonNull @PrimaryKey private String bookId; private String date; private String image; private String imageHash; private String link; private long lastModified; private String resource; private boolean demo; private String title; private long validUntil; private String publication; @Ignore private Map<String, Integer> articleCollectionOrder; @Ignore private Map<Integer, String> articleCollectionPositionIndex; public Paper() { } public Paper(NSDictionary nsDictionary) { this.date = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.DATE); this.image = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.IMAGE); this.imageHash = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.IMAGEHASH); this.link = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.LINK); this.fileHash = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.FILEHASH); this.len = PlistHelper.getInt(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.LEN); this.lastModified = PlistHelper.getInt(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.LASTMODIFIED); this.bookId = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.BOOKID); this.demo = PlistHelper.getBoolean(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.ISDEMO); this.resource = PlistHelper.getString(nsDictionary, de.thecode.android.tazreader.sync.model.Plist.Fields.RESOURCE); } @NonNull public String getBookId() { return bookId; } public String getDate(int style) throws ParseException { SimpleDateFormat outformat = (SimpleDateFormat) DateFormat.getDateInstance(style); return outformat.format(parseDate()); } private Date parseDate() throws ParseException { SimpleDateFormat informat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); return informat.parse(this.date); } public String getTitelWithDate(String seperator) { try { return getTitle() + " " + seperator + " " + getDate(DateFormat.MEDIUM); } catch (ParseException e) { return getTitle(); } } public String getTitelWithDate(Context context) { return getTitelWithDate(context.getString(R.string.string_titel_seperator)); } public String getTitelWithDate(Resources resources) { return getTitelWithDate(resources.getString(R.string.string_titel_seperator)); } public String getImage() { return image; } public boolean isDemo() { return demo; } public String getDate() { return date; } public long getDateInMillis() { try { return new SimpleDateFormat("yyyy-MM-dd", Locale.GERMANY).parse(getDate()) .getTime(); } catch (ParseException e) { return 0; } } public void setDate(String date) { this.date = date; } public String getImageHash() { return imageHash; } public void setImageHash(String imageHash) { this.imageHash = imageHash; } public void setImage(String image) { this.image = image; } public void setLastModified(long lastModified) { this.lastModified = lastModified; } public void setDemo(boolean isDemo) { this.demo = isDemo; } public void setLink(String link) { this.link = link; } public String getLink() { return link; } public long getLastModified() { return lastModified; } public void setBookId(String bookId) { this.bookId = bookId; } public String getTitle() { if (title == null) return ""; return title; } public void setPublication(String publication) { this.publication = publication; } public String getPublication() { return publication; } public void setTitle(String title) { this.title = title; } public long getValidUntil() { return validUntil; } public void setValidUntil(long validUntil) { this.validUntil = validUntil; } public void setResource(String resource) { this.resource = resource; } public String getResource() { return resource; } public int getArticleCollectionOrderPosition(String key) { return articleCollectionOrder.get(key); } public int getArticleCollectionSize() { return articleCollectionOrder.size(); } public String getArticleCollectionOrderKey(int postion) { return articleCollectionPositionIndex.get(postion); } public void setArticleCollectionOrder(Map<String, Integer> articleCollectionOrder) { this.articleCollectionOrder = articleCollectionOrder; } public void setArticleCollectionPositionIndex(Map<Integer, String> articleCollectionPositionIndex) { this.articleCollectionPositionIndex = articleCollectionPositionIndex; } @Ignore private Plist plist; public void parsePlist(File file) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException { parsePlist(file, true); } public void parsePlist(File file, boolean parseIndex) throws ParserConfigurationException, ParseException, SAXException, PropertyListFormatException, IOException { FileInputStream fis = new FileInputStream(file); parsePlist(fis, parseIndex); } public void parsePlist(InputStream is) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException { parsePlist(is, true); } public void parsePlist(InputStream is, boolean parseIndex) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException { Timber.i("Start parsing Plist - parse Index: %s", parseIndex); plist = new Plist(is, parseIndex); Timber.i("Finished parsing Plist"); } public Plist getPlist() { if (plist == null) throw new IllegalStateException("No Plist parsed. Call parsePlist() before!"); return plist; } public boolean parseMissingAttributes(boolean overwrite) { boolean result = false; //Did you write somthing new? if (TextUtils.isEmpty(getResource()) || overwrite) { setResource(getPlist().getResource()); result = true; } return result; } public class Plist { private static final String KEY_ARCHIVEURL = "ArchivUrl"; private static final String KEY_BOOKID = "BookId"; private static final String KEY_RESOURCE = "ressource"; private static final String KEY_MINVERSION = "MinVersion"; private static final String KEY_VERSION = "Version"; private static final String KEY_HASHVALS = "HashVals"; private static final String KEY_SOURCES = "Quellen"; private static final String KEY_TOPLINKS = "TopLinks"; private String archiveUrl; private String bookId; private String resource; private String minVersion; private String version; private Map<String, String> hashVals; private NSDictionary root; private List<Source> sources; private List<TopLink> toplinks; private Map<String, ITocItem> indexMap = new LinkedHashMap<>(); public Plist(InputStream is, boolean parseIndex) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException { root = (NSDictionary) PropertyListParser.parse(is); is.close(); archiveUrl = PlistHelper.getString(root, KEY_ARCHIVEURL); bookId = PlistHelper.getString(root, KEY_BOOKID); resource = PlistHelper.getString(root, KEY_RESOURCE); if (!TextUtils.isEmpty(resource)) { resource = resource.replace(".res", ""); } minVersion = PlistHelper.getString(root, KEY_MINVERSION); version = PlistHelper.getString(root, KEY_VERSION); parseHashVals(); if (parseIndex) { parseSources(); parseToplinks(); } } private void parseHashVals() { hashVals = new HashMap<>(); if (root.containsKey(KEY_HASHVALS)) { NSDictionary hashValsDict = (NSDictionary) root.objectForKey(KEY_HASHVALS); Set<Map.Entry<String, NSObject>> set = hashValsDict.entrySet(); for (Map.Entry<String, NSObject> stringNSObjectEntry : set) { hashVals.put(stringNSObjectEntry.getKey(), ((NSString) stringNSObjectEntry.getValue()).getContent()); } } } private void parseSources() { sources = new ArrayList<>(); if (root.containsKey(KEY_SOURCES)) { NSObject[] sourcesArray = ((NSArray) root.objectForKey(KEY_SOURCES)).getArray(); if (sourcesArray != null) { // result = new Source[sources.length]; for (NSObject sourceObject : sourcesArray) { NSDictionary sourceDict = (NSDictionary) sourceObject; String key = sourceDict.allKeys()[0]; Source source = new Source(key, (NSArray) sourceDict.objectForKey(key)); indexMap.put(source.getKey(), source); source.parseBooks(); sources.add(source); } } } } private void parseToplinks() { toplinks = new ArrayList<>(); if (root.containsKey(KEY_TOPLINKS)) { NSObject[] toplinksArray = ((NSArray) root.objectForKey(KEY_TOPLINKS)).getArray(); if (toplinksArray != null) { for (NSObject toplinkeObject : toplinksArray) { NSDictionary toplinkDict = (NSDictionary) toplinkeObject; String key = toplinkDict.allKeys()[0]; TopLink toplink = new TopLink(key, PlistHelper.getString(toplinkDict, key)); boolean foundDefaultPageLink = false; for (Source source : getSources()) { for (Book book : source.getBooks()) { for (Category category : book.getCategories()) { for (Page page : category.getPages()) { if (toplink.getKey() .equals(page.getDefaultLink())) { toplink.page = page; foundDefaultPageLink = true; } if (foundDefaultPageLink) break; } if (foundDefaultPageLink) break; } if (foundDefaultPageLink) break; } if (foundDefaultPageLink) break; } if (indexMap.containsKey(toplink.getKey())) { toplink.setLink(indexMap.get(toplink.getKey())); } else { indexMap.put(toplink.getKey(), toplink); } toplinks.add(toplink); } } } } public String getArchiveUrl() { return archiveUrl; } public String getBookId() { return bookId; } public String getResource() { return resource; } public String getMinVersion() { return minVersion; } public String getVersion() { return version; } public Map<String, String> getHashVals() { return hashVals; } public List<Source> getSources() { return sources; } public List<TopLink> getToplinks() { return toplinks; } public ArrayList<Page> getAllPages() { ArrayList<Page> result = new ArrayList<>(); for (Source aSource : getSources()) { for (Book aBook : aSource.getBooks()) { for (Category aCategory : aBook.getCategories()) { result.addAll(aCategory.getPages()); } } } return result; } public ITocItem getIndexItem(String key) { return indexMap.get(key); } public class Source extends TocItemTemplate { String key; NSArray array; List<Book> books; public Source(String key, NSArray array) { this.key = key; this.array = array; } public String getKey() { return key; } private void parseBooks() { books = new ArrayList<>(); NSObject[] sourceBooks = array.getArray(); if (sourceBooks != null) { for (NSObject sourceBook : sourceBooks) { NSDictionary sourceBookDict = (NSDictionary) sourceBook; String key = sourceBookDict.allKeys()[0]; Book book = new Book(this, key, (NSArray) sourceBookDict.objectForKey(key)); book.parseCategories(); books.add(book); } } } @Override public String getTitle() { return getKey(); } public List<Book> getBooks() { if (books == null) throw new IllegalStateException("Books not parsed yet, call parseBooks() before"); return books; } @Override public ITocItem getIndexParent() { return null; } @Override public boolean hasIndexParent() { return false; } @Override public boolean hasIndexChilds() { if (books != null) { for (Book book : getBooks()) { if (book.categories != null) { if (book.categories.size() > 0) return true; } } } return false; } @Override public List<ITocItem> getIndexChilds() { List<ITocItem> resultList = new ArrayList<>(); if (hasIndexChilds()) { for (Book book : getBooks()) { resultList.addAll(book.getCategories()); } return resultList; } return null; } } public class Book { Source source; String key; NSArray array; List<Category> categories; public Book(Source source, String key, NSArray array) { this.source = source; this.key = source.getKey() + "_" + key; this.array = array; } private void parseCategories() { categories = new ArrayList<>(); NSObject[] sourceBookCategories = array.getArray(); if (sourceBookCategories != null) { for (NSObject sourceBookCategory : sourceBookCategories) { NSDictionary sourceBookCategoryDict = (NSDictionary) sourceBookCategory; String key = sourceBookCategoryDict.allKeys()[0]; Category category = new Category(this, key, (NSArray) sourceBookCategoryDict.objectForKey(key)); indexMap.put(category.getKey(), category); category.parsePages(); category.parseRealPagesForArticles(); categories.add(category); } } } public String getKey() { return key; } public Source getSource() { return source; } public List<Category> getCategories() { if (categories == null) throw new IllegalStateException("Categories not parsed yet, call parseCategeories() before"); return categories; } } public class Category extends TocItemTemplate { Book book; String key; String title; NSArray array; List<Page> pages; public Category(Book book, String key, NSArray array) { this.book = book; //Da Key nicht einzigartig in PList this.key = book.getKey() + "_" + key + "_" + book.getCategories() .size(); this.title = key; this.array = array; } public Book getBook() { return book; } private void parsePages() { pages = new ArrayList<>(); NSObject[] sourceBookCategoryPages = array.getArray(); if (sourceBookCategoryPages != null) { for (NSObject sourceBookCategoryPage : sourceBookCategoryPages) { NSDictionary sourceBookCategoryPageDict = (NSDictionary) sourceBookCategoryPage; String key = sourceBookCategoryPageDict.allKeys()[0]; Page page = new Page(this, key, (NSDictionary) sourceBookCategoryPageDict.objectForKey(key)); indexMap.put(page.getKey(), page); for (Article article : page.getArticles()) { indexMap.put(article.getKey(), article); } pages.add(page); } } } private void parseRealPagesForArticles() { List<Article> allArticlesFromCategory = new ArrayList<>(); for (Page aPage : getPages()) { allArticlesFromCategory.addAll(aPage.getArticles()); } for (Article aArticle : allArticlesFromCategory) { for (Page aPage : getPages()) { for (Page.Geometry aGeometry : aPage.getGeometries()) { if (aGeometry.getLink() .equals(aArticle.getKey())) { aArticle.setRealPage(aPage); break; } } if (aArticle.getRealPage() != null) break; } } } @Override public String getTitle() { return title; } public List<Page> getPages() { if (pages == null) throw new IllegalStateException("Pages not parsed yet, call parsePages() before"); return pages; } public String getKey() { return key; } @Override public ITocItem getIndexParent() { return getBook().getSource(); } @Override public boolean hasIndexParent() { return true; } @Override public boolean hasIndexChilds() { if (pages != null) { return pages.size() > 0; } return false; } @Override public List<ITocItem> getIndexChilds() { List<ITocItem> resultList = new ArrayList<>(); if (hasIndexChilds()) { for (Page page : getPages()) { //resultList.add(page); resultList.addAll(page.getArticles()); } return resultList; } return null; } } public class Page extends TocItemTemplate { private static final String KEY_GEOMETRY = "geometry"; private static final String KEY_PAGINA = "SeitenNummer"; private static final String KEY_DEFAULTLINK = "defaultLink"; private static final String KEY_ARTICLE = "Artikel"; private static final String KEY_RIGHT = "right"; private static final String KEY_LEFT = "left"; Category category; String key; String pagina; String defaultLink; String left; String right; NSArray geometryArray; NSArray articleArray; List<Geometry> geometries; List<Article> articles; public Page(Category category, String key, NSDictionary dict) { this.category = category; this.key = key; if (dict != null) { pagina = PlistHelper.getString(dict, KEY_PAGINA); left = PlistHelper.getString(dict, KEY_LEFT); right = PlistHelper.getString(dict, KEY_RIGHT); defaultLink = PlistHelper.getString(dict, KEY_DEFAULTLINK); geometryArray = (NSArray) dict.get(KEY_GEOMETRY); articleArray = (NSArray) dict.get(KEY_ARTICLE); parseGeometries(); parseArticles(); } } private void parseGeometries() { geometries = new ArrayList<>(); NSObject[] sourceBookCategoryPageGeometries = geometryArray.getArray(); if (sourceBookCategoryPageGeometries != null) { for (NSObject sourceBookCategoryPageGeometry : sourceBookCategoryPageGeometries) { NSDictionary sourceBookCategoryPageGeometryDict = (NSDictionary) sourceBookCategoryPageGeometry; geometries.add(new Geometry(sourceBookCategoryPageGeometryDict)); } } } private void parseArticles() { articles = new ArrayList<>(); NSObject[] sourceBookCategoryPageArticles = articleArray.getArray(); if (sourceBookCategoryPageArticles != null) { for (NSObject sourceBookCategoryPageArticle : sourceBookCategoryPageArticles) { NSDictionary sourceBookCategoryPageArticleDict = (NSDictionary) sourceBookCategoryPageArticle; String key = sourceBookCategoryPageArticleDict.allKeys()[0]; Article article = new Article(key, (NSDictionary) sourceBookCategoryPageArticleDict.get(key)); articles.add(article); } } } public List<Article> getArticles() { if (articles == null) throw new IllegalStateException("Articles not parsed yet, call parseArticles() before"); return articles; } public List<Geometry> getGeometries() { if (geometries == null) throw new IllegalStateException("Geometries not parsed yet, call parseGeometries() before"); return geometries; } @Override public String getTitle() { return category.getTitle() + " " + pagina; } public String getDefaultLink() { return defaultLink; } public Category getCategory() { return category; } public String getKey() { return key; } @Override public ITocItem getIndexParent() { return getCategory(); } @Override public boolean hasIndexParent() { return true; } @Override public boolean hasIndexChilds() { return false; } @Override public List<ITocItem> getIndexChilds() { return null; } @Override public boolean isShareable() { return true; } @Override public Intent getShareIntent(Context context) { StorageManager storage = StorageManager.getInstance(context); File pdfFile = new File(storage.getPaperDirectory(getPaper()), getKey()); File papersDir = storage.get(StorageManager.PAPER); try { String pagePath = pdfFile.getCanonicalPath() .replace(papersDir.getCanonicalPath(), "papers"); Uri contentUri = StreamProvider.getUriForFile(BuildConfig.APPLICATION_ID + ".streamprovider", pdfFile); //share Intent Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("application/pdf"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra(Intent.EXTRA_STREAM, contentUri); intent.putExtra(Intent.EXTRA_SUBJECT, getPaper().getTitelWithDate(context) + ": " + getTitle()); intent.putExtra(Intent.EXTRA_TEXT, getPaper().getTitelWithDate(context) + "\n" + getTitle()); //get extra intents to view pdf Intent viewIntent = new Intent(Intent.ACTION_VIEW); viewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); viewIntent.setData(contentUri); PackageManager packageManager = context.getPackageManager(); List<ResolveInfo> resInfo = packageManager.queryIntentActivities(viewIntent, 0); Intent[] extraIntents = new Intent[resInfo.size()]; for (int i = 0; i < resInfo.size(); i++) { // Extract the label, append it, and repackage it in a LabeledIntent ResolveInfo ri = resInfo.get(i); String packageName = ri.activityInfo.packageName; Intent extraViewIntent = new Intent(); extraViewIntent.setComponent(new ComponentName(packageName, ri.activityInfo.name)); extraViewIntent.setAction(Intent.ACTION_VIEW); extraViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); extraViewIntent.setData(contentUri); CharSequence label = ri.loadLabel(packageManager); extraIntents[i] = new LabeledIntent(extraViewIntent, packageName, label, ri.icon); } Intent chooserIntent = Intent.createChooser(intent, context.getString(R.string.reader_action_share_open)); if (extraIntents.length > 0) chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents); return chooserIntent; } catch (IOException e) { e.printStackTrace(); } return null; } public class Geometry { private static final String KEY_X1 = "x1"; private static final String KEY_Y1 = "y1"; private static final String KEY_X2 = "x2"; private static final String KEY_Y2 = "y2"; private static final String KEY_LINK = "link"; private float x1; private float y1; private float x2; private float y2; private String link; //private Article article; public Geometry(NSDictionary dict) { this.x1 = PlistHelper.getFloat(dict, KEY_X1); this.y1 = PlistHelper.getFloat(dict, KEY_Y1); this.x2 = PlistHelper.getFloat(dict, KEY_X2); this.y2 = PlistHelper.getFloat(dict, KEY_Y2); this.link = PlistHelper.getString(dict, KEY_LINK); } public float getX1() { return x1; } public float getY1() { return y1; } public float getX2() { return x2; } public float getY2() { return y2; } public String getLink() { return link; } public String getCleanLink() { if (link!=null) return link.replaceFirst("^(\\./)+",""); return null; } public Page getPage() { return Page.this; } public boolean checkCoordinates(float x, float y) { return x >= x1 && x <= x2 && y >= y1 && y <= y2; } // public Article getArticle() { // return article; } public class Article extends TocItemTemplate //implements ArticleReaderItem { private static final String KEY_TITLE = "Titel"; private static final String KEY_SUBTITLE = "Untertitel"; private static final String KEY_AUTHOR = "Autor"; private static final String KEY_ONLINELINK = "OnlineLink"; private static final String KEY_AUDIOLINK = "AudioLink"; private String key; private String title; private String subtitle; private String author; private String onlinelink; private String audiolink; private Page realPage; public Article(String key, NSDictionary dict) { this.key = key; this.title = PlistHelper.getString(dict, KEY_TITLE); this.subtitle = PlistHelper.getString(dict, KEY_SUBTITLE); this.author = PlistHelper.getString(dict, KEY_AUTHOR); this.onlinelink = PlistHelper.getString(dict, KEY_ONLINELINK); this.audiolink = PlistHelper.getString(dict, KEY_AUDIOLINK); } public String getKey() { return key; } public String getTitle() { if (TextUtils.isEmpty(title)) { if (getRealPage() != null && !TextUtils.isEmpty(getRealPage().getTitle())) { return getRealPage().getTitle(); } } return title; } public String getSubtitle() { return subtitle; } public String getAuthor() { return author; } public String getOnlinelink() { return onlinelink; } public String getAudiolink() { return audiolink; } public Category getCategory() { return category; } public Page getRealPage() { return realPage; } public void setRealPage(Page realPage) { this.realPage = realPage; } public Page getPage() { return Page.this; } // public void setBookmarked(boolean bookmarked) { // this.bookmarked = bookmarked; // public boolean isBookmarked() { // return bookmarked; @Override public boolean isBookmarkable() { return true; } @Override public ITocItem getIndexParent() { return getPage().getCategory(); } @Override public boolean hasIndexParent() { return true; } @Override public boolean hasIndexChilds() { return false; } @Override public List<ITocItem> getIndexChilds() { return null; } @Override public boolean isShareable() { return !TextUtils.isEmpty(onlinelink); } @Override public Intent getShareIntent(Context context) { StringBuilder text = new StringBuilder(getPaper().getTitelWithDate(context)).append("\n") .append(getTitle()) .append("\n\n"); if (!TextUtils.isEmpty(getSubtitle())) { text.append(getSubtitle()) .append("\n\n"); } text.append(getOnlinelink()); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, getPaper().getTitelWithDate(context) + ": " + getTitle()); intent.putExtra(Intent.EXTRA_TEXT, text.toString()); return Intent.createChooser(intent, context.getString(R.string.reader_action_share)); } } } public class TopLink extends TocItemTemplate //implements ArticleReaderItem { private String title; private String key; private Page page; public TopLink(String key, String title) { this.key = key; this.title = title; } public String getKey() { return key; } @Override public String getTitle() { return title; } public Page getPage() { return page; } @Override public ITocItem getIndexParent() { return null; } @Override public boolean hasIndexParent() { return false; } @Override public boolean hasIndexChilds() { return false; } @Override public List<ITocItem> getIndexChilds() { return null; } } public abstract class TocItemTemplate implements ITocItem { Type type; private boolean bookmarked; private ITocItem link; public abstract String getTitle(); public boolean hasBookmarkedChilds() { if (getIndexChilds() != null) { for (ITocItem child : getIndexChilds()) { if (child.isBookmarked()) { return true; } else { if (child.hasBookmarkedChilds()) return true; } } } return false; } public ITocItem getIndexAncestorWithKey(String key) { if (hasIndexParent()) { if (getIndexParent().getKey() .equals(key)) return getIndexParent(); else return getIndexParent().getIndexAncestorWithKey(key); } return null; } public Type getType() { if (type == null) { if (this instanceof Source) type = Type.SOURCE; else if (this instanceof Category) type = Type.CATEGORY; else if (this instanceof Page) type = Type.PAGE; else if (this instanceof Article) type = Type.ARTICLE; else if (this instanceof TopLink) type = Type.TOPLINK; else type = Type.UNKNOWN; } return type; } public Paper getPaper() { return Paper.this; } @Override public boolean isBookmarkable() { return false; } @Override public void setBookmark(boolean bookmarked) { if (isBookmarkable()) this.bookmarked = bookmarked; } @Override public boolean isBookmarked() { return bookmarked; } @Override public boolean isShareable() { return false; } @Override public Intent getShareIntent(Context context) { return null; } public ITocItem getLink() { return link; } public boolean isLink() { return link != null; } @Override public void setLink(ITocItem link) { this.link = link; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()) .append("@") .append(Integer.toHexString(hashCode())); builder.append("|") .append(bookId); if (getSources() != null) { builder.append("|") .append("sources:") .append(getSources().size()); } if (getToplinks() != null) { builder.append("|") .append("toplinks:") .append(getToplinks().size()); } return builder.toString(); } } public @NonNull JSONArray getBookmarkJson() { JSONArray array = new JSONArray(); try { for (Map.Entry<String, ITocItem> entry : getPlist().indexMap.entrySet()) { switch (entry.getValue() .getType()) { case ARTICLE: if (entry.getValue() .isBookmarked()) { array.put(entry.getValue() .getKey()); } break; } } } catch (Exception e) { } return array; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Paper)) return false; Paper paper = (Paper) o; return new EqualsBuilder().appendSuper(super.equals(o)) .append(lastModified, paper.lastModified) .append(demo, paper.demo) .append(validUntil, paper.validUntil) .append(bookId, paper.bookId) .append(date, paper.date) .append(image, paper.image) .append(imageHash, paper.imageHash) .append(link, paper.link) .append(resource, paper.resource) .append(title, paper.title) .append(publication, paper.publication) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).appendSuper(super.hashCode()) .append(bookId) .append(date) .append(image) .append(imageHash) .append(link) .append(lastModified) .append(resource) .append(demo) .append(title) .append(validUntil) .append(publication) .toHashCode(); } @Override public String toString() { //return Log.toString(this, ":", "; "); return ToStringBuilder.reflectionToString(this); } public static class PaperNotFoundException extends ReadableException { public PaperNotFoundException() { } public PaperNotFoundException(String detailMessage) { super(detailMessage); } public PaperNotFoundException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public PaperNotFoundException(Throwable throwable) { super(throwable); } } }
package com.plnyyanks.frcnotebook.database; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.preference.PreferenceManager; import com.plnyyanks.frcnotebook.R; import com.plnyyanks.frcnotebook.activities.StartActivity; public class PreferenceHandler { private static SharedPreferences prefs; public static int getTheme(){ int themeId = R.style.theme_light; if(StartActivity.startActivityContext==null)return themeId; if(prefs==null) prefs = PreferenceManager.getDefaultSharedPreferences(StartActivity.startActivityContext); if(prefs==null) return themeId; String theme = prefs.getString("theme","theme_light"); if(theme.equals("theme_light")) themeId = R.style.theme_light; if(theme.equals("theme_dark")) themeId = R.style.theme_dark; return themeId; } public static boolean getFMEnabled(){ if(prefs==null) prefs = PreferenceManager.getDefaultSharedPreferences(StartActivity.startActivityContext); if(prefs==null) return false; return prefs.getBoolean("show_field_monitor",false); } public static void setAppVersion(Context context){ if(prefs==null) prefs = PreferenceManager.getDefaultSharedPreferences(StartActivity.startActivityContext); try { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); prefs.edit().putString("app_version",info.versionName).commit(); } catch (Exception e) { e.printStackTrace(); } } }
package thredds.dqc.server.latest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.util.*; import java.io.*; import java.text.SimpleDateFormat; import java.text.ParseException; import java.net.URL; import thredds.catalog.*; import thredds.catalog.parser.jdom.InvCatalogFactory10; import thredds.catalog.query.*; import thredds.servlet.ServletUtil; import thredds.servlet.UsageLog; import thredds.dqc.server.DqcHandler; import ucar.nc2.constants.FeatureType; /** * _more_ * * @author edavis * @since Sep 21, 2005 9:12:56 PM */ public class LatestDqcHandler extends DqcHandler { private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger( LatestDqcHandler.class ); protected LatestConfig config; /** * Default constructor. */ public LatestDqcHandler() { } /** * @param req * @param res * @throws java.io.IOException if an input or output error is detected while the servlet handles the GET request. * @throws javax.servlet.ServletException if the request can't be handled for some reason. */ public void handleRequest( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException { // Get request path. String reqPath = req.getPathInfo(); // Get path after this handler's name. String extraPath = reqPath.substring( this.getHandlerInfo().getName().length() + 1 ); // Deal with request for DQC document. if ( extraPath.equals( ".xml" ) ) { // Create the DQC document. QueryCapability dqc = createDqcDocument( req.getContextPath() + req.getServletPath() + "/" + this.getHandlerInfo().getName() ); // Write DQC doc as response DqcFactory dqcFactory = new DqcFactory( false ); String dqcAsString = dqcFactory.writeXML( dqc ); PrintWriter out = res.getWriter(); res.setContentType( "text/xml" ); res.setStatus( HttpServletResponse.SC_OK ); out.print( dqcAsString ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_OK, dqcAsString.length() )); return; } // If not a request for DQC document, should not be any extra path info. if ( extraPath.length() > 0 ) { String tmpMsg = "Extra path information <" + extraPath + "> not understood."; log.error( "handleRequest(): " + tmpMsg ); res.sendError( HttpServletResponse.SC_BAD_REQUEST, tmpMsg ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_BAD_REQUEST, 0 )); return; } // Determine what LatestConfig.Item was requested. String reqItemId = req.getQueryString(); if ( reqItemId == null ) { // No LatestConfig.Item ID was given in request. String tmpMsg = "No latest request ID given."; log.error( "handleRequest(): " + tmpMsg ); res.sendError( HttpServletResponse.SC_NOT_FOUND, "LatestDqcHandler.handleRequest(): " + tmpMsg ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_NOT_FOUND, 0 )); return; } log.debug( "Request for the latest \"" + reqItemId + "\"." ); // Determine if the requested Item is supported. LatestConfig.Item reqItem = this.config.getItem( reqItemId ); if ( reqItem == null ) { String tmpMsg = "The Item requested, " + reqItemId + ", is not supported."; log.error( "handleRequest(): " + tmpMsg ); res.sendError( HttpServletResponse.SC_NOT_FOUND, "LatestDqcHandler.handleRequest(): " + tmpMsg ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_NOT_FOUND, 0 )); return; } // Check that directory exists String reqItemName = reqItem.getName(); File dir = new File( reqItem.getDirLocation() ); log.debug( "handleRequest(): requested Item <id=" + reqItemId + ", name=" + reqItemName + ", dir=" + dir.getPath() + "> is supported." ); if ( !dir.isDirectory() ) { // The dataset location is not a directory. log.error( "handleRequest(): Directory <" + dir.getPath() + "> given by configuration item <id=" + reqItemId + "> is not a directory." ); res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Directory given by config item <id=" + reqItemId + "> is not a directory." ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0 )); return; } // Find the latest dataset. File mostRecentDs = findLatestDataset( reqItem, dir.listFiles() ); if ( mostRecentDs != null ) { // Create catalog for the latest dataset. String catalogAsString = createCatalog( mostRecentDs, reqItem ); if ( catalogAsString == null ) { String tmpMsg = "Could not generate a catalog, unsupported InvCat spec version <" + reqItem.getInvCatSpecVersion() + ">."; log.error( "handleRequest(): " + tmpMsg ); res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, tmpMsg ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0 )); return; } // Send catalog as response. PrintWriter out = res.getWriter(); res.setContentType( "text/xml" ); res.setStatus( HttpServletResponse.SC_OK ); out.print( catalogAsString ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_OK, catalogAsString.length() )); return; } else { // The requested Item is not available. Return an error. String tmpMsg = "No latest dataset found for request<" + reqItemId + ">."; log.error( "handleRequest(): " + tmpMsg ); res.sendError( HttpServletResponse.SC_NOT_FOUND, tmpMsg ); log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_NOT_FOUND, 0 )); return; } } /** * Read the configuration from the config doc. */ public void initWithHandlerConfigDoc( URL configDocURL ) throws IOException { // Open the preferences file. log.debug( "initWithHandlerConfigDoc(): open config document <" + configDocURL.toString() + "> and read config information." ); InputStream is = configDocURL.openStream(); config = LatestConfigFactory.parseXML( is, configDocURL.toString()); if ( config == null ) { String tmpMsg = "Failed to parse config doc <" + configDocURL.toString() + ">."; log.error( "initWithHandlerConfigDoc(): " + tmpMsg ); throw new IOException( tmpMsg ); } // Check for validity of each config item. List badDirItemIDs = new ArrayList(); for ( Iterator it = config.getIds().iterator(); it.hasNext(); ) { LatestConfig.Item curItem = config.getItem( (String) it.next() ); File dir = new File( curItem.getDirLocation() ); if ( ! dir.isDirectory() ) { log.warn( "initWithHandlerConfigDoc(): Directory <" + dir.getAbsolutePath() + "> is not a directory; config item<id=" + curItem.getId() + "> being removed." ); badDirItemIDs.add( curItem.getId()); } } // Remove any invalid items. for ( Iterator it = badDirItemIDs.iterator(); it.hasNext(); ) { String curItemID = (String) it.next(); if ( ! config.removeItem( curItemID ) ) { log.warn( "initWithHandlerConfigDoc(): Bad Item <id=" + curItemID + "> not removed."); } } if ( config.isEmpty() ) { String tmpMsg = "No configuration info."; log.error( "initWithHandlerConfigDoc(): " + tmpMsg ); throw new IOException( tmpMsg); } } protected File findLatestDataset( LatestConfig.Item reqItem, File allFiles[] ) { File mostRecentDs = null; Date mostRecentDsDate = null; File curDs = null; Date curDsDate = null; log.debug( "findLatestDataset(): getting dir listing." ); for ( int i = 0; i < allFiles.length; i++ ) { // Get the date for the current dataset. curDs = allFiles[i]; curDsDate = this.getDatasetDate( curDs, reqItem ); log.debug( "findLatestDataset(): current dataset is <" + curDs.getName() + ">." ); // If this is the first dataset, make it the most recent one. if ( curDsDate != null ) { if ( mostRecentDs == null ) { mostRecentDs = curDs; mostRecentDsDate = curDsDate; } else { // Check if current dataset is most recent. if ( mostRecentDsDate.before( curDsDate ) ) { mostRecentDs = curDs; mostRecentDsDate = curDsDate; } } log.debug( "findLatestDataset(): the most recent dataset <" + mostRecentDs.getName() + "> has date <" + mostRecentDsDate + ">." ); } } return ( mostRecentDs ); } protected QueryCapability createDqcDocument( String baseURI ) { // Create DQC root elements (QueryCapability and Query). QueryCapability dqc = new QueryCapability( null, this.getHandlerInfo().getName() + " DQC Document", "0.3" ); Query query = new Query( baseURI, null, null ); dqc.setQuery( query ); // Create the SelectService and add to the DQC. SelectService selectService = new SelectService( "service", "Select service type." ); selectService.addServiceChoice( "OpenDAP", "OPeNDAP/DODS", null, null, null ); selectService.setRequired( "false" ); dqc.addUniqueSelector( selectService ); dqc.setServiceSelector( selectService ); // Create the SelectList and add to the DQC SelectList selectList = new SelectList( "Model name", "models", null, "true", "false" ); for ( Iterator it = config.getIds().iterator(); it.hasNext(); ) { LatestConfig.Item curConfigItem = config.getItem( (String) it.next() ); ListChoice curChoice = new ListChoice( selectList, curConfigItem.getId(), curConfigItem.getName(), null ); selectList.addChoice( curChoice ); } dqc.addUniqueSelector( selectList ); return ( dqc ); } /** * Generate a latest dataset catalog. */ protected InvCatalogImpl createCatalog( String catName, String dsName, FeatureType dsType, String serviceType, String serviceName, String serviceBaseURL, String urlPath ) { log.debug( "createCatalog(): creating createCatalog/dataset." ); // Create the catalog, service, and top-level dataset. InvCatalogImpl catalog = new InvCatalogImpl( catName, null, null ); InvService myService = new InvService( serviceName, serviceType, serviceBaseURL, null, null ); InvDatasetImpl topDs = new InvDatasetImpl( null, dsName, dsType, serviceName, urlPath ); // OR ( null, this.mainConfig.getDqcServletTitle() ); // Add service and top-level dataset to the catalog. catalog.addService( myService ); catalog.addDataset( topDs ); catalog.finish(); log.debug( "createCatalog(): createCatalog/dataset created." ); return ( catalog ); } protected String createCatalog( File mostRecentDs, LatestConfig.Item reqItem ) throws IOException { InvCatalogImpl catalog; String urlPath = mostRecentDs.getName(); // Get date of most recent dataset. Date mostRecentDsDate = this.getDatasetDate( mostRecentDs, reqItem ); // Determine name of most recent dataset SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH'Z'", Locale.US ); dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); String mostRecentDsName = "Latest " + reqItem.getName() + " (" + dateFormat.format( mostRecentDsDate ) + ")"; log.debug( "handleRequest(): Latest dataset <" + mostRecentDs.getAbsolutePath() + "> named \"" + mostRecentDsName + "\"." ); // Create catalog for the latest dataset String catalogName = null; if ( reqItem.getInvCatSpecVersion().equals( "0.6" ) ) { catalogName = mostRecentDsName; } catalog = this.createCatalog( catalogName, mostRecentDsName, FeatureType.GRID, "DODS", "mlode", reqItem.getServiceBaseURL(), urlPath ); // Write catalog as response InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( true ); String catalogAsString = null; if ( reqItem.getInvCatSpecVersion().equals( "0.6" ) ) { log.warn( "createCatalog(): LatestDqcHandler configured to generate \"0.6\" InvCatalogs. Version \"0.6\" no longer supported." ); //catalogAsString = fac.writeXML_0_6( catalog ); } else if ( reqItem.getInvCatSpecVersion().startsWith( "1.0" ) ) { InvCatalogFactory10 fac10 = (InvCatalogFactory10) fac.getCatalogConverter( XMLEntityResolver.CATALOG_NAMESPACE_10 ); fac10.setVersion( reqItem.getInvCatSpecVersion() ); ByteArrayOutputStream osCat = new ByteArrayOutputStream( 10000 ); fac10.writeXML( catalog, osCat ); catalogAsString = osCat.toString(); } return catalogAsString; } /** * Return the date of run time for the current dataset file. * If the file does not match the match pattern, null is returned. * * @param theFile - the File representing the current dataset file. * @param reqItem - the LatestConfig.Item for the request. * @return Date of the current dataset files run time */ protected Date getDatasetDate( File theFile, LatestConfig.Item reqItem ) { java.util.regex.Pattern pattern = java.util.regex.Pattern.compile( reqItem.getDatasetNameMatchPattern() ); java.util.regex.Matcher matcher = pattern.matcher( theFile.getName() ); // Look for match in filename. if ( ! matcher.find() ) { log.warn( "getDatasetDate(): File name <" + theFile.getName() + "> didn't match pattern <" + reqItem.getDatasetNameMatchPattern() + ">."); return null; } // Build time string from substitution pattern. // Note: since appendReplacement() isn't just for capturing groups, // need to remove start of filename from resulting StringBuffer. StringBuffer dateString = new StringBuffer(); matcher.appendReplacement( dateString, reqItem.getDatasetTimeSubstitutionPattern() ); dateString.delete( 0, matcher.start() ); Date theDate; if ( dateString.length() > 0 ) { String dateFormatString = "yyyy-MM-dd'T'HH:mm:ss"; String dateFormatAltString = "yyyy/MM/dd HH:mm"; SimpleDateFormat dateFormat = new SimpleDateFormat( dateFormatString, Locale.US ); dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); try { theDate = dateFormat.parse( dateString.toString() ); } catch ( java.text.ParseException e ) { log.debug( "getDatasetDate(): Failed to parse date with format \"" + dateFormatString + "\": " + e.getMessage() ); dateFormat = new SimpleDateFormat( dateFormatAltString, Locale.US ); dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); try { theDate = dateFormat.parse( dateString.toString() ); } catch ( ParseException e1 ) { log.warn( "getDatasetDate(): Failed to parse date with either format \"" + dateFormatString + "\" or \"" + dateFormatAltString + "\": " + e.getMessage() ); return ( null ); } } log.debug( "getDatasetDate(): Got date <" + dateString + " - " + theDate.toString() + "> from file name <" + theFile.getName() + ">." ); return theDate; } log.warn( "getDatasetDate(): File name <" + theFile.getName() + ">, match pattern <" + reqItem.getDatasetNameMatchPattern() + ">, and sub pattern <" + reqItem.getDatasetTimeSubstitutionPattern() + "> produced a zero length date string." ); return ( null ); } public String toString() { StringBuffer buf = new StringBuffer(); buf.append( "LatestDqcHandler[" ); buf.append( config.toString() ); buf.append( "\n]"); return ( buf.toString() ); } }
package org.eclipse.birt.chart.reportitem; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.SortOption; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.impl.ChartModelHelper; import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil; import org.eclipse.birt.chart.reportitem.api.ChartItemUtil; import org.eclipse.birt.chart.reportitem.api.ChartReportItemConstants; import org.eclipse.birt.chart.reportitem.i18n.Messages; import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionCodec; import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionSet; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.chart.util.SecurityUtil; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.aggregation.api.IBuildInAggregation; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.data.engine.api.ISortDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.olap.api.query.IBaseCubeQueryDefinition; import org.eclipse.birt.data.engine.olap.api.query.ICubeElementFactory; import org.eclipse.birt.data.engine.olap.api.query.ICubeFilterDefinition; import org.eclipse.birt.data.engine.olap.api.query.ICubeOperation; import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition; import org.eclipse.birt.data.engine.olap.api.query.ICubeSortDefinition; import org.eclipse.birt.data.engine.olap.api.query.IDimensionDefinition; import org.eclipse.birt.data.engine.olap.api.query.IEdgeDefinition; import org.eclipse.birt.data.engine.olap.api.query.IHierarchyDefinition; import org.eclipse.birt.data.engine.olap.api.query.ILevelDefinition; import org.eclipse.birt.data.engine.olap.api.query.IMeasureDefinition; import org.eclipse.birt.data.engine.olap.api.query.ISubCubeQueryDefinition; import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil; import org.eclipse.birt.report.data.adapter.api.DataSessionContext; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.data.adapter.impl.DataModelAdapter; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.AggregationCellHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FilterConditionElementHandle; import org.eclipse.birt.report.model.api.MemberValueHandle; import org.eclipse.birt.report.model.api.ModuleUtil; import org.eclipse.birt.report.model.api.MultiViewsHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.extension.ExtendedElementException; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.HierarchyHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; import org.eclipse.birt.report.model.api.util.CubeUtil; import org.eclipse.birt.report.model.elements.interfaces.IMemberValueModel; import org.eclipse.emf.common.util.EList; import com.ibm.icu.util.ULocale; /** * Query helper for cube query definition */ public class ChartCubeQueryHelper { protected static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$ protected final ExtendedItemHandle handle; protected final Chart cm; /** * Maps for registered column bindings.<br> * Key: binding name, value: Binding */ protected Map<String, IBinding> registeredBindings = new HashMap<String, IBinding>( ); /** * Maps for registered queries.<br> * Key: binding name, value: raw query expression */ protected Map<String, String> registeredQueries = new HashMap<String, String>( ); /** * Maps for registered level definitions.<br> * Key: Binding name of query, value: ILevelDefinition */ protected Map<String, ILevelDefinition> registeredLevels = new HashMap<String, ILevelDefinition>( ); /** * Maps for registered measure definitions.<br> * Key: Binding name of query, value: IMeasureDefinition */ protected Map<String, IMeasureDefinition> registeredMeasures = new HashMap<String, IMeasureDefinition>( ); /** * Maps for registered level handles.<br> * Key: LevelHandle, value: ILevelDefinition */ protected Map<LevelHandle, ILevelDefinition> registeredLevelHandles = new HashMap<LevelHandle, ILevelDefinition>( ); protected String rowEdgeDimension; /** * Indicates if used for single chart case, such as Live preview in chart * builder, or no inheritance. In this case, sub/nest query is not * supported, and aggregateOn in measure binding should be removed to make * preview work. */ private boolean bSingleChart = false; private static ICubeElementFactory cubeFactory = null; protected final IModelAdapter modelAdapter; protected final ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); public ChartCubeQueryHelper( ExtendedItemHandle handle, Chart cm ) throws BirtException { this.handle = handle; this.cm = cm; DataSessionContext dsc = new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION, handle.getModuleHandle( ) ); modelAdapter = new DataModelAdapter( dsc ); } public ChartCubeQueryHelper( ExtendedItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { this.handle = handle; this.cm = cm; this.modelAdapter = modelAdapter; } public synchronized static ICubeElementFactory getCubeElementFactory( ) throws BirtException { if ( cubeFactory != null ) { return cubeFactory; } try { Class<?> cls = Class.forName( ICubeElementFactory.CUBE_ELEMENT_FACTORY_CLASS_NAME ); cubeFactory = (ICubeElementFactory) SecurityUtil.newClassInstance( cls ); } catch ( Exception e ) { throw new ChartException( ChartReportItemConstants.ID, BirtException.ERROR, e ); } return cubeFactory; } /** * Creates the cube query definition for chart. If parent definition is * null, it's usually used for Live preview in chart builder. If chart in * xtab, will return sub cube query definition. * * @param parent * @return ICubeQueryDefinition for cube consuming or * ISubCubeQueryDefinition for chart in xtab case * @throws BirtException */ public IBaseCubeQueryDefinition createCubeQuery( IDataQueryDefinition parent ) throws BirtException { return createCubeQuery( parent, null ); } /** * Creates the cube query definition for chart. If parent definition is * null, it's usually used for Live preview in chart builder. If chart in * xtab, will return sub cube query definition. * * @param parent * @param expressions * the extended expressions. * @return ICubeQueryDefinition for cube consuming or * ISubCubeQueryDefinition for chart in xtab case * @throws BirtException * @since 2.5.2 */ @SuppressWarnings("unchecked") public IBaseCubeQueryDefinition createCubeQuery( IDataQueryDefinition parent, String[] expressions ) throws BirtException { bSingleChart = parent == null; CubeHandle cubeHandle = getCubeHandle( ); ICubeQueryDefinition cubeQuery = null; if ( cubeHandle == null ) { // Create sub query for chart in xtab cubeHandle = ChartCubeUtil.getBindingCube( handle ); if ( cubeHandle == null ) { throw new ChartException( ChartReportItemConstants.ID, ChartException.NULL_DATASET, Messages.getString( "ChartCubeQueryHelper.Error.MustBindCube" ) ); //$NON-NLS-1$ } // Do not support sub query without parent if ( parent instanceof ICubeQueryDefinition ) { ISubCubeQueryDefinition subQuery = createSubCubeQuery( ); if ( ChartCubeUtil.isPlotChart( handle ) ) { // Adds min and max binding to parent query definition // for shared scale. Only added for plot chart addMinMaxBinding( (ICubeQueryDefinition) parent ); } if ( subQuery != null ) { return subQuery; } // If single chart in xtab and chart doesn't include bindings, // use parent to render directly Iterator<ComputedColumnHandle> bindings = handle.columnBindingsIterator( ); if ( !bindings.hasNext( ) ) { return (ICubeQueryDefinition) parent; } } } cubeQuery = getCubeElementFactory( ).createCubeQuery( cubeHandle.getQualifiedName( ) ); // Add column bindings from handle initBindings( cubeQuery, cubeHandle ); List<SeriesDefinition> sdList = getAllSeriesDefinitions( cm ); ExpressionSet exprSet = getExpressions( expressions, sdList ); for ( String expr : exprSet ) { bindExpression( expr, cubeQuery, cubeHandle ); } // Add sorting // Sorting must be added after measures and dimensions, since sort // key references to measures or dimensions for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = sdList.get( i ); addSorting( cubeQuery, cubeHandle, sd, i ); } // Add filter // Filter may include new levels and modify level definition, so it // should be added before aggregation. addCubeFilter( cubeQuery, cubeHandle ); // Sort the level definitions by hierarchy order in multiple levels // case sortLevelDefinition( cubeQuery.getEdge( ICubeQueryDefinition.ROW_EDGE ), cubeHandle ); sortLevelDefinition( cubeQuery.getEdge( ICubeQueryDefinition.COLUMN_EDGE ), cubeHandle ); // Add aggregation list to measure bindings on demand Collection<ILevelDefinition> levelsInOrder = getAllLevelsInHierarchyOrder( cubeHandle, cubeQuery ); addAggregateOnToMeasures( levelsInOrder ); return cubeQuery; } /** * @param expressions * @param sdList * @return */ protected ExpressionSet getExpressions( String[] expressions, List<SeriesDefinition> sdList ) { ExpressionSet exprSet = new ExpressionSet( ); // Add measures and dimensions for ( int i = 0; i < sdList.size( ); i++ ) { SeriesDefinition sd = sdList.get( i ); List<Query> queryList = sd.getDesignTimeSeries( ) .getDataDefinition( ); for ( int j = 0; j < queryList.size( ); j++ ) { Query query = queryList.get( j ); // Add measures or dimensions for data definition, and update // query expression exprSet.add( query.getDefinition( ) ); } // Add measures or dimensions for optional grouping, and update // query expression exprSet.add( sd.getQuery( ).getDefinition( ) ); } if ( expressions != null ) { for ( String expr : expressions ) { exprSet.add( expr ); } } return exprSet; } protected CubeHandle getCubeHandle( ) { return handle.getCube( ); } protected void addAggregateOnToMeasures( Collection<ILevelDefinition> levelsInOrder ) throws DataException { for ( Iterator<String> measureNames = registeredMeasures.keySet( ) .iterator( ); measureNames.hasNext( ); ) { IBinding binding = registeredBindings.get( measureNames.next( ) ); if ( binding != null && binding.getAggregatOns( ).isEmpty( ) ) { for ( Iterator<ILevelDefinition> levels = levelsInOrder.iterator( ); levels.hasNext( ); ) { ILevelDefinition level = levels.next( ); String dimensionName = level.getHierarchy( ) .getDimension( ) .getName( ); binding.addAggregateOn( ExpressionUtil.createJSDimensionExpression( dimensionName, level.getName( ) ) ); } } } } protected ISubCubeQueryDefinition createSubCubeQuery( ) throws BirtException { String queryName = ChartReportItemConstants.NAME_SUBQUERY; AggregationCellHandle containerCell = ChartCubeUtil.getXtabContainerCell( handle ); if ( containerCell == null ) { return null; } CrosstabReportItemHandle xtab = containerCell.getCrosstab( ); int columnLevelCount = ChartCubeUtil.getLevelCount( xtab, ICrosstabConstants.COLUMN_AXIS_TYPE ); int rowLevelCount = ChartCubeUtil.getLevelCount( xtab, ICrosstabConstants.ROW_AXIS_TYPE ); if ( cm instanceof ChartWithAxes ) { if ( ( (ChartWithAxes) cm ).isTransposed( ) ) { if ( columnLevelCount >= 1 ) { ISubCubeQueryDefinition subCubeQuery = getCubeElementFactory( ).createSubCubeQuery( queryName ); subCubeQuery.setStartingLevelOnColumn( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.COLUMN_AXIS_TYPE, columnLevelCount - 1 ) .getCubeLevel( ) ) ); if ( rowLevelCount > 1 ) { // Only add another level in multiple levels case subCubeQuery.setStartingLevelOnRow( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.ROW_AXIS_TYPE, rowLevelCount - 2 ) .getCubeLevel( ) ) ); } return subCubeQuery; } else if ( rowLevelCount > 1 ) { // No column level and multiple row levels, use the top // row level ISubCubeQueryDefinition subCubeQuery = getCubeElementFactory( ).createSubCubeQuery( queryName ); subCubeQuery.setStartingLevelOnRow( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.ROW_AXIS_TYPE, rowLevelCount - 2 ) .getCubeLevel( ) ) ); return subCubeQuery; } // If corresponding column is null and without multiple // levels, do not use sub query } else { if ( rowLevelCount >= 1 ) { ISubCubeQueryDefinition subCubeQuery = getCubeElementFactory( ).createSubCubeQuery( queryName ); subCubeQuery.setStartingLevelOnRow( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.ROW_AXIS_TYPE, rowLevelCount - 1 ) .getCubeLevel( ) ) ); if ( columnLevelCount > 1 ) { // Only add another level in multiple levels case subCubeQuery.setStartingLevelOnColumn( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.COLUMN_AXIS_TYPE, columnLevelCount - 2 ) .getCubeLevel( ) ) ); } return subCubeQuery; } else if ( columnLevelCount > 1 ) { // No row level and multiple column levels, use the top // column level ISubCubeQueryDefinition subCubeQuery = getCubeElementFactory( ).createSubCubeQuery( queryName ); subCubeQuery.setStartingLevelOnColumn( ChartCubeUtil.createDimensionExpression( ChartCubeUtil.getLevel( xtab, ICrosstabConstants.COLUMN_AXIS_TYPE, columnLevelCount - 2 ) .getCubeLevel( ) ) ); return subCubeQuery; } // If corresponding row is null and without multiple levels, // do not use sub query } } // Do not use sub query for other cases return null; } /** * Adds min and max binding to parent query definition * * @param parent * @throws BirtException */ private void addMinMaxBinding( ICubeQueryDefinition parent ) throws BirtException { Axis xAxis = ( (ChartWithAxes) cm ).getAxes( ).get( 0 ); SeriesDefinition sdValue = ( (ChartWithAxes) cm ).getOrthogonalAxes( xAxis, true )[0].getSeriesDefinitions( ).get( 0 ); Query queryValue = sdValue.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); String bindingValue = exprCodec.getCubeBindingName( queryValue.getDefinition( ), false ); String maxBindingName = ChartReportItemConstants.NAME_QUERY_MAX + bindingValue; String minBindingName = ChartReportItemConstants.NAME_QUERY_MIN + bindingValue; for ( Iterator<ComputedColumnHandle> bindings = ChartReportItemUtil.getAllColumnBindingsIterator( handle ); bindings.hasNext( ); ) { ComputedColumnHandle column = bindings.next( ); if ( column.getName( ).equals( bindingValue ) ) { // Create nest total aggregation binding IBinding maxBinding = new Binding( maxBindingName ); maxBinding.setExpression( new ScriptExpression( queryValue.getDefinition( ) ) ); maxBinding.setAggrFunction( IBuildInAggregation.TOTAL_MAX_FUNC ); maxBinding.setExportable( false ); IBinding minBinding = new Binding( minBindingName ); minBinding.setExpression( new ScriptExpression( queryValue.getDefinition( ) ) ); minBinding.setAggrFunction( IBuildInAggregation.TOTAL_MIN_FUNC ); minBinding.setExportable( false ); // create adding nest aggregations operation ICubeOperation op = getCubeElementFactory( ).getCubeOperationFactory( ) .createAddingNestAggregationsOperation( new IBinding[]{ maxBinding, minBinding } ); // add cube operations to cube query definition parent.addCubeOperation( op ); break; } } } @SuppressWarnings("unchecked") private void initBindings( ICubeQueryDefinition cubeQuery, CubeHandle cube ) throws BirtException { for ( Iterator<ComputedColumnHandle> bindings = ChartReportItemUtil.getAllColumnBindingsIterator( handle ); bindings.hasNext( ); ) { ComputedColumnHandle column = bindings.next( ); // Create new binding IBinding binding = new Binding( column.getName( ) ); binding.setDataType( DataAdapterUtil.adaptModelDataType( column.getDataType( ) ) ); binding.setAggrFunction( column.getAggregateFunction( ) == null ? null : DataAdapterUtil.adaptModelAggregationType( column.getAggregateFunction( ) ) ); ChartItemUtil.loadExpression( exprCodec, column ); // Even if expression is null, create the script expression binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, true ) ); List<String> lstAggOn = column.getAggregateOnList( ); // Do not add aggregateOn to binding in single chart case, because // it doesn't use sub query. // If expression is null, such as count aggregation, always add all // aggregate on levels if ( column.getExpression( ) == null || !bSingleChart && !lstAggOn.isEmpty( ) ) { // Add aggregate on in binding addAggregateOn( binding, lstAggOn, cubeQuery, cube ); } // Add binding query expression here registeredBindings.put( binding.getBindingName( ), binding ); // Add raw query expression here registeredQueries.put( binding.getBindingName( ), exprCodec.encode( ) ); // Do not add every binding to cube query, since it may be not used. // The binding will be added only if it's used in chart. } } private void addAggregateOn( IBinding binding, List<String> lstAggOn, ICubeQueryDefinition cubeQuery, CubeHandle cube ) throws BirtException { for ( Iterator<String> iAggs = lstAggOn.iterator( ); iAggs.hasNext( ); ) { String aggOn = iAggs.next( ); // Convert full level name to dimension expression String[] levelNames = CubeUtil.splitLevelName( aggOn ); String dimExpr = ExpressionUtil.createJSDimensionExpression( levelNames[0], levelNames[1] ); binding.addAggregateOn( dimExpr ); } } private void addSorting( ICubeQueryDefinition cubeQuery, CubeHandle cube, SeriesDefinition sd, int i ) throws BirtException { if ( sd.getSortKey( ) == null ) { return; } String sortKey = sd.getSortKey( ).getDefinition( ); if ( sd.isSetSorting( ) && sortKey != null && sortKey.length( ) > 0 ) { exprCodec.decode( sortKey ); String sortKeyBinding = exprCodec.getCubeBindingName( true ); if ( registeredLevels.containsKey( sortKeyBinding ) ) { // Add sorting on dimension ICubeSortDefinition sortDef = getCubeElementFactory( ).createCubeSortDefinition( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, true ), registeredLevels.get( sortKeyBinding ), null, null, sd.getSorting( ) == SortOption.ASCENDING_LITERAL ? ISortDefinition.SORT_ASC : ISortDefinition.SORT_DESC ); if ( sd.getSortLocale( ) != null ) { sortDef.setSortLocale( new ULocale( sd.getSortLocale( ) ) ); } if ( sd.isSetSortStrength( ) ) { sortDef.setSortStrength( sd.getSortStrength( ) ); } cubeQuery.addSort( sortDef ); } else if ( registeredMeasures.containsKey( sortKeyBinding ) ) { // Add sorting on measures IMeasureDefinition mDef = registeredMeasures.get( sortKeyBinding ); Query targetQuery = i > 0 ? sd.getQuery( ) : (Query) sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); ExpressionCodec exprCodecTarget = ChartModelHelper.instance( ) .createExpressionCodec( ); exprCodecTarget.decode( targetQuery.getDefinition( ) ); String targetBindingName = exprCodecTarget.getCubeBindingName( true ); // Find measure binding IBinding measureBinding = registeredBindings.get( sortKeyBinding ); // Create new total binding on measure IBinding aggBinding = new Binding( measureBinding.getBindingName( ) + targetBindingName ); aggBinding.setDataType( measureBinding.getDataType( ) ); aggBinding.setExpression( measureBinding.getExpression( ) ); ILevelDefinition level = registeredLevels.get( targetBindingName ); aggBinding.addAggregateOn( ExpressionUtil.createJSDimensionExpression( level.getHierarchy( ) .getDimension( ) .getName( ), level.getName( ) ) ); aggBinding.setAggrFunction( mDef.getAggrFunction( ) ); aggBinding.setExportable( false ); cubeQuery.addBinding( aggBinding ); ICubeSortDefinition sortDef = getCubeElementFactory( ).createCubeSortDefinition( ExpressionUtil.createJSDataExpression( aggBinding.getBindingName( ) ), registeredLevels.get( targetBindingName ), null, null, sd.getSorting( ) == SortOption.ASCENDING_LITERAL ? ISortDefinition.SORT_ASC : ISortDefinition.SORT_DESC ); if ( sd.getSortLocale( ) != null ) { sortDef.setSortLocale( new ULocale( sd.getSortLocale( ) ) ); } if ( sd.isSetSortStrength( ) ) { sortDef.setSortStrength( sd.getSortStrength( ) ); } cubeQuery.addSort( sortDef ); } } } protected void bindBinding( IBinding colBinding, ICubeQueryDefinition cubeQuery, CubeHandle cube ) throws BirtException { if ( colBinding == null ) { return; } String bindingName = colBinding.getBindingName( ); // Convert binding expression like data[] to raw expression // like dimension[] or measure[] String expr = registeredQueries.get( bindingName ); // Add binding to query definition if ( !cubeQuery.getBindings( ).contains( colBinding ) ) { cubeQuery.addBinding( colBinding ); } String measure = exprCodec.getMeasureName( expr ); if ( measure != null ) { if ( registeredMeasures.containsKey( bindingName ) ) { return; } // Add measure IMeasureDefinition mDef = cubeQuery.createMeasure( measure ); String aggFun = DataAdapterUtil.adaptModelAggregationType( cube.getMeasure( measure ) .getFunction( ) ); mDef.setAggrFunction( aggFun ); registeredMeasures.put( bindingName, mDef ); // AggregateOn has been added in binding when initializing // column bindings } else if ( exprCodec.isDimensionExpresion( ) ) { registerDimensionLevel( cubeQuery, cube, bindingName ); } else if ( exprCodec.isCubeBinding( true ) ) { // Support nest data expression in binding bindExpression( expr, cubeQuery, cube ); return; } } /** * @param cubeQuery * @param cube * @param bindingName */ protected void registerDimensionLevel( ICubeQueryDefinition cubeQuery, CubeHandle cube, String bindingName ) { if ( registeredLevels.containsKey( bindingName ) ) { return; } // Add row/column edge String[] levels = exprCodec.getLevelNames( ); String dimensionName = levels[0]; final int edgeType = getEdgeType( dimensionName ); IEdgeDefinition edge = cubeQuery.getEdge( edgeType ); IHierarchyDefinition hieDef = null; if ( edge == null ) { // Only create one edge/dimension/hierarchy in one // direction edge = cubeQuery.createEdge( edgeType ); IDimensionDefinition dimDef = edge.createDimension( dimensionName ); // Do not use qualified name since it may be from // library hieDef = dimDef.createHierarchy( cube.getDimension( dimDef.getName( ) ) .getDefaultHierarchy( ) .getName( ) ); } else { hieDef = edge.getDimensions( ).get( 0 ).getHierarchy( ).get( 0 ); } // Create level ILevelDefinition levelDef = hieDef.createLevel( levels[1] ); registeredLevels.put( bindingName, levelDef ); LevelHandle levelHandle = handle.getModuleHandle( ) .findLevel( levelDef.getHierarchy( ) .getDimension( ) .getName( ) + "/" + levelDef.getName( ) ); //$NON-NLS-1$ registeredLevelHandles.put( levelHandle, levelDef ); } /** * Adds measure or row/column edge according to query expression. */ protected void bindExpression( String expression, ICubeQueryDefinition cubeQuery, CubeHandle cube ) throws BirtException { if ( expression == null ) { return; } String expr = expression.trim( ); if ( expr != null && expr.length( ) > 0 ) { exprCodec.decode( expression ); String bindingName = null; IBinding colBinding = null; if ( exprCodec.isCubeBinding( false ) ) { // Simple binding name case bindingName = exprCodec.getCubeBindingName( false ); colBinding = registeredBindings.get( bindingName ); } else { // Complex expression case bindingName = ChartUtil.escapeSpecialCharacters( exprCodec.getExpression( ) ); // Create new binding colBinding = new Binding( bindingName ); colBinding.setDataType( DataType.ANY_TYPE ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, true ) ); cubeQuery.addBinding( colBinding ); List<String> nameList = exprCodec.getCubeBindingNameList( ); if ( nameList.size( ) == 0 ) { // Constant case return; } else if ( nameList.size( ) == 1 ) { // One binding case bindingName = nameList.get( 0 ); colBinding = registeredBindings.get( bindingName ); } else { // Support multiple data expression concatenation like: // data["a"]+data["b"] for ( String bn : nameList ) { bindBinding( registeredBindings.get( bn ), cubeQuery, cube ); } return; } } bindBinding( colBinding, cubeQuery, cube ); } } @SuppressWarnings("unchecked") protected List<FilterConditionElementHandle> getCubeFiltersFromHandle( ReportItemHandle itemHandle ) { PropertyHandle propHandle = itemHandle.getPropertyHandle( ChartReportItemConstants.PROPERTY_CUBE_FILTER ); if ( propHandle == null ) { return Collections.emptyList( ); } return propHandle.getListValue( ); } private void addCubeFilter( ICubeQueryDefinition cubeQuery, CubeHandle cubeHandle ) throws BirtException { List<ILevelDefinition> levels = new ArrayList<ILevelDefinition>( ); List<String> values = new ArrayList<String>( ); List<FilterConditionElementHandle> filters = null; if ( handle.getContainer( ) instanceof MultiViewsHandle ) { // This code may never be invoked. Leave this for potential risk DesignElementHandle xtabHandle = handle.getContainer( ) .getContainer( ); if ( xtabHandle instanceof ExtendedItemHandle ) { CrosstabReportItemHandle crossTab = (CrosstabReportItemHandle) ( (ExtendedItemHandle) xtabHandle ).getReportItem( ); filters = getFiltersFromXtab( crossTab ); } } else if ( handle.getContainer( ) instanceof ExtendedItemHandle && handle.getCube( ) == null ) { // In inheritance case, chart's cube should be null and container // should be xtab cell ExtendedItemHandle xtabHandle = (ExtendedItemHandle) handle.getContainer( ); String exName = xtabHandle.getExtensionName( ); if ( ICrosstabConstants.AGGREGATION_CELL_EXTENSION_NAME.equals( exName ) || ICrosstabConstants.CROSSTAB_CELL_EXTENSION_NAME.equals( exName ) ) { // In xtab cell CrosstabCellHandle cell = (CrosstabCellHandle) xtabHandle.getReportItem( ); filters = getFiltersFromXtab( cell.getCrosstab( ) ); filters.addAll( getCubeFiltersFromHandle( handle ) ); } } else if ( ChartReportItemUtil.getReportItemReference( handle ) != null ) { ReportItemHandle rih = ChartReportItemUtil.getReportItemReference( handle ); if ( rih instanceof ExtendedItemHandle && ( (ExtendedItemHandle) rih ).getReportItem( ) instanceof CrosstabReportItemHandle ) { // It is sharing crosstab case. CrosstabReportItemHandle crossTab = (CrosstabReportItemHandle) ( (ExtendedItemHandle) rih ).getReportItem( ); filters = getFiltersFromXtab( crossTab ); } else { filters = getCubeFiltersFromHandle( rih ); } } if ( filters == null ) { filters = getCubeFiltersFromHandle( handle ); } for ( FilterConditionElementHandle filterCon : filters ) { // clean up first levels.clear( ); values.clear( ); addMembers( levels, values, filterCon.getMember( ) ); ILevelDefinition[] qualifyLevels = null; Object[] qualifyValues = null; if ( levels.size( ) > 0 ) { qualifyLevels = levels.toArray( new ILevelDefinition[levels.size( )] ); qualifyValues = values.toArray( new Object[values.size( )] ); } ConditionalExpression filterCondExpr; ChartItemUtil.loadExpression( exprCodec, filterCon ); String filterQuery = exprCodec.encode( ); if ( exprCodec.isCubeBinding( filterQuery, true ) ) { List<String> bindingNames = exprCodec.getCubeBindingNameList( ); // Replace inexistent data query with expression one by one for ( String filterBindingName : bindingNames ) { if ( filterBindingName != null && !registeredLevels.containsKey( filterBindingName ) && !registeredMeasures.containsKey( filterBindingName ) ) { String operator = filterCon.getOperator( ); if ( DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_N.equals( operator ) || DesignChoiceConstants.FILTER_OPERATOR_BOTTOM_PERCENT.equals( operator ) || DesignChoiceConstants.FILTER_OPERATOR_TOP_N.equals( operator ) || DesignChoiceConstants.FILTER_OPERATOR_TOP_PERCENT.equals( operator ) ) { // Top and Bottom are not supported in fact table of // data engine break; } // If filter expression is not used as dimension or // measure, // should set dimension/measure expression as filter // directly String newExpr = registeredQueries.get( filterBindingName ); if ( newExpr != null ) { // Replace all data expressions with // dimension/measure // expressions in complex expression exprCodec.setBindingName( filterBindingName, true ); filterQuery = filterQuery.replace( exprCodec.encode( ), newExpr ); } } } } List<Expression> value1 = filterCon.getValue1ExpressionList( ) .getListValue( ); if ( ModuleUtil.isListFilterValue( filterCon ) ) { List<ScriptExpression> valueList = new ArrayList<ScriptExpression>( value1.size( ) ); for ( Expression value : value1 ) { valueList.add( modelAdapter.adaptExpression( value ) ); } exprCodec.decode( filterQuery ); filterCondExpr = new ConditionalExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, true ), DataAdapterUtil.adaptModelFilterOperator( filterCon.getOperator( ) ), valueList ); } else { Object value2 = filterCon.getExpressionProperty( FilterConditionElementHandle.VALUE2_PROP ) .getValue( ); exprCodec.decode( filterQuery ); filterCondExpr = new ConditionalExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, true ), DataAdapterUtil.adaptModelFilterOperator( filterCon.getOperator( ) ), value1 == null ? null : modelAdapter.adaptExpression( value1.get( 0 ) ), value2 == null ? null : modelAdapter.adaptExpression( (Expression) value2 ) ); } ILevelDefinition levelDefinition = null; if ( filterCon.getMember( ) != null ) { levelDefinition = registeredLevelHandles.get( filterCon.getMember( ) .getLevel( ) ); } else { // Do not need to set target level for dimension filter due to // DTE support // String levelName = exprCodec.getCubeBindingName( // filterCondExpr.getExpression( ) // .getText( ), // true ); // if ( levelName != null // && exprCodec.getCubeBindingNameList( ).size( ) > 1 ) // // In multiple dimensions case, do not set target level. // levelName = null; // levelDefinition = registeredLevels.get( levelName ); } ICubeFilterDefinition filterDef = getCubeElementFactory( ).creatCubeFilterDefinition( filterCondExpr, levelDefinition, qualifyLevels, qualifyValues ); cubeQuery.addFilter( filterDef ); } } @SuppressWarnings("unchecked") private List<FilterConditionElementHandle> getFiltersFromXtab( CrosstabReportItemHandle crossTab ) { List<FilterConditionElementHandle> list = new ArrayList<FilterConditionElementHandle>( ); if ( crossTab == null ) { return list; } if ( crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ) != null ) { DesignElementHandle elementHandle = crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ) .getModelHandle( ); list.addAll( getLevelOnCrosstab( (ExtendedItemHandle) elementHandle ) ); } if ( crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ) != null ) { DesignElementHandle elementHandle = crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ) .getModelHandle( ); list.addAll( getLevelOnCrosstab( (ExtendedItemHandle) elementHandle ) ); } int measureCount = crossTab.getMeasureCount( ); for ( int i = 0; i < measureCount; i++ ) { MeasureViewHandle measureView = crossTab.getMeasure( i ); Iterator<FilterConditionElementHandle> iter = measureView.filtersIterator( ); while ( iter.hasNext( ) ) { list.add( iter.next( ) ); } } return list; } @SuppressWarnings("unchecked") private List<FilterConditionElementHandle> getLevelOnCrosstab( ExtendedItemHandle handle ) { CrosstabViewHandle crossTabViewHandle = null; try { crossTabViewHandle = (CrosstabViewHandle) handle.getReportItem( ); } catch ( ExtendedElementException e ) { logger.log( e ); } List<FilterConditionElementHandle> list = new ArrayList<FilterConditionElementHandle>( ); if ( crossTabViewHandle == null ) { return list; } int dimensionCount = crossTabViewHandle.getDimensionCount( ); for ( int i = 0; i < dimensionCount; i++ ) { DimensionViewHandle dimension = crossTabViewHandle.getDimension( i ); int levelCount = dimension.getLevelCount( ); for ( int j = 0; j < levelCount; j++ ) { LevelViewHandle levelHandle = dimension.getLevel( j ); Iterator<FilterConditionElementHandle> iter = levelHandle.filtersIterator( ); while ( iter.hasNext( ) ) { list.add( iter.next( ) ); } } } return list; } /** * Recursively add all member values and associated levels to the given * list. */ private void addMembers( List<ILevelDefinition> levels, List<String> values, MemberValueHandle member ) { if ( member != null ) { ILevelDefinition levelDef = registeredLevelHandles.get( member.getLevel( ) ); if ( levelDef != null ) { levels.add( levelDef ); values.add( member.getValue( ) ); if ( member.getContentCount( IMemberValueModel.MEMBER_VALUES_PROP ) > 0 ) { // only use first member here addMembers( levels, values, (MemberValueHandle) member.getContent( IMemberValueModel.MEMBER_VALUES_PROP, 0 ) ); } } } } /** * Gets all levels and sorts them in hierarchy order in multiple levels * case. * * @param cubeHandle * @param cubeQuery */ private Collection<ILevelDefinition> getAllLevelsInHierarchyOrder( CubeHandle cubeHandle, ICubeQueryDefinition cubeQuery ) { Collection<ILevelDefinition> levelValues = registeredLevels.values( ); // Only sort the level for multiple levels case if ( levelValues.size( ) > 1 ) { List<ILevelDefinition> levelList = new ArrayList<ILevelDefinition>( levelValues.size( ) ); for ( ILevelDefinition level : levelValues ) { levelList.add( level ); } Collections.sort( levelList, getLevelComparator( cubeHandle, true ) ); return levelList; } return levelValues; } protected int getEdgeType( String dimensionName ) { if ( this.rowEdgeDimension == null ) { this.rowEdgeDimension = dimensionName; return ICubeQueryDefinition.ROW_EDGE; } return this.rowEdgeDimension.equals( dimensionName ) ? ICubeQueryDefinition.ROW_EDGE : ICubeQueryDefinition.COLUMN_EDGE; } private Comparator<ILevelDefinition> getLevelComparator( final CubeHandle cubeHandle, final boolean hasDiffEdges ) { return new Comparator<ILevelDefinition>( ) { public int compare( ILevelDefinition a, ILevelDefinition b ) { String dimA = a.getHierarchy( ).getDimension( ).getName( ); int edgeA = getEdgeType( dimA ); // If edges are the same, do not check again. if ( hasDiffEdges ) { // If edges are different, column edge should be latter. String dimB = b.getHierarchy( ).getDimension( ).getName( ); int edgeB = getEdgeType( dimB ); if ( edgeA != edgeB ) { return edgeA == ICubeQueryDefinition.COLUMN_EDGE ? 1 : -1; } } String dimB = b.getHierarchy( ).getDimension( ).getName( ); // If the level index is bigger, it should be latter. HierarchyHandle hh = cubeHandle.getDimension( dimA ) .getDefaultHierarchy( ); HierarchyHandle hb = hh; if ( !dimB.equals( dimA ) ) { hb = cubeHandle.getDimension( dimB ).getDefaultHierarchy( ); } return hh.getLevel( a.getName( ) ).getIndex( ) - hb.getLevel( b.getName( ) ).getIndex( ); } }; } private void sortLevelDefinition( IEdgeDefinition edge, CubeHandle cubeHandle ) { if ( edge != null ) { for ( IDimensionDefinition dim : edge.getDimensions( ) ) { IHierarchyDefinition hd = dim.getHierarchy( ).get( 0 ); if ( hd != null && hd.getLevels( ).size( ) > 1 ) { Collections.sort( hd.getLevels( ), getLevelComparator( cubeHandle, false ) ); } } } } static List<SeriesDefinition> getAllSeriesDefinitions( Chart chart ) { List<SeriesDefinition> seriesList = new ArrayList<SeriesDefinition>( ); if ( chart instanceof ChartWithAxes ) { Axis xAxis = ( (ChartWithAxes) chart ).getAxes( ).get( 0 ); // Add base series definitions seriesList.addAll( xAxis.getSeriesDefinitions( ) ); EList<Axis> axisList = xAxis.getAssociatedAxes( ); for ( int i = 0; i < axisList.size( ); i++ ) { // Add value series definitions seriesList.addAll( axisList.get( i ).getSeriesDefinitions( ) ); } } else if ( chart instanceof ChartWithoutAxes ) { SeriesDefinition sdBase = ( (ChartWithoutAxes) chart ).getSeriesDefinitions( ) .get( 0 ); seriesList.add( sdBase ); seriesList.addAll( sdBase.getSeriesDefinitions( ) ); } return seriesList; } }
package net.mitchtech.xposed; import static de.robv.android.xposed.XposedHelpers.findAndHookConstructor; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import android.content.Context; import android.graphics.Paint; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.EditText; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XSharedPreferences; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XC_MethodHook.MethodHookParam; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class XposedTextReplace implements IXposedHookLoadPackage, IXposedHookZygoteInit { private static final String TAG = XposedTextReplace.class.getSimpleName(); private static final String PKG_NAME = "net.mitchtech.xposed.textreplace"; private XSharedPreferences prefs; public ArrayList<TextReplaceEntry> replacements; @Override public void initZygote(StartupParam startupParam) throws Throwable { loadPrefs(); } @Override public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { // don't replace text in this package, otherwise can't edit macros if (lpparam.packageName.equals(PKG_NAME)) { return; } // don't proceed if current package is system ui and is disabled if (lpparam.packageName.equals("com.android.systemui")) { if (!isEnabled("prefSystemUi")) { return; } // don't proceed for other apps if preference is disabled } else { if (!isEnabled("prefAllApps")) { return; } } // common hook method for all textview methods XC_MethodHook replaceTextMethodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam methodHookParam) throws Throwable { CharSequence actualText = (CharSequence) methodHookParam.args[0]; if (actualText != null) { String replacementText = replaceText(actualText.toString()); methodHookParam.args[0] = replacementText; } } }; // common hook method for all edittext constructors XC_MethodHook editTextMethodHook = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam methodHookParam) throws Throwable { final EditText editText = (EditText) methodHookParam.thisObject; if (editText instanceof MultiAutoCompleteTextView) { // XposedBridge.log(TAG + ": MultiAutoCompleteTextView"); return; } editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if (!hasFocus) { String actualText = editText.getText().toString(); // XposedBridge.log(TAG + ": onFocusChange(): " + actualText); String replacementText = replaceText(actualText); // prevent stack overflow, only set text if modified if (!actualText.equals(replacementText)) { editText.setText(replacementText); editText.setSelection(editText.getText().length()); } } } }); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence text, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence text, int start, int count, int after) { } @Override public void afterTextChanged(Editable editable) { String actualText = editable.toString(); // XposedBridge.log(TAG + ": afterTextChanged(): " + actualText); String replacementText = replaceText(actualText); // prevent stack overflow, only set text if modified if (!actualText.equals(replacementText)) { editText.setText(replacementText); editText.setSelection(editText.getText().length()); } } }); } }; // hook standard text views if (isEnabled("prefTextView")) { findAndHookMethod(TextView.class, "setText", CharSequence.class, TextView.BufferType.class, boolean.class, int.class, replaceTextMethodHook); findAndHookMethod(TextView.class, "setHint", CharSequence.class, replaceTextMethodHook); findAndHookMethod(TextView.class, "append", CharSequence.class, replaceTextMethodHook); findAndHookMethod(TextView.class, "append", CharSequence.class, int.class, int.class, replaceTextMethodHook); } // hook GL canvas text views if (isEnabled("prefGlText")) { findAndHookMethod("android.view.GLES20Canvas", null, "drawText", String.class, float.class, float.class, Paint.class, replaceTextMethodHook); } // hook editable text views if (isEnabled("prefEditText")) { // redundant since edittext descendant of textview? findAndHookMethod(EditText.class, "setText", CharSequence.class, TextView.BufferType.class, replaceTextMethodHook); // public EditText(Context context) findAndHookConstructor(EditText.class, Context.class, editTextMethodHook); // public EditText(Context context, AttributeSet attrs) findAndHookConstructor(EditText.class, Context.class, AttributeSet.class, editTextMethodHook); // public EditText(Context context, AttributeSet attrs, int defStyle) findAndHookConstructor(EditText.class, Context.class, AttributeSet.class, int.class, editTextMethodHook); } } private String replaceText(String actualText) { String replacementText = actualText.toString(); if (replacements != null && !replacements.isEmpty()) { for (TextReplaceEntry replacement : replacements) { if (isEnabled("prefCaseSensitive")) { // case sensitive replacement replacementText = replacementText.replaceAll(replacement.actual, replacement.replacement); } else { // "(?i)" used for case insensitive replace replacementText = replacementText.replaceAll(("(?i)" + replacement.actual), replacement.replacement); } } } return replacementText; } private boolean isEnabled(String pkgName) { prefs.reload(); return prefs.getBoolean(pkgName, false); } private void loadPrefs() { prefs = new XSharedPreferences(PKG_NAME); prefs.makeWorldReadable(); String json = prefs.getString("json", ""); Type type = new TypeToken<List<TextReplaceEntry>>() { }.getType(); replacements = new Gson().fromJson(json, type); XposedBridge.log(TAG + ": prefs loaded."); } }
package io.cattle.iaas.healthcheck.service.impl; import static io.cattle.platform.core.constants.HealthcheckConstants.*; import static io.cattle.platform.core.model.tables.HealthcheckInstanceHostMapTable.*; import static io.cattle.platform.core.model.tables.HealthcheckInstanceTable.*; import static io.cattle.platform.core.util.SystemLabels.*; import io.cattle.iaas.healthcheck.service.HealthcheckService; import io.cattle.platform.allocator.dao.AllocatorDao; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.HealthcheckConstants; import io.cattle.platform.core.dao.GenericMapDao; import io.cattle.platform.core.dao.GenericResourceDao; import io.cattle.platform.core.dao.HostDao; import io.cattle.platform.core.dao.NetworkDao; import io.cattle.platform.core.model.HealthcheckInstance; import io.cattle.platform.core.model.HealthcheckInstanceHostMap; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.InstanceHostMap; import io.cattle.platform.lock.LockCallbackNoReturn; import io.cattle.platform.lock.LockManager; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.meta.ObjectMetaDataManager; import io.cattle.platform.object.process.ObjectProcessManager; import io.cattle.platform.object.process.StandardProcess; import io.cattle.platform.util.type.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.inject.Inject; import org.apache.commons.collections.TransformerUtils; public class HealthcheckServiceImpl implements HealthcheckService { @Inject GenericMapDao mapDao; @Inject ObjectManager objectManager; @Inject GenericResourceDao resourceDao; @Inject ObjectProcessManager objectProcessManager; @Inject LockManager lockManager; @Inject AllocatorDao allocatorDao; @Inject HostDao hostDao; @Inject NetworkDao ntwkDao; @Override public void updateHealthcheck(String healthcheckInstanceHostMapUuid, final long externalTimestamp, final String healthState) { HealthcheckInstanceHostMap hcihm = objectManager.findOne(HealthcheckInstanceHostMap.class, ObjectMetaDataManager.UUID_FIELD, healthcheckInstanceHostMapUuid); if (!shouldUpdate(hcihm, externalTimestamp, healthState)) { return; } String hcihmNewState = healthState; if (healthState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_INITIALIZING)) { if (!hcihm.getState().equalsIgnoreCase(healthState)) { hcihmNewState = HealthcheckConstants.HEALTH_STATE_REINITIALIZING; } } final HealthcheckInstanceHostMap updatedHcihm = objectManager.setFields(hcihm, HEALTHCHECK_INSTANCE_HOST_MAP.EXTERNAL_TIMESTAMP, externalTimestamp, HEALTHCHECK_INSTANCE_HOST_MAP.HEALTH_STATE, hcihmNewState); lockManager.lock(new HealthcheckInstanceLock(hcihm.getHealthcheckInstanceId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { processHealthcheckInstance(updatedHcihm, healthState); } }); } @Override public void healthCheckReconcile(final HealthcheckInstanceHostMap hcihm, final String healthState) { final HealthcheckInstance hcInstance = objectManager.loadResource(HealthcheckInstance.class, hcihm.getHealthcheckInstanceId()); lockManager.lock(new HealthcheckInstanceLock(hcInstance.getId()), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { processHealthcheckInstance(hcihm, healthState); } }); } protected void processHealthcheckInstance(HealthcheckInstanceHostMap hcihm, String healthState) { HealthcheckInstance hcInstance = objectManager.loadResource(HealthcheckInstance.class, hcihm.getHealthcheckInstanceId()); String updateWithState = determineNewHealthState(hcInstance, hcihm, healthState); if (updateWithState == null) { return; } Instance instance = objectManager.loadResource(Instance.class, hcInstance.getInstanceId()); updateInstanceHealthState(instance, updateWithState); } protected boolean shouldUpdate(HealthcheckInstanceHostMap hcihm, long externalTimestamp, String healthState) { HealthcheckInstance hcInstance = objectManager.loadResource(HealthcheckInstance.class, hcihm.getHealthcheckInstanceId()); if (healthState.equalsIgnoreCase(HEALTH_STATE_UNHEALTHY) && HealthcheckConstants.isInit(getHealthState(hcInstance))) { return false; } if (hcihm.getExternalTimestamp() == null) { return true; } if (externalTimestamp < hcihm.getExternalTimestamp()) { return false; } return true; } protected String determineNewHealthState(HealthcheckInstance hcInstance, HealthcheckInstanceHostMap hcihm, String healthState) { List<HealthcheckInstanceHostMap> others = objectManager.find(HealthcheckInstanceHostMap.class, HEALTHCHECK_INSTANCE_HOST_MAP.HEALTHCHECK_INSTANCE_ID, hcInstance.getId(), HEALTHCHECK_INSTANCE_HOST_MAP.STATE, CommonStatesConstants.ACTIVE); boolean currentlyHealthy = HEALTH_STATE_HEALTHY.equals(getHealthState(hcInstance)); if (healthState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_HEALTHY)) { return currentlyHealthy ? null : healthState; } else if (healthState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_INITIALIZING)) { return currentlyHealthy ? HealthcheckConstants.HEALTH_STATE_REINITIALIZING : null; } else { if (!currentlyHealthy) { return null; } boolean seenUnhealthy = HEALTH_STATE_UNHEALTHY.equals(healthState); boolean seenHealthy = HEALTH_STATE_HEALTHY.equals(healthState); int i = 0; for (HealthcheckInstanceHostMap map : others) { if (map.getId().equals(hcihm.getId())) { continue; } i++; if (HEALTH_STATE_UNHEALTHY.equals(map.getHealthState())) { seenUnhealthy = true; } else if (HEALTH_STATE_HEALTHY.equals(map.getHealthState())) { seenHealthy = true; break; } } boolean allUnhealthy = seenUnhealthy && !seenHealthy; if (healthState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_RECONCILE)) { // if no other hosts are present, don't change the state; // otherwise calculate based on the health check present if (i == 0) { return null; } else { return allUnhealthy ? HealthcheckConstants.HEALTH_STATE_UNHEALTHY : null; } } return allUnhealthy ? healthState : null; } } protected String getHealthState(HealthcheckInstance hcInstance) { Instance instance = objectManager.loadResource(Instance.class, hcInstance.getInstanceId()); return instance == null ? null : instance.getHealthState(); } @Override public void updateInstanceHealthState(Instance instance, String updateWithState) { if (instance != null) { if (updateWithState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_HEALTHY)) { objectProcessManager.scheduleProcessInstance(HealthcheckConstants.PROCESS_UPDATE_HEALTHY, instance, null); } else if (updateWithState.equalsIgnoreCase(HealthcheckConstants.HEALTH_STATE_REINITIALIZING)) { objectProcessManager.scheduleProcessInstance(HealthcheckConstants.PROCESS_UPDATE_REINITIALIZING, instance, null); } else { objectProcessManager.scheduleProcessInstance(HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, instance, null); } } } @Override public void registerForHealtcheck(final HealthcheckInstanceType instanceType, final long id) { final Long accountId = getAccountId(instanceType, id); if (accountId == null) { return; } lockManager.lock(new HealthcheckRegisterLock(id, instanceType), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { // 1. create healthcheckInstance mapping HealthcheckInstance healthInstance = createHealtcheckInstance(id, accountId); // 2. create healtcheckInstance to hosts mappings createHealthCheckHostMaps(instanceType, id, accountId, healthInstance); } }); } protected HealthcheckInstance createHealtcheckInstance(long id, Long accountId) { HealthcheckInstance healthInstance = objectManager.findAny(HealthcheckInstance.class, HEALTHCHECK_INSTANCE.ACCOUNT_ID, accountId, HEALTHCHECK_INSTANCE.INSTANCE_ID, id, HEALTHCHECK_INSTANCE.REMOVED, null); if (healthInstance == null) { healthInstance = resourceDao.createAndSchedule(HealthcheckInstance.class, HEALTHCHECK_INSTANCE.ACCOUNT_ID, accountId, HEALTHCHECK_INSTANCE.INSTANCE_ID, id); } return healthInstance; } protected void createHealthCheckHostMaps(HealthcheckInstanceType instanceType, long id, Long accountId, HealthcheckInstance healthInstance) { Long inferiorHostId = getInstanceHostId(instanceType, id); List<Long> healthCheckHostIds = getHealthCheckHostIds(healthInstance, inferiorHostId); List<HealthcheckInstanceHostMap> healthHostMaps = objectManager.find(HealthcheckInstanceHostMap.class, HEALTHCHECK_INSTANCE_HOST_MAP.HEALTHCHECK_INSTANCE_ID, healthInstance.getId(), HEALTHCHECK_INSTANCE_HOST_MAP.REMOVED, null); for (Long healthCheckHostId : healthCheckHostIds) { HealthcheckInstanceHostMap healthHostMap = null; for(HealthcheckInstanceHostMap hostMap : healthHostMaps) { if(!hostMap.getHostId().equals(healthCheckHostId)) { continue; } if (healthHostMap == null) { healthHostMap = hostMap; } else if (!hostMap.getState().equals(CommonStatesConstants.REMOVING)) { objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, hostMap, null); } } Long instanceId = (instanceType == HealthcheckInstanceType.INSTANCE ? id : null); if (healthHostMap == null) { resourceDao.createAndSchedule(HealthcheckInstanceHostMap.class, HEALTHCHECK_INSTANCE_HOST_MAP.HOST_ID, healthCheckHostId, HEALTHCHECK_INSTANCE_HOST_MAP.HEALTHCHECK_INSTANCE_ID, healthInstance.getId(), HEALTHCHECK_INSTANCE_HOST_MAP.ACCOUNT_ID, accountId, HEALTHCHECK_INSTANCE_HOST_MAP.INSTANCE_ID, instanceId); } } } @SuppressWarnings("unchecked") private List<Long> getHealthCheckHostIds(HealthcheckInstance healthInstance, Long inferiorHostId) { int requiredNumber = 3; List<? extends HealthcheckInstanceHostMap> existingHostMaps = mapDao.findNonRemoved( HealthcheckInstanceHostMap.class, HealthcheckInstance.class, healthInstance.getId()); List<? extends Host> availableActiveHosts = allocatorDao.getActiveHosts(healthInstance.getAccountId()); // skip hosts labeled accordingly Iterator<? extends Host> it = availableActiveHosts.iterator(); while (it.hasNext()) { String deployStrategy = (String) CollectionUtils.getNestedValue(it.next().getData(), "fields", "labels", LABEL_HEALTHCHECK_DEPLOY_STRATEGY); if (deployStrategy != null && "skip".equals(deployStrategy)) { it.remove(); } } List<Long> availableActiveHostIds = (List<Long>) org.apache.commons.collections.CollectionUtils.collect(availableActiveHosts, TransformerUtils.invokerTransformer("getId")); List<Long> allocatedActiveHostIds = (List<Long>) org.apache.commons.collections.CollectionUtils.collect(existingHostMaps, TransformerUtils.invokerTransformer("getHostId")); // skip the host that if not active (being removed, reconnecting, etc) Iterator<Long> it2 = allocatedActiveHostIds.iterator(); while (it2.hasNext()) { Long allocatedHostId = it2.next(); if (!availableActiveHostIds.contains(allocatedHostId)) { it2.remove(); } } // return if allocated active hosts is >= required number of hosts for healtcheck if (allocatedActiveHostIds.size() >= requiredNumber) { return new ArrayList<>(); } // remove allocated hosts from the available hostIds and shuffle the list to randomize the choice availableActiveHostIds.removeAll(allocatedActiveHostIds); requiredNumber = requiredNumber - allocatedActiveHostIds.size(); Collections.shuffle(availableActiveHostIds); // place inferiorHostId to the end of the list if (inferiorHostId != null) { if (availableActiveHostIds.contains(inferiorHostId)) { availableActiveHostIds.remove(inferiorHostId); } if(!allocatedActiveHostIds.contains(inferiorHostId)) { availableActiveHostIds.add(inferiorHostId); } } // Figure out the final number of hosts int returnedNumber = requiredNumber > availableActiveHostIds.size() ? availableActiveHostIds.size() : requiredNumber; // always include inferiorHostId int start_index = availableActiveHostIds.size() - returnedNumber; return availableActiveHostIds.subList(start_index, availableActiveHostIds.size()); } private Long getInstanceHostId(HealthcheckInstanceType type, long instanceId) { if (type == HealthcheckInstanceType.INSTANCE) { List<? extends InstanceHostMap> maps = mapDao.findNonRemoved(InstanceHostMap.class, Instance.class, instanceId); if (!maps.isEmpty()) { return maps.get(0).getHostId(); } } return null; } private Long getAccountId(HealthcheckInstanceType type, long instanceId) { if (type == HealthcheckInstanceType.INSTANCE) { Instance instance = objectManager.loadResource(Instance.class, instanceId); if (instance != null) { return instance.getAccountId(); } } return null; } }
package org.opendaylight.yangtools.util.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.Uninterruptibles; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unit tests for QueuedNotificationManager. * * @author Thomas Pantelis */ public class QueuedNotificationManagerTest { static class TestListener<N> { private final List<N> actual; private volatile int expCount; private volatile CountDownLatch latch; volatile long sleepTime = 0; volatile RuntimeException runtimeEx; volatile Error jvmError; boolean cacheNotifications = true; String name; TestListener(final int expCount, final int id) { name = "TestListener " + id; actual = Collections.synchronizedList(new ArrayList<>(expCount)); reset(expCount); } void reset(final int expCount) { this.expCount = expCount; latch = new CountDownLatch(expCount); actual.clear(); } void onNotification(final N data) { try { if (sleepTime > 0) { Uninterruptibles.sleepUninterruptibly( sleepTime, TimeUnit.MILLISECONDS); } if (cacheNotifications) { actual.add(data); } RuntimeException localRuntimeEx = runtimeEx; if (localRuntimeEx != null) { runtimeEx = null; throw localRuntimeEx; } Error localJvmError = jvmError; if (localJvmError != null) { jvmError = null; throw localJvmError; } } finally { latch.countDown(); } } void verifyNotifications() { boolean done = Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS); if (!done) { long actualCount = latch.getCount(); fail(name + ": Received " + (expCount - actualCount) + " notifications. Expected " + expCount); } } void verifyNotifications(final List<N> expected) { verifyNotifications(); assertEquals(name + ": Notifications", expected, actual); } // Implement bad hashCode/equals methods to verify it doesn't screw up the // QueuedNotificationManager as it should use reference identity. @Override public int hashCode() { return 1; } @Override public boolean equals(final Object obj) { TestListener<?> other = (TestListener<?>) obj; return other != null; } } static class TestListener2<N> extends TestListener<N> { TestListener2(final int expCount, final int id) { super(expCount, id); } } static class TestListener3<N> extends TestListener<N> { TestListener3(final int expCount, final int id) { super(expCount, id); } } static class TestNotifier<N> implements QueuedNotificationManager.Invoker<TestListener<N>, N> { @Override public void invokeListener(final TestListener<N> listener, final N notification) { listener.onNotification(notification); } } private static final Logger LOG = LoggerFactory.getLogger(QueuedNotificationManagerTest.class); private ExecutorService queueExecutor; @After public void tearDown() { if (queueExecutor != null) { queueExecutor.shutdownNow(); } } @Test(timeout=10000) public void testNotificationsWithSingleListener() { queueExecutor = Executors.newFixedThreadPool( 2 ); NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>(queueExecutor, new TestNotifier<>(), 10, "TestMgr" ); int initialCount = 6; int nNotifications = 100; TestListener<Integer> listener = new TestListener<>(nNotifications, 1); listener.sleepTime = 20; manager.submitNotifications(listener, Arrays.asList(1, 2)); manager.submitNotification(listener, 3); manager.submitNotifications(listener, Arrays.asList(4, 5)); manager.submitNotification(listener, 6); manager.submitNotifications(null, Collections.emptyList()); manager.submitNotifications(listener, null); manager.submitNotification(listener, null); Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); listener.sleepTime = 0; List<Integer> expNotifications = new ArrayList<>(nNotifications); expNotifications.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)); for (int i = 1; i <= nNotifications - initialCount; i++) { Integer v = Integer.valueOf(initialCount + i); expNotifications.add(v); manager.submitNotification(listener, v); } listener.verifyNotifications( expNotifications ); } @Test public void testNotificationsWithMultipleListeners() throws InterruptedException { int nListeners = 10; queueExecutor = Executors.newFixedThreadPool(nListeners); final ExecutorService stagingExecutor = Executors.newFixedThreadPool(nListeners); final NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>( queueExecutor, new TestNotifier<>(), 5000, "TestMgr" ); final int nNotifications = 100000; LOG.info("Testing {} listeners with {} notifications each...", nListeners, nNotifications); final Integer[] notifications = new Integer[nNotifications]; for (int i = 1; i <= nNotifications; i++) { notifications[i - 1] = Integer.valueOf(i); } Stopwatch stopWatch = Stopwatch.createStarted(); List<TestListener<Integer>> listeners = new ArrayList<>(); List<Thread> threads = new ArrayList<>(); for (int i = 1; i <= nListeners; i++) { final TestListener<Integer> listener = i == 2 ? new TestListener2<>(nNotifications, i) : i == 3 ? new TestListener3<>(nNotifications, i) : new TestListener<>(nNotifications, i); listeners.add(listener); final Thread t = new Thread(() -> { for (int j = 1; j <= nNotifications; j++) { final Integer n = notifications[j - 1]; stagingExecutor.execute(() -> manager.submitNotification(listener, n)); } }); t.start(); threads.add(t); } try { for (TestListener<Integer> listener: listeners) { listener.verifyNotifications(); LOG.info("{} succeeded", listener.name); } } finally { stagingExecutor.shutdownNow(); } stopWatch.stop(); LOG.info("Elapsed time: {}", stopWatch); LOG.info("Executor: {}", queueExecutor); for (Thread t : threads) { t.join(); } } @Test(timeout=10000) public void testNotificationsWithListenerRuntimeEx() { queueExecutor = Executors.newFixedThreadPool(1); NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>( queueExecutor, new TestNotifier<>(), 10, "TestMgr" ); TestListener<Integer> listener = new TestListener<>(2, 1); final RuntimeException mockedRuntimeException = mock(RuntimeException.class); doNothing().when(mockedRuntimeException).printStackTrace(any(PrintStream.class)); listener.runtimeEx = mockedRuntimeException; manager.submitNotification(listener, 1); manager.submitNotification(listener, 2); listener.verifyNotifications(); } @Test(timeout=10000) public void testNotificationsWithListenerJVMError() { final CountDownLatch errorCaughtLatch = new CountDownLatch(1); queueExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()) { @Override public void execute(final Runnable command) { super.execute(() -> { try { command.run(); } catch (Error e) { errorCaughtLatch.countDown(); } }); } }; NotificationManager<TestListener<Integer>, Integer> manager = new QueuedNotificationManager<>(queueExecutor, new TestNotifier<>(), 10, "TestMgr"); TestListener<Integer> listener = new TestListener<>(2, 1); listener.jvmError = mock(Error.class); manager.submitNotification(listener, 1); assertEquals("JVM Error caught", true, Uninterruptibles.awaitUninterruptibly( errorCaughtLatch, 5, TimeUnit.SECONDS)); manager.submitNotification(listener, 2); listener.verifyNotifications(); } }
package org.neo4j.kernel.impl.nioneo.xa; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import org.neo4j.kernel.impl.nioneo.store.AbstractBaseRecord; import org.neo4j.kernel.impl.nioneo.store.DynamicRecord; import org.neo4j.kernel.impl.nioneo.store.LabelTokenRecord; import org.neo4j.kernel.impl.nioneo.store.NeoStore; import org.neo4j.kernel.impl.nioneo.store.NodeRecord; import org.neo4j.kernel.impl.nioneo.store.NodeStore; import org.neo4j.kernel.impl.nioneo.store.PrimitiveRecord; import org.neo4j.kernel.impl.nioneo.store.PropertyKeyTokenRecord; import org.neo4j.kernel.impl.nioneo.store.PropertyRecord; import org.neo4j.kernel.impl.nioneo.store.PropertyStore; import org.neo4j.kernel.impl.nioneo.store.RelationshipGroupRecord; import org.neo4j.kernel.impl.nioneo.store.RelationshipRecord; import org.neo4j.kernel.impl.nioneo.store.RelationshipStore; import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeTokenRecord; import org.neo4j.kernel.impl.nioneo.store.SchemaRule; import org.neo4j.kernel.impl.nioneo.xa.RecordChanges.RecordChange; import org.neo4j.kernel.impl.nioneo.xa.command.Command.NodeCommand; import org.neo4j.kernel.impl.nioneo.xa.command.NeoCommandVisitor; import org.neo4j.kernel.impl.transaction.xaframework.PhysicalTransactionRepresentation; public class WriteTransactionCommandOrderingTest { private final AtomicReference<List<String>> currentRecording = new AtomicReference<>(); private final NeoStore store = mock( NeoStore.class ); private final RecordingRelationshipStore relationshipStore = new RecordingRelationshipStore( currentRecording ); private final RecordingNodeStore nodeStore = new RecordingNodeStore( currentRecording ); private final RecordingPropertyStore propertyStore = new RecordingPropertyStore( currentRecording ); public WriteTransactionCommandOrderingTest() { when( store.getPropertyStore() ).thenReturn( propertyStore ); when( store.getNodeStore() ).thenReturn( nodeStore ); when( store.getRelationshipStore() ).thenReturn( relationshipStore ); } @Test public void shouldExecuteCommandsInTheSameOrderRegardlessOfItBeingRecoveredOrNot() throws Exception { // Given TransactionRecordState tx = injectAllPossibleCommands(); // When PhysicalTransactionRepresentation commands = tx.doPrepare(); // Then commands.execute( new OrderVerifyingCommandVisitor() ); } private TransactionRecordState injectAllPossibleCommands() { NeoStoreTransactionContext context = mock( NeoStoreTransactionContext.class ); RecordChanges<Integer,LabelTokenRecord,Void> labelTokenChanges = mock( RecordChanges.class); RecordChanges<Integer,RelationshipTypeTokenRecord,Void> relationshipTypeTokenChanges = mock( RecordChanges.class); RecordChanges<Integer,PropertyKeyTokenRecord,Void> propertyKeyTokenChanges = mock( RecordChanges.class); RecordChanges<Long,NodeRecord,Void> nodeRecordChanges = mock( RecordChanges.class); RecordChanges<Long,RelationshipRecord,Void> relationshipRecordChanges = mock( RecordChanges.class); RecordChanges<Long,PropertyRecord,PrimitiveRecord> propertyRecordChanges = mock( RecordChanges.class); RecordChanges<Long,RelationshipGroupRecord,Integer> relationshipGroupChanges = mock( RecordChanges.class); RecordChanges<Long, Collection<DynamicRecord>, SchemaRule> schemaRuleChanges = mock( RecordChanges.class); when( context.getLabelTokenRecords() ).thenReturn( labelTokenChanges ); when( context.getRelationshipTypeTokenRecords() ).thenReturn( relationshipTypeTokenChanges ); when( context.getPropertyKeyTokenRecords() ).thenReturn( propertyKeyTokenChanges ); when( context.getNodeRecords() ).thenReturn( nodeRecordChanges ); when( context.getRelRecords() ).thenReturn( relationshipRecordChanges ); when( context.getPropertyRecords() ).thenReturn( propertyRecordChanges ); when( context.getRelGroupRecords() ).thenReturn( relationshipGroupChanges ); when( context.getSchemaRuleChanges() ).thenReturn( schemaRuleChanges ); List<RecordChange<Long, NodeRecord, Void>> nodeChanges = new LinkedList<>(); RecordChange<Long, NodeRecord, Void> deletedNode = mock( RecordChange.class ); when( deletedNode.getBefore() ).thenReturn( inUseNode() ); when( deletedNode.forReadingLinkage() ).thenReturn( missingNode() ); nodeChanges.add( deletedNode ); RecordChange<Long, NodeRecord, Void> createdNode = mock( RecordChange.class ); when( createdNode.getBefore() ).thenReturn( missingNode() ); when( createdNode.forReadingLinkage() ).thenReturn( createdNode() ); nodeChanges.add( createdNode ); RecordChange<Long, NodeRecord, Void> updatedNode = mock( RecordChange.class ); when( updatedNode.getBefore() ).thenReturn( inUseNode() ); when( updatedNode.forReadingLinkage() ).thenReturn( inUseNode() ); nodeChanges.add( updatedNode ); when( nodeRecordChanges.changes() ).thenReturn( nodeChanges ); when( labelTokenChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Integer,LabelTokenRecord,Void>>emptyList() ); when( relationshipTypeTokenChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Integer,RelationshipTypeTokenRecord,Void>>emptyList() ); when( propertyKeyTokenChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Integer,PropertyKeyTokenRecord,Void>>emptyList() ); when( relationshipRecordChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Long,RelationshipRecord,Void>>emptyList() ); when( propertyRecordChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Long,PropertyRecord,PrimitiveRecord>>emptyList() ); when( relationshipGroupChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Long,RelationshipGroupRecord,Integer>>emptyList() ); when( schemaRuleChanges.changes() ).thenReturn( Collections.<RecordChanges.RecordChange<Long,Collection<DynamicRecord>,SchemaRule>>emptyList() ); return new TransactionRecordState( 1, mock( NeoStore.class), mock( IntegrityValidator.class), context ); // Command.PropertyCommand updatedProp = new Command.PropertyCommand(); // updatedProp.init( inUseProperty(), inUseProperty() ); // tx.injectCommand( updatedProp ); // Command.PropertyCommand deletedProp = new Command.PropertyCommand(); // deletedProp.init( inUseProperty(), missingProperty() ); // tx.injectCommand( deletedProp ); // Command.PropertyCommand createdProp = new Command.PropertyCommand(); // createdProp.init( missingProperty(), createdProperty() ); // tx.injectCommand( createdProp ); // Command.RelationshipCommand updatedRel = new Command.RelationshipCommand(); // updatedRel.init( inUseRelationship() ); // tx.injectCommand( updatedRel ); // Command.RelationshipCommand deletedRel =new Command.RelationshipCommand(); // deletedRel.init( missingRelationship() ); // tx.injectCommand( deletedRel ); // Command.RelationshipCommand createdRel = new Command.RelationshipCommand(); // createdRel.init( createdRelationship() ); // tx.injectCommand( createdRel ); } private static RelationshipRecord missingRelationship() { return new RelationshipRecord( -1 ); } private static RelationshipRecord createdRelationship() { RelationshipRecord record = new RelationshipRecord( 2 ); record.setInUse( true ); record.setCreated(); return record; } private static RelationshipRecord inUseRelationship() { RelationshipRecord record = new RelationshipRecord( 1 ); record.setInUse( true ); return record; } private static PropertyRecord missingProperty() { return new PropertyRecord( -1 ); } private static PropertyRecord createdProperty() { PropertyRecord record = new PropertyRecord( 2 ); record.setInUse( true ); record.setCreated(); return record; } private static PropertyRecord inUseProperty() { PropertyRecord record = new PropertyRecord( 1 ); record.setInUse( true ); return record; } private static NodeRecord missingNode() { return new NodeRecord(-1, false, -1, -1); } private static NodeRecord createdNode() { NodeRecord record = new NodeRecord( 2, false, -1, -1 ); record.setInUse( true ); record.setCreated(); return record; } private static NodeRecord inUseNode() { NodeRecord record = new NodeRecord( 1, false, -1, -1 ); record.setInUse( true ); return record; } private static String commandActionToken( AbstractBaseRecord record ) { if ( !record.inUse() ) { return "deleted"; } if ( record.isCreated() ) { return "created"; } return "updated"; } private static class RecordingPropertyStore extends PropertyStore { private final AtomicReference<List<String>> currentRecording; public RecordingPropertyStore( AtomicReference<List<String>> currentRecording ) { super( null, null, null, null, null, null, null, null, null, null ); this.currentRecording = currentRecording; } @Override public void updateRecord(PropertyRecord record) { currentRecording.get().add(commandActionToken(record) + " property"); } @Override protected void checkStorage() { } @Override protected void checkVersion() { } @Override protected void loadStorage() { } } private static class RecordingNodeStore extends NodeStore { private final AtomicReference<List<String>> currentRecording; public RecordingNodeStore( AtomicReference<List<String>> currentRecording ) { super( null, null, null, null, null, null, null, null ); this.currentRecording = currentRecording; } @Override public void updateRecord(NodeRecord record) { currentRecording.get().add(commandActionToken(record) + " node"); } @Override protected void checkStorage() { } @Override protected void checkVersion() { } @Override protected void loadStorage() { } @Override public NodeRecord getRecord(long id) { NodeRecord record = new NodeRecord(id, false, -1, -1); record.setInUse(true); return record; } } private static class RecordingRelationshipStore extends RelationshipStore { private final AtomicReference<List<String>> currentRecording; public RecordingRelationshipStore( AtomicReference<List<String>> currentRecording ) { super( null, null, null, null, null, null, null ); this.currentRecording = currentRecording; } @Override public void updateRecord(RelationshipRecord record) { currentRecording.get().add(commandActionToken(record) + " relationship"); } @Override protected void checkStorage() { } @Override protected void checkVersion() { } @Override protected void loadStorage() { } } private static class OrderVerifyingCommandVisitor extends NeoCommandVisitor.Adapter { private boolean nodeVisited; private boolean relationshipVisited; private boolean propertyVisited; // Commands should appear in this order private boolean created; private boolean updated; private boolean deleted; @Override public boolean visitNodeCommand( NodeCommand command ) throws IOException { if ( !nodeVisited ) { created = false; updated = false; deleted = false; } nodeVisited = true; assertFalse( relationshipVisited ); assertFalse( propertyVisited ); switch( command.getMode() ) { case CREATE: created = true; assertFalse( updated ); assertFalse( deleted ); break; case UPDATE: updated = true; assertFalse( deleted ); break; case DELETE: deleted = true; break; } return true; } } }
package net.mostlyoriginal.api.event.dispatcher; import com.artemis.utils.reflect.ClassReflection; import com.artemis.utils.reflect.Method; import net.mostlyoriginal.api.event.common.Event; import net.mostlyoriginal.api.event.common.EventDispatchStrategy; import net.mostlyoriginal.api.event.common.EventListener; import net.mostlyoriginal.api.event.dispatcher.BasicEventDispatcher; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public abstract class AbstractEventDispatcherTest { public EventDispatchStrategy dispatcher; @Before public void setUp() throws Exception { dispatcher = createDispatcherInstance(); } protected abstract EventDispatchStrategy createDispatcherInstance(); public static class BaseEvent implements Event {} public static class ExtendedEvent extends BaseEvent {} public static class MismatchedEvent implements Event {} public static class SingleListenPojo { public int calls=0; public void l(BaseEvent event) { calls++; } } /** Setup a listener pojo, registering all methods as listeners. */ private <T> T setupListenerPojo( Class<T> pojoClass ) { try { final T pojo = pojoClass.newInstance(); for (Method method : ClassReflection.getMethods(pojoClass)) { // do not register superclass methods. if ( !method.getDeclaringClass().equals(pojoClass) ) continue; dispatcher.register(new EventListener(pojo, method)); } return pojo; } catch ( Exception e ) { throw new RuntimeException("Could not setup listener pojo",e); } } @Test public void Dispatch_EventWithExactClassListener_ListenerReceivesEvent() { final SingleListenPojo pojo = setupListenerPojo(SingleListenPojo.class); // match on exact listener class. dispatcher.dispatch(new BaseEvent()); assertEquals(1, pojo.calls); } @Test public void Dispatch_EventWithSuperclassListener_ListenerReceivesEvent() { final SingleListenPojo pojo = setupListenerPojo(SingleListenPojo.class); dispatcher.dispatch(new ExtendedEvent()); assertEquals(1, pojo.calls); } @Test public void Dispatch_LateRegisteredListener_NoRegistrationIssues() { // Make sure registering a listener late doesn't break the dispatchers. final SingleListenPojo pojo = setupListenerPojo(SingleListenPojo.class); dispatcher.dispatch(new ExtendedEvent()); final SingleListenPojo pojo2 = setupListenerPojo(SingleListenPojo.class); dispatcher.dispatch(new ExtendedEvent()); assertEquals(2, pojo.calls); assertEquals(1, pojo2.calls); } @Test public void Dispatch_MismatchingEvents_ListenerDoesNotReceiveEvent() { final SingleListenPojo pojo = setupListenerPojo(SingleListenPojo.class); // mismatched event has no listeners. dispatcher.dispatch(new MismatchedEvent()); assertEquals(0, pojo.calls); } public static class MultiListenPojo { public int calls1=0; public int calls2=0; public int calls3=0; public void l(BaseEvent event) { calls1++; } public void l2(BaseEvent event) { calls2++; } public void l3(ExtendedEvent event) { calls3++; } } @Test public void Dispatch_SeveralMatchingListeners_AllListenersCalled() { final MultiListenPojo pojo = setupListenerPojo(MultiListenPojo.class); dispatcher.dispatch(new ExtendedEvent()); // all listeners should be hit, even superclass ones. assertEquals(1, pojo.calls1); assertEquals(1, pojo.calls2); assertEquals(1, pojo.calls3); } }
package nu.validator.datatype; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.relaxng.datatype.DatatypeException; /** * Superclass for various datetime datatypes. * * @version $Id$ * @author hsivonen */ abstract class AbstractDatetime extends AbstractDatatype { /** * Days in monts on non-leap years. */ private static int[] DAYS_IN_MONTHS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; /** * Constructor. */ AbstractDatetime() { super(); } private final static boolean WARN = System.getProperty("nu.validator.datatype.warn", "").equals("true"); private void checkMonth(String year, String month) throws DatatypeException { try { checkMonth(Integer.parseInt(year), Integer.parseInt(month)); } catch (NumberFormatException e) { throw newDatatypeException("Year or month out of range."); } } private void checkYear(int year) throws DatatypeException { if (year < 1) { throw newDatatypeException("Year cannot be less than 1."); } else if (WARN && (year < 1000 || year >= 3000)) { throw newDatatypeException("Year may be mistyped.", WARN); } } private void checkMonth(int year, int month) throws DatatypeException { if (month < 1) { throw newDatatypeException("Month cannot be less than 1."); } if (month > 12) { throw newDatatypeException("Month cannot be greater than 12."); } checkYear(year); } private void checkDate(String year, String month, String day) throws DatatypeException { try { checkDate(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)); } catch (NumberFormatException e) { throw newDatatypeException("Year, month, or day out of range."); } } private void checkDate(int year, int month, int day) throws DatatypeException { if (month < 1) { throw newDatatypeException("Month cannot be less than 1."); } if (month > 12) { throw newDatatypeException("Month cannot be greater than 12."); } if (day < 1) { throw newDatatypeException("Day cannot be less than 1."); } if (day > DAYS_IN_MONTHS[month - 1]) { if (!(day == 29 && month == 2 && isLeapYear(year))) { throw newDatatypeException("Day out of range."); } } checkYear(year); } private boolean isLeapYear(int year) { return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)); } private void checkYearlessDate(String month, String day) throws DatatypeException { try { checkYearlessDate(Integer.parseInt(month), Integer.parseInt(day)); } catch (NumberFormatException e) { throw newDatatypeException("Month or day out of range."); } } private void checkYearlessDate(int month, int day) throws DatatypeException { if (month < 1) { throw newDatatypeException("Month cannot be less than 1."); } if (month > 12) { throw newDatatypeException("Month cannot be greater than 12."); } if (day < 1) { throw newDatatypeException("Day cannot be less than 1."); } } private void checkWeek(String year, String week) throws DatatypeException { try { checkWeek(Integer.parseInt(year), Integer.parseInt(week)); } catch (NumberFormatException e) { throw newDatatypeException("Year or week out of range."); } } private void checkWeek(int year, int week) throws DatatypeException { if (week< 1) { throw newDatatypeException("Week cannot be less than 1."); } if (week > 53) { throw newDatatypeException("Week cannot be greater than 53."); } checkYear(year); } protected final void checkHour(String hour) throws DatatypeException { try { checkHour(Integer.parseInt(hour)); } catch (NumberFormatException e) { throw newDatatypeException("Hour out of range."); } } private void checkHour(int hour) throws DatatypeException { if (hour > 23) { throw newDatatypeException("Hour cannot be greater than 23."); } } protected final void checkMinute(String minute) throws DatatypeException { try { checkMinute(Integer.parseInt(minute)); } catch (NumberFormatException e) { throw newDatatypeException("Minute out of range."); } } private void checkMinute(int minute) throws DatatypeException { if (minute > 59) { throw newDatatypeException("Minute cannot be greater than 59."); } } protected final void checkSecond(String second) throws DatatypeException { try { checkSecond(Integer.parseInt(second)); } catch (NumberFormatException e) { throw newDatatypeException("Seconds out of range."); } } private void checkSecond(int second) throws DatatypeException { if (second > 59) { throw newDatatypeException("Second cannot be greater than 59."); } } protected final void checkMilliSecond(String millisecond) throws DatatypeException { if (millisecond.length() > 3) { throw newDatatypeException("A fraction of a second must be one, two, or three digits."); } } private void checkTzd(String hours, String minutes) throws DatatypeException { if (hours.charAt(0) == '+') { hours = hours.substring(1); } try { checkTzd(Integer.parseInt(hours), Integer.parseInt(minutes)); } catch (NumberFormatException e) { throw newDatatypeException("Hours or minutes out of range."); } } private void checkTzd(int hours, int minutes) throws DatatypeException { if (hours < -23 || hours > 23) { throw newDatatypeException("Hours out of range in time zone designator."); } if (minutes > 59) { throw newDatatypeException("Minutes out of range in time zone designator."); } if (WARN) { if (hours < -12 || hours > 14) { throw newDatatypeException( "Hours in time zone designator should be from \u201C-12:00\u201d to \u201d+14:00\u201d", WARN); } if (minutes != 00 && minutes != 30 && minutes != 45) { throw newDatatypeException( "Minutes in time zone designator should be either \u201c00\u201d, \u201c30\u201d, or \u201c45\u201d.", WARN); } } } protected abstract Pattern getPattern(); @Override public void checkValid(CharSequence literal) throws DatatypeException { String year; String month; String day; String hour; String minute; String seconds; String milliseconds; String tzdHours; String tzdMinutes; Matcher m = getPattern().matcher(literal); if (m.matches()) { // valid month string year = m.group(1); month = m.group(2); if (year != null) { checkMonth(year, month); return; } // valid date string year = m.group(3); month = m.group(4); day = m.group(5); if (year != null) { checkDate(year, month, day); return; } // valid yearless date string month = m.group(6); day = m.group(7); if (month != null) { checkYearlessDate(month, day); return; } // valid time string hour = m.group(8); minute = m.group(9); seconds = m.group(10); milliseconds = m.group(11); if (hour != null) { checkHour(hour); checkMinute(minute); if (seconds != null) { checkSecond(seconds); } if (milliseconds != null) { checkMilliSecond(milliseconds); } return; } // valid local date and time string year = m.group(12); month = m.group(13); day = m.group(14); hour = m.group(15); minute = m.group(16); seconds = m.group(17); milliseconds = m.group(18); if (year != null) { checkDate(year, month, day); checkHour(hour); checkMinute(minute); if (seconds != null) { checkSecond(seconds); } if (milliseconds != null) { checkMilliSecond(milliseconds); } return; } // valid time-zone offset string tzdHours = m.group(19); tzdMinutes = m.group(20); if (tzdHours != null) { checkTzd(tzdHours, tzdMinutes); return; } // valid global date and time string year = m.group(21); month = m.group(22); day = m.group(23); hour = m.group(24); minute = m.group(25); seconds = m.group(26); milliseconds = m.group(27); tzdHours = m.group(28); tzdMinutes = m.group(29); if (year != null) { checkDate(year, month, day); checkHour(hour); checkMinute(minute); if (seconds != null) { checkSecond(seconds); } if (milliseconds != null) { checkMilliSecond(milliseconds); } if (tzdHours != null) { checkTzd(tzdHours, tzdMinutes); } return; } // valid week string year = m.group(30); String week = m.group(31); if (year != null) { checkWeek(year, week); } // valid year (valid non-negative integer) year = m.group(32); if (year != null) { try { checkYear(Integer.parseInt(year)); } catch (NumberFormatException e) { throw newDatatypeException("Year out of range."); } } // valid duration string milliseconds = m.group(33); if (milliseconds != null) { checkMilliSecond(milliseconds); return; } milliseconds = m.group(34); if (milliseconds != null) { checkMilliSecond(milliseconds); return; } } else { throw newDatatypeException( "The literal did not satisfy the " + getName() + " format."); } } }
package org.mousephenotype.cda.solr.service.embryoviewer; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.solr.client.solrj.SolrServerException; import org.mousephenotype.cda.solr.service.GeneService; import org.mousephenotype.cda.solr.service.HeatmapData; import org.mousephenotype.cda.solr.service.dto.GeneDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.xml.bind.JAXBException; import java.io.IOException; import java.net.URL; import java.util.*; import java.util.stream.Collectors; @Component public class EmbryoViewerService { private static int NO_DATA=0; private static int IMAGES_AVAILABLE=2; private static int IMAGES_AND_AUTOMATED_ANAYLISIS_AVAILABLE=4; private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String EMBRYO_VIEWER_URL = "https: private static final String PROCEDURE_URL = "https://api.mousephenotype.org/impress/procedure/%s"; private static final ObjectMapper mapper = new ObjectMapper(); private final GeneService geneService; public EmbryoViewerService(GeneService geneService) { this.geneService = geneService; } public List<GeneEntry> getGenesEmbryoStatus() { Map<Integer, Procedure> procedures = new HashMap<>(); List<GeneEntry> genes = new ArrayList<>(); try { Embryo embryo = getEmbryos(); for (Colony colony : embryo.colonies) { GeneEntry gene = new GeneEntry(); gene.mgiAccessionId = colony.mgi; for (ProceduresParameter proceduresParameter : colony.proceduresParameters) { try { Integer procedureId = Integer.parseInt(proceduresParameter.procedureId); if (!procedures.containsKey(procedureId)) { procedures.put(procedureId, getProcedure(procedureId)); } Procedure p = procedures.get(procedureId); switch (p.name) { case "OPT E9.5": gene.opt9_5 = true; break; case "MicroCT E14.5-E15.5": gene.microct14_5_15_5 = true; break; case "MicroCT E18.5": gene.microct18_5 = true; break; default: logger.info("Embryo REST service returned unmapped procedure {}", p.name); break; } } catch (JAXBException | IOException e) { logger.warn("Could not retreive entry for procedure ID {}", proceduresParameter.procedureId, e); } } //add analysis information here for the heat map if(colony.hasAutomatedAnalysis){ gene.hasAutomatedAnalysis=true; gene.analysisDownloadUrl=colony.analysisDownloadUrl; gene.analysisViewUrl=colony.analysisViewUrl; } genes.add(gene); } } catch (IOException e) { logger.warn("Could not retrieve embryo entries", e); } // Decorate the records with gene symbol List<String> mgiIds = genes.stream().map(x -> x.mgiAccessionId).collect(Collectors.toList()); try { final Map<String, String> genesByMgiIds = geneService .getGenesByMgiIds(mgiIds, GeneDTO.MGI_ACCESSION_ID, GeneDTO.MARKER_SYMBOL) .stream() .collect(Collectors.toMap(GeneDTO::getMgiAccessionId, GeneDTO::getMarkerSymbol)); for (GeneEntry entry : genes) { entry.symbol = genesByMgiIds.get(entry.mgiAccessionId); } } catch (SolrServerException | IOException e) { logger.warn("Error occurred getting gene information"); } return genes; } Embryo getEmbryos() throws IOException { URL url = new URL(EMBRYO_VIEWER_URL); return mapper.readValue(url, Embryo.class); } Procedure getProcedure(Integer id) throws JAXBException, IOException { URL url = new URL(String.format(PROCEDURE_URL, id)); return mapper.readValue(url, Procedure.class); } public HeatmapData getEmbryoHeatmap(){ List<EmbryoViewerService.GeneEntry> genes = this.getGenesEmbryoStatus(); List<String> columnList=new ArrayList<>(); columnList.add("E9.5"); columnList.add("E14.5/E15.5"); columnList.add("E18.5"); //UMASS data column and hacks for Washington meeting columnList.add("UMASS"); //add rows for UMASS - hack here as code not very open for extension Map<String,String> umassSymbolAccessions=this.populateUmassData(); List<String> geneList=new ArrayList<>(); List<String> mgiAccessionsList=new ArrayList<>(); List<List<Integer>> rows=new ArrayList<>(); Map<String,EmbryoViewerService.GeneEntry>geneSymbolToEntryMap=new HashMap<>(); for(EmbryoViewerService.GeneEntry gene: genes){ geneList.add(gene.symbol); geneSymbolToEntryMap.put(gene.symbol, gene); } geneList.addAll(umassSymbolAccessions.keySet());//add all the genes from UMass to this set int numberOfImpcColumns=3; for(String geneSymbol: geneList){ ArrayList<Integer> row = new ArrayList<>(); String mgiAccessionId=""; if(geneSymbolToEntryMap.containsKey(geneSymbol)) { GeneEntry gene=geneSymbolToEntryMap.get(geneSymbol); mgiAccessionId=gene.mgiAccessionId; int typeOfData = IMAGES_AVAILABLE;//if stage is mentioned in rest service means we at least have images if (gene.opt9_5) { row.add(IMAGES_AVAILABLE); } else { row.add(NO_DATA); } if (gene.microct14_5_15_5) { if (gene.hasAutomatedAnalysis) { typeOfData = IMAGES_AND_AUTOMATED_ANAYLISIS_AVAILABLE;//used to show has automated analysis but only automated analysis for E15 data currently and need more info in rest from dcc if otherwise } row.add(typeOfData); } else { row.add(NO_DATA); } if (gene.microct18_5) { row.add(IMAGES_AVAILABLE); } else { row.add(NO_DATA); } }else{ //add dummy columns for impc data if non for this gene for(int i=0; i<numberOfImpcColumns;i++){ row.add(NO_DATA); } } if(umassSymbolAccessions.containsKey(geneSymbol)){ row.add(IMAGES_AVAILABLE); }else{ row.add(NO_DATA); } if(mgiAccessionId.equals("")){//if emtpy assume we need to get it from UMASS data map mgiAccessionId=umassSymbolAccessions.get(geneSymbol); } mgiAccessionsList.add(mgiAccessionId); rows.add(row); } HeatmapData heatmapData=new HeatmapData(columnList,geneList,rows); heatmapData.setMgiAccessions(mgiAccessionsList); return heatmapData; } public class GeneEntry { @JsonProperty("symbol") String symbol; @JsonProperty("mgiAccessionId") String mgiAccessionId; @JsonProperty("opt9_5") Boolean opt9_5 = false; @JsonProperty("microct14_5_15_5") Boolean microct14_5_15_5 = false; @JsonProperty("microct18_5") Boolean microct18_5 = false; @JsonProperty("has_automated_analysis") Boolean hasAutomatedAnalysis = false; @JsonProperty("analysis_download_url") String analysisDownloadUrl; @JsonProperty("analysis_view_url") String analysisViewUrl; } private Map<String, String> populateUmassData(){ List<String> originalUmassGeneSymbols = Arrays.asList("4933427D14Rik","Actr8","Alg14","Ap2s1","Atp2b1","B4gat1","Bc052040","Bcs1l","Borcs6","Casc3","Ccdc59","Cenpo","Clpx","Dbr1","Dctn6","Ddx59","Dnaaf2","Dolk","Elof1","Exoc2","Fastkd6","Glrx3","Hlcs","Ipo11","Isca1","mars2","Mcrs1","med20","Mepce","Mrm3","Mrpl22","Mrpl3","Mrpl44","Mrps18c","Mrps22","Mrps25","mtpap","Nars2","Ndufa9","Ndufs8","Orc6","Pmpcb","Pold2","Polr1a","Polr1d","Ppp1r35","Prim1","Prpf4b","Rab11a","Ranbp2","Rbbp4","Riok1","Rpain","Sars","Sdhaf2","Ska2","Snapc2","Sptssa","Strn3","Timm22","tmx2","Tpk1","Trit1","Tubgcp4","Ube2m","Washc4","Ylpm1","Zc3h4","Zfp407","Zwint"); System.out.println("calling decorate Gene info"); Map<String, String> symbolAndAccession = this.getLatestGeneSymbolAndAccession(originalUmassGeneSymbols); System.out.println("symbolAndAccession size="+symbolAndAccession.size()); return symbolAndAccession; } public Map<String, String> getLatestGeneSymbolAndAccession(List<String> geneSymbols){ Map<String, String> genesByMgiIdsUmass=null; try { genesByMgiIdsUmass = geneService .getGeneByGeneSymbolsOrGeneSynonyms(geneSymbols) .stream() .collect(Collectors.toMap(GeneDTO::getMarkerSymbol,GeneDTO::getMgiAccessionId)); System.out.println(genesByMgiIdsUmass); // for (EmbryoViewerService.GeneEntry entry : genes) { // entry.symbol = genesByMgiIds.get(entry.mgiAccessionId); } catch (SolrServerException | IOException e) { System.out.print(e); } return genesByMgiIdsUmass; } }
package com.sometrik.framework; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.sometrik.framework.FWList.ColumnType; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class FWAdapter2 extends ArrayAdapter<View> { enum AdapterDataType { SHEET, DATA } private List<View> viewList; private HashMap<Integer, AdapterData> dataList; // private AdapterData columnData; private FrameWork frame; private LinearLayout.LayoutParams defaultListParams; private LinearLayout.LayoutParams numericListParams; private LinearLayout.LayoutParams iconListParams; private LinearLayout.LayoutParams timestampListParams; private boolean sheetsEnabled = false; private HashMap<Integer, ColumnType> columnTypes; public FWAdapter2(FrameWork frame, List<View> viewList) { super(frame, 0, viewList); this.frame = frame; dataList = new HashMap<Integer, AdapterData>(); columnTypes = new HashMap<Integer, ColumnType>(); defaultListParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, FWList.defaultColumnWeight); numericListParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, FWList.numericColumnWeight); iconListParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, FWList.iconColumnWeight); timestampListParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, FWList.timestampColumnWeight); defaultListParams.leftMargin = 20; numericListParams.leftMargin = 20; iconListParams.leftMargin = 20; timestampListParams.leftMargin = 20; } public ArrayList<String> getDataRow(int row, int sheet) { // if (sheetData == null || sheetData.type == AdapterDataType.DATA) { AdapterData data = dataList.get(row); if (data == null) { Log.d("adapter", "no row found"); return null; } else { Log.d("adapter", "row found"); return data.stringList; } } public void addItem(int row, int sheet, ArrayList<String> cellItems) { Log.d("adapter", "adding new dataList to row: " + row + " sheet: " + sheet); AdapterData data = new AdapterData(cellItems); dataList.put(row, data); } public void reshape(int sheet, int size) { if (size == dataList.size()){ return; } if (size < dataList.size()) { // Currently removes rows from the end ArrayList<Integer> keyList = new ArrayList<Integer>(); for (Entry<Integer, AdapterData> entry : dataList.entrySet()) { keyList.add(entry.getKey()); } for (int i = 0; i < size; i++) { int key = keyList.get(keyList.size() - 1); dataList.remove(key); } } else { int difference = size - dataList.size(); System.out.println("adding " + difference + " new rows"); for (int i = 0; i < difference; i++) { ArrayList<String> newSheet = new ArrayList<String>(); dataList.put(dataList.size(), new AdapterData(newSheet, AdapterDataType.SHEET)); } } notifyDataSetChanged(); } @Override public int getCount() { return dataList.size(); } @Override public long getItemId(int arg0) { return 0; } @Override public void clear() { Log.d("adapter", "clear"); Iterator<Entry<Integer, AdapterData>> iterator = dataList.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, AdapterData> entry = iterator.next(); if (entry.getValue().type == AdapterDataType.DATA) { iterator.remove(); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { System.out.println("adapter position: " + position); if (convertView == null) { System.out.println("Data already set"); AdapterData data = dataList.get(position); if (data == null) { Log.d("adapter", "no data on position " + position); LinearLayout layout = new LinearLayout(frame); convertView = layout; return convertView; } LinearLayout layout = new LinearLayout(frame); layout.setOrientation(LinearLayout.HORIZONTAL); layout.setPadding(0, 20, 0, 20); ViewHolder holder = new ViewHolder(data, layout); convertView = holder.rowLayout; convertView.setTag(holder); } else { AdapterData data = dataList.get(position); if (data == null) { Log.d("adapter", "no data on position " + position); return convertView; } ViewHolder holder = (ViewHolder) convertView.getTag(); holder.update(data); } return convertView; } @Override public boolean isEnabled(int position) { return true; } public class AdapterData { private ArrayList<String> stringList; private boolean columnData = false; private AdapterDataType type = AdapterDataType.DATA; public AdapterData(ArrayList<String> stringList) { this.stringList = stringList; } public AdapterData(ArrayList<String> stringList, AdapterDataType type) { this.type = type; this.stringList = stringList; } public void addString(String text) { stringList.add(text); } public int getSize() { return stringList.size(); } public String getData(int position) { if (position < stringList.size()) { return stringList.get(position); } else { return stringList.get(0); } } public ArrayList<String> getList() { return stringList; } } public void setColumnType(ColumnType type, int column){ columnTypes.put(column, type); } public LinearLayout.LayoutParams getColumnParameters(int column) { // Check column specs ColumnType type = columnTypes.get(column); if (type != null) { switch (type) { case TEXT: return defaultListParams; case NUMERIC: return numericListParams; case TIMESTAMP: return timestampListParams; case ICON: return iconListParams; default: return defaultListParams; } } else { return defaultListParams; } } public class ViewHolder { AdapterData data; LinearLayout rowLayout; ArrayList<TextView> viewList; int row; public ViewHolder(AdapterData data, LinearLayout rowLayout){ this.data = data; viewList = new ArrayList<TextView>(); this.rowLayout = rowLayout; for (int i = 0; i < data.getSize(); i++){ TextView textView = new TextView(frame); textView.setFocusable(false); textView.setFocusableInTouchMode(false); textView.setClickable(false); textView.setTextSize(9); textView.setSingleLine(); textView.setLayoutParams(getColumnParameters(i)); textView.setText(data.getData(i)); viewList.add(textView); rowLayout.addView(textView); } } public void update(AdapterData data){ for (int i = viewList.size(); i < data.getSize(); i++){ TextView textView = new TextView(frame); textView.setFocusable(false); textView.setFocusableInTouchMode(false); textView.setClickable(false); textView.setTextSize(9); textView.setLayoutParams(getColumnParameters(i)); textView.setText(data.getData(i)); textView.setSingleLine(); viewList.add(textView); rowLayout.addView(textView); } for (int i = 0; i < viewList.size(); i++){ TextView view = viewList.get(i); view.setText(data.getData(i)); } } } }
package omnikryptec.util.profiler; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import omnikryptec.swing.ChartData; import omnikryptec.swing.PieChartGenerator; /** * LiveProfiler * @author Panzer1119 */ public class LiveProfiler { private BufferedImage image = null; private final JFrame frame = new JFrame("LiveProfiler"); private final JPanel panel_image = new JPanel() { @Override protected void paintComponent(Graphics g) { g.drawImage(image, 0, 0, null); } }; private final ChartData[] chartDatas = new ChartData[] { new ChartData(Profiler.DISPLAY_IDLE_TIME, 0), new ChartData(Profiler.DISPLAY_UPDATE_TIME, 0), new ChartData(Profiler.SCENE_TIME, 0), new ChartData(Profiler.PARTICLE_RENDERER, 0), new ChartData(Profiler.PARTICLE_UPDATER, 0), new ChartData(Profiler.POSTPROCESSOR, 0), new ChartData(Profiler.OTHER_TIME, 0)}; private final HashMap<ChartData, LinkedList<Double>> data = new HashMap<>(); private float[] sqrts = null; private Timer timer = null; private int lastSeconds = 30; final Dimension size; private int maxValuesSize = 0; public LiveProfiler(int width, int height) { this.size = new Dimension(width, height); frame.setLayout(new BorderLayout()); frame.setSize(size); frame.setPreferredSize(size); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel_image, BorderLayout.CENTER); frame.setLocationRelativeTo(null); frame.setVisible(true); init(); } public final LiveProfiler startTimer() { return startTimer(250); } public final LiveProfiler startTimer(int delay) { if(timer == null) { timer = new Timer(delay, (e) -> new Thread(() -> updateData()).start()); } maxValuesSize = (timer != null ? ((lastSeconds * 1000) / timer.getInitialDelay()) : 0); sqrts = new float[maxValuesSize]; for(int i = 1; i <= maxValuesSize; i++) { sqrts[i - 1] = (float) Math.sqrt(i * 1.0); } timer.start(); return this; } public final LiveProfiler stopTimer() { if(timer != null) { timer.stop(); timer = null; } return this; } private final LiveProfiler init() { for(ChartData chartData : chartDatas) { chartData.setColor(PieChartGenerator.generateRandomColor()); data.put(chartData, new LinkedList<>()); } return this; } private final LiveProfiler updateData() { frame.setTitle(String.format("LiveProfiler - %s: %f ms", Profiler.OVERALL_FRAME_TIME, (Profiler.currentTimeByName(Profiler.OVERALL_FRAME_TIME)))); for (ChartData chartData : data.keySet()) { final LinkedList<Double> values = data.get(chartData); final double addValue = Math.max(Profiler.currentTimeByName(chartData.getName()), 0.0F); values.addFirst(addValue); while(values.size() > maxValuesSize) { values.removeLast(); } float completeValue = 0.0F; final Iterator<Double> floats = values.iterator(); int i = 0; while(floats.hasNext()) { completeValue += (floats.next() / sqrts[i]); i++; } chartData.setValue(Math.max((completeValue / values.size()), 0.0F)); } return updateImage(); } private final LiveProfiler updateImage() { image = PieChartGenerator.createPieChart(chartDatas, size.width, size.height, 0.9F, 0.275F, true, "%s %.2f ms"); panel_image.revalidate(); panel_image.repaint(); return this; } public final int getLastSeconds() { return lastSeconds; } public final LiveProfiler setLastSeconds(int lastSeconds) { this.lastSeconds = lastSeconds; return this; } public static final void main(String[] args) { final LiveProfiler liveProfiler = new LiveProfiler(1000, 1000); } }
package net.metadata.dataspace.atom.adapter; import net.metadata.dataspace.app.Constants; import net.metadata.dataspace.app.DataRegistryApplication; import net.metadata.dataspace.data.access.CollectionDao; import net.metadata.dataspace.data.access.PartyDao; import net.metadata.dataspace.model.Collection; import net.metadata.dataspace.model.Party; import net.metadata.dataspace.util.CollectionAdapterHelper; import org.apache.abdera.Abdera; import org.apache.abdera.ext.json.JSONWriter; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Content; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Person; import org.apache.abdera.parser.stax.util.PrettyWriter; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextException; import org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.activation.MimeType; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class CollectionCollectionAdapter extends AbstractEntityCollectionAdapter<Collection> { private Logger logger = Logger.getLogger(getClass()); private CollectionDao collectionDao = DataRegistryApplication.getApplicationContext().getCollectionDao(); private PartyDao partyDao = DataRegistryApplication.getApplicationContext().getPartyDao(); private static final String ID_PREFIX = DataRegistryApplication.getApplicationContext().getUriPrefix(); @Override public Collection postEntry(String title, IRI iri, String summary, Date updated, List<Person> authors, Content content, RequestContext requestContext) throws ResponseContextException { Collection collection = new Collection(); collection.setTitle(title); collection.setSummary(summary); collection.setUpdated(updated); collection.setAuthors(getAuthors(authors)); collectionDao.save(collection); return collection; } @Override public Collection postMedia(MimeType mimeType, String slug, InputStream inputStream, RequestContext request) throws ResponseContextException { logger.info("Persisting Collection as Media Entry"); if (mimeType.getBaseType().equals("application/json")) { String jsonString = getJsonString(inputStream); Collection collection = new Collection(); assembleCollectionFromJson(collection, jsonString); collectionDao.save(collection); return collection; } return null; } @Override public String getMediaName(Collection collection) throws ResponseContextException { return collection.getTitle(); } @Override public String getContentType(Collection collection) { return Constants.JSON_MIMETYPE; } @Override public void putEntry(Collection collection, String title, Date updated, List<Person> authors, String summary, Content content, RequestContext requestContext) throws ResponseContextException { collectionDao.update(collection); } @Override public ResponseContext putEntry(RequestContext request) { logger.info("Updating Collection as Media Entry"); if (request.getContentType().getBaseType().equals(Constants.JSON_MIMETYPE)) { InputStream inputStream = null; try { inputStream = request.getInputStream(); } catch (IOException e) { logger.fatal("Cannot create inputstream from request.", e); } String collectionAsJsonString = getJsonString(inputStream); String uriKey = CollectionAdapterHelper.getEntryID(request); Collection collection = collectionDao.getByKey(uriKey); assembleCollectionFromJson(collection, collectionAsJsonString); collectionDao.update(collection); } return getEntry(request); } @Override public void deleteEntry(String key, RequestContext requestContext) throws ResponseContextException { collectionDao.delete(collectionDao.getByKey(key)); } @Override public Collection getEntry(String key, RequestContext requestContext) throws ResponseContextException { return collectionDao.getByKey(key); } @Override public ResponseContext getEntry(RequestContext request) { String uriKey = CollectionAdapterHelper.getEntryID(request); Collection collection = collectionDao.getByKey(uriKey); Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setId(collection.getUriKey()); entry.setTitle(collection.getTitle()); entry.setSummary(collection.getSummary()); entry.setUpdated(collection.getUpdated()); ResponseContext responseContext = ProviderHelper.returnBase(entry, 200, collection.getUpdated()) .setEntityTag(ProviderHelper.calculateEntityTag(entry)); if (request.getAccept().equals(Constants.JSON_MIMETYPE)) { responseContext.setContentType(Constants.JSON_MIMETYPE); responseContext.setWriter(new JSONWriter()); } else { responseContext.setContentType(Constants.ATOM_MIMETYPE); responseContext.setWriter(new PrettyWriter()); } return responseContext; } public List<Person> getAuthors(Collection collection, RequestContext request) throws ResponseContextException { Set<String> authors = collection.getAuthors(); List<Person> personList = new ArrayList<Person>(); for (String author : authors) { Person person = request.getAbdera().getFactory().newAuthor(); person.setName(author); personList.add(person); } return personList; } @Override public Object getContent(Collection collection, RequestContext requestContext) throws ResponseContextException { Content content = requestContext.getAbdera().getFactory().newContent(Content.Type.TEXT); content.setText(collection.getSummary()); return content; } @Override public Iterable<Collection> getEntries(RequestContext requestContext) throws ResponseContextException { return collectionDao.getAll(); } @Override public String getId(Collection collection) throws ResponseContextException { return collection.getUriKey(); } @Override public String getName(Collection collection) throws ResponseContextException { return collection.getUriKey(); } @Override public String getTitle(Collection collection) throws ResponseContextException { return collection.getTitle(); } @Override public Date getUpdated(Collection collection) throws ResponseContextException { return collection.getUpdated(); } @Override public String getAuthor(RequestContext requestContext) throws ResponseContextException { return DataRegistryApplication.getApplicationContext().getUriPrefix(); } @Override public String getId(RequestContext requestContext) { return ID_PREFIX + "collections"; } @Override public String getTitle(RequestContext requestContext) { return "Collections"; } @Override public String[] getAccepts(RequestContext request) { return new String[]{Constants.ATOM_MIMETYPE + ";type=entry", Constants.JSON_MIMETYPE}; } private Set<String> getAuthors(List<Person> persons) { Set<String> authors = new HashSet<String>(); for (Person person : persons) { authors.add(person.getName()); } return authors; } private String getJsonString(InputStream inputStream) { //Parse the input stream to string StringBuilder sb = new StringBuilder(); if (inputStream != null) { String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException ex) { logger.fatal("Could not parse inputstream to a JSON string", ex); } finally { try { inputStream.close(); } catch (IOException ex) { logger.fatal("Could not close inputstream", ex); } } } String jsonString = sb.toString(); return jsonString; } private void assembleCollectionFromJson(Collection collection, String jsonString) { try { JSONObject jsonObj = new JSONObject(jsonString); collection.setTitle(jsonObj.getString("title")); collection.setSummary(jsonObj.getString("summary")); collection.setUpdated(new Date()); collection.setLocation(jsonObj.getString("location")); JSONArray collectors = jsonObj.getJSONArray("collector"); Set<Party> parties = new HashSet<Party>(); for (int i = 0; i < collectors.length(); i++) { parties.add(partyDao.getByKey(collectors.getString(i))); } collection.setCollector(parties); JSONArray authors = jsonObj.getJSONArray("authors"); Set<String> persons = new HashSet<String>(); for (int i = 0; i < authors.length(); i++) { persons.add(authors.getString(i)); } collection.setAuthors(persons); } catch (JSONException ex) { logger.fatal("Could not assemble collection from JSON object", ex); } } }
package org.adligo.models.params.client; /** * Title: * Description: <p>This is a generic and reuseable implementation of the * I_TemplateParams interface. It relies on the TemplateParam * class for storing the name, values and nested I_TemplateParams. * Company: Adligo * @author scott@adligo.com * @version 1.3 */ import java.util.Date; import org.adligo.i.log.client.Log; import org.adligo.i.log.client.LogFactory; import org.adligo.i.util.client.I_Iterator; import org.adligo.i.util.client.I_Map; import org.adligo.i.util.client.MapFactory; import org.adligo.i.util.client.StringUtils; public class Params implements I_MultipleParamsObject { private static final long serialVersionUID = 1L; static final Log log = LogFactory.getLog(Params.class); /** * this version number represents the xml format and should be incremented * only if the format changes */ public static final String CLASS_VERSION = new String("1.5"); private I_Map // String, I_OneOrN paramsMap = MapFactory.create();// holds TemplateParam objects private I_OneOrN m_currentGroup = null; private int counntForThisName = 0; private I_TemplateParams param; // the current param that was selected by // getNextParam(String s) /** Constructors */ public Params() { } /** * This creates a Param object using the parameters and adds it to the * Collection of Param objects. */ public Param addParam(String name, String value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Integer value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Integer value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Short value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Short value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Long value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Long value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Double value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Double value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Float value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Float value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Date value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Date value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Boolean value, I_TemplateParams params) { Param parm = new Param(name,params); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, Boolean value) { Param parm = new Param(name); parm.setValue(value); addParam(parm); return parm; } /** * returns the parameter created * @param name * @return */ public Param addParam(String name) { Param parm = new Param(name); addParam(parm); return parm; } /** * returns the children of the parameter created * @param name * @return */ public Params addParams(String name) { Params toRet = new Params(); Param parm = new Param(name,toRet); addParam(parm); return toRet; } public Params addWhereParams() { return this.addParams(Param.WHERE); } public Param addParam(String name, I_TemplateParams params) { Param parm = new Param(name,params); addParam(parm); return parm; } public Param addParam(String name, String operator, String value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Integer value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Short value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Long value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Double value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Float value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Date value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String operator, Boolean value ) { Param parm = new Param(name,operator, value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, String value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators) { Param parm = new Param(name,operators); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Integer value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Short value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Long value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Double value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Float value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Date value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, String [] operators, Boolean value ) { Param parm = new Param(name,new Operators(operators)); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, String value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators) { Param parm = new Param(name,operators); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Integer value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Short value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Long value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Double value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Float value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Date value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } public Param addParam(String name, I_Operators operators, Boolean value ) { Param parm = new Param(name,operators); parm.setValue(value); addParam(parm); return parm; } /** * Adds a I_TemplateParams to the vector of params */ public void addParam(I_TemplateParams p) { if (p == null) { throw new NullPointerException("Can't contain a null item"); } if (p.getName() == null) { throw new NullPointerException("Can't contain a param " + "with a null name"); } I_OneOrN container = (I_OneOrN) paramsMap.get(p.getName()); if (container == null) { SingleParamContainer toAdd = new SingleParamContainer(); toAdd.setItem(p); paramsMap.put(p.getName(), toAdd); } else if (container.size() == 1) { NParamContainer newGroup = new NParamContainer(); newGroup.addItem(container.get(0)); newGroup.addItem(p); paramsMap.put(p.getName(), newGroup); } else { NParamContainer currentGroup = (NParamContainer) container; currentGroup.addItem(p); } try { ((Param) p).setParent(this); } catch (ClassCastException x) { } } public void removeParam(I_TemplateParams p) { if (p == null) { throw new NullPointerException("Can't contain a null item"); } if (p.getName() == null) { throw new NullPointerException("Can't contain a param " + "with a null name"); } I_OneOrN container = (I_OneOrN) paramsMap.get(p.getName()); if (container.size() == 1) { paramsMap.remove(p.getName()); } else { NParamContainer currentGroup = (NParamContainer) container; currentGroup.removeItem(p); } } /** * Implementation of I_TemplateParams see the interfaces documentation. */ public void First() { m_currentGroup = null; counntForThisName = 0; } /** * Implementation of I_TemplateParams see the interfaces documentation. */ public Object[] getValues() { if (param != null) { return param.getValues(); } return null; } /** * Implementation of I_TemplateParams see the interfaces documentation. */ public I_Operators getOperators() { if (param != null) { return param.getOperators(); } return null; } public String getName() { String r = new String(""); if (param != null) { r = param.getName(); } return r; } /** * Implementation of I_TemplateParams see the interfaces documentation. */ public I_TemplateParams getNestedParams() { if (param != null) { return param.getNestedParams(); } return null; } public I_TemplateParams getCurrentParam() { return param; } public void removeAllParams(String name) { paramsMap.remove(name); } /** * Implementation of I_TemplateParams see the interfaces documentation. */ public boolean getNextParam(String s) { if (s == null) { return false; } if (log.isDebugEnabled()) { log.debug("getNextParamFool =" + s); } I_OneOrN currentGroup = (I_OneOrN) this.paramsMap.get(s); if (currentGroup == null) { if (log.isDebugEnabled()) { log.debug("got null I_OneOrN returning"); } param = null; return false; } if (m_currentGroup != null) { // yes make sure their the same instace if (m_currentGroup == currentGroup) { counntForThisName++; if (log.isDebugEnabled()) { log.debug("got same I_OneOrN count is now " + counntForThisName); } param = m_currentGroup.get(counntForThisName); if (param == null) { return false; } else { return true; } } } m_currentGroup = currentGroup; param = m_currentGroup.get(0); if (param == null) { return false; } else { return true; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Params to String \n"); I_Iterator it = paramsMap.getKeysIterator(); boolean first = true; while (it.hasNext()) { if (!first) { sb.append(","); } sb.append(it.next()); } return sb.toString(); } public String writeXML() { XMLBuilder builder = new XMLBuilder(); writeXML(builder); return builder.getBuffer().toString(); } public String writeXML(XMLBuilder sb) { writeXML(sb, ""); return sb.toString(); } public void writeXML(XMLBuilder sb, String name) { sb.indent(); sb.append(XMLObject.OBJECT_HEADER); sb.append(" "); sb.append(XMLObject.CLASS); sb.append("=\""); sb.append(ClassForNameMap.PARAMS_SHORT_NAME); sb.append("\" "); sb.append(XMLObject.VERSION); sb.append("=\""); sb.append(CLASS_VERSION); sb.append("\" "); sb.append(XMLObject.NAME); sb.append("=\""); if (!StringUtils.isEmpty(name)) { sb.append(name); } else { sb.append(Param.PARAMS); } sb.append("\" >"); sb.lineFeed(); sb.addIndentLevel(); I_Iterator it = paramsMap.getValuesIterator(); while (it.hasNext()) { I_OneOrN items = (I_OneOrN) it.next(); for (int i = 0; i < items.size(); i++) { ((I_XML_Serilizable) items.get(i)).writeXML(sb); if (log.isDebugEnabled()) { log.debug(sb.toString()); } } } sb.removeIndentLevel(); sb.indent(); sb.append(XMLObject.OBJECT_ENDER); sb.lineFeed(); if (log.isDebugEnabled()) { log.debug(sb.toString()); } } public void readXML(String s) { readXML(s, null); } public void readXML(String s, String name) { if (log.isDebugEnabled()) { log.debug("Reading XML in Params\n" + s); } int[] iaVectorTags = Parser.getTagIndexs(s, XMLObject.OBJECT_HEADER, XMLObject.OBJECT_ENDER); // get vector element s = s.substring(iaVectorTags[0], iaVectorTags[1]); int[] iaVectorHeader = Parser.getTagIndexs(s, XMLObject.OBJECT_HEADER, ">"); // get vector header String sVectorHeader = s .substring(iaVectorHeader[0], iaVectorHeader[1]); if (name == null) { name = Parser.getAttributeValue(sVectorHeader, XMLObject.NAME); } int[] iaObject = Parser.getTagIndexs(s, XMLObject.OBJECT_HEADER, ">"); s = s.substring(iaObject[1] + 1, s.length()); // remove object header // name=vParmas iaObject = Parser.getTagIndexs(s, XMLObject.OBJECT_HEADER, XMLObject.OBJECT_ENDER); while (iaObject[1] > 10 && iaObject[0] >= 0) { String sVectorObject = s.substring(iaObject[0], iaObject[1]); if (log.isDebugEnabled()) { log.debug("readXML:\n" + sVectorObject); } this.addParam((I_TemplateParams) XMLObject.readXML(sVectorObject)); s = s.substring(iaObject[1] + 1, s.length()); iaObject = Parser.getTagIndexs(s, XMLObject.OBJECT_HEADER, XMLObject.OBJECT_ENDER); } } public String getClassVersion() { return CLASS_VERSION; } /** * This is a utility method for manipulateing I_TemplateParams object this * method encapsulates the ability to add a param to another param object * with out adding duplicate (named getName()) params * * @return the pAddTo object if not null the p object if pAddTo is null and * p is not null * * @param pAddTo * the param to add the other param to * @param p * the param to add so pAddTo.add(p); * @param bAddDuplicate * if it should add a pram if there is already one with the same * name */ public static I_TemplateParams addParam(I_TemplateParams pAddTo, I_TemplateParams p, boolean bAddDuplicate) { if (pAddTo == null) { return p; } else { pAddTo.First(); // if there isn't a param already if (!pAddTo.getNextParam(p.getName())) { return addParamToParam(pAddTo, p); } else if (bAddDuplicate) { return addParamToParam(pAddTo, p); } else { // didn't add anything so we return the same thing return pAddTo; } } } /** * Adds param p to pAddTo with out looking for dups * * @param pAddTo * @param p * @return pAddTo */ private static I_TemplateParams addParamToParam(I_TemplateParams pAddTo, I_TemplateParams p) { if (pAddTo instanceof I_MultipleParamsObject) { ((I_MultipleParamsObject) pAddTo).addParam(p); return pAddTo; } else { Params params = new Params(); params.addParam(pAddTo); params.addParam(p); return params; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((paramsMap == null) ? 0 : paramsMap.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Params other = (Params) obj; if (paramsMap == null) { if (other.paramsMap != null) return false; } else if (!paramsMap.equals(other.paramsMap)) return false; return true; } @Override public short[] getValueTypes() { return this.param.getValueTypes(); } }
package com.oracle.graal.truffle; import static com.oracle.graal.api.code.CodeUtil.*; import static com.oracle.graal.truffle.TruffleCompilerOptions.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.code.Assumptions.Assumption; import com.oracle.graal.api.code.CallingConvention.Type; import com.oracle.graal.api.meta.*; import com.oracle.graal.api.runtime.*; import com.oracle.graal.compiler.*; import com.oracle.graal.compiler.target.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.internal.*; import com.oracle.graal.hotspot.*; import com.oracle.graal.java.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.phases.*; import com.oracle.graal.phases.PhasePlan.PhasePosition; import com.oracle.graal.phases.tiers.*; import com.oracle.graal.phases.util.*; import com.oracle.graal.printer.*; import com.oracle.graal.truffle.nodes.*; import com.oracle.truffle.api.*; import com.oracle.truffle.api.nodes.*; /** * Implementation of the Truffle compiler using Graal. */ public class TruffleCompilerImpl implements TruffleCompiler { private static final PrintStream OUT = TTY.out().out(); private final Providers providers; private final Suites suites; private final PartialEvaluator partialEvaluator; private final Backend backend; private final ResolvedJavaType[] skippedExceptionTypes; private final HotSpotGraalRuntime runtime; private final TruffleCache truffleCache; private final ThreadPoolExecutor compileQueue; private static final Class[] SKIPPED_EXCEPTION_CLASSES = new Class[]{SlowPathException.class, UnexpectedResultException.class, ArithmeticException.class}; public static final OptimisticOptimizations Optimizations = OptimisticOptimizations.ALL.remove(OptimisticOptimizations.Optimization.UseExceptionProbability, OptimisticOptimizations.Optimization.RemoveNeverExecutedCode, OptimisticOptimizations.Optimization.UseTypeCheckedInlining, OptimisticOptimizations.Optimization.UseTypeCheckHints); public TruffleCompilerImpl() { Replacements truffleReplacements = ((GraalTruffleRuntime) Truffle.getRuntime()).getReplacements(); this.providers = GraalCompiler.getGraalProviders().copyWith(truffleReplacements); this.suites = Graal.getRequiredCapability(SuitesProvider.class).createSuites(); this.backend = Graal.getRequiredCapability(Backend.class); this.runtime = HotSpotGraalRuntime.runtime(); this.skippedExceptionTypes = getSkippedExceptionTypes(providers.getMetaAccess()); // Create compilation queue. compileQueue = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CompilerThread.FACTORY); final GraphBuilderConfiguration config = GraphBuilderConfiguration.getEagerDefault(); config.setSkippedExceptionTypes(skippedExceptionTypes); this.truffleCache = new TruffleCache(providers, config, TruffleCompilerImpl.Optimizations); this.partialEvaluator = new PartialEvaluator(providers, truffleCache); if (Debug.isEnabled()) { DebugEnvironment.initialize(System.out); } } static ResolvedJavaType[] getSkippedExceptionTypes(MetaAccessProvider metaAccess) { ResolvedJavaType[] skippedExceptionTypes = new ResolvedJavaType[SKIPPED_EXCEPTION_CLASSES.length]; for (int i = 0; i < SKIPPED_EXCEPTION_CLASSES.length; i++) { skippedExceptionTypes[i] = metaAccess.lookupJavaType(SKIPPED_EXCEPTION_CLASSES[i]); } return skippedExceptionTypes; } public Future<InstalledCode> compile(final OptimizedCallTarget compilable) { Future<InstalledCode> future = compileQueue.submit(new Callable<InstalledCode>() { @Override public InstalledCode call() throws Exception { Object[] debug = new Object[]{new DebugDumpScope("Truffle: " + compilable)}; return Debug.scope("Truffle", debug, new Callable<InstalledCode>() { @Override public InstalledCode call() throws Exception { return compileMethodImpl(compilable); } }); } }); return future; } public static final DebugTimer PartialEvaluationTime = Debug.timer("PartialEvaluationTime"); public static final DebugTimer CompilationTime = Debug.timer("CompilationTime"); public static final DebugTimer CodeInstallationTime = Debug.timer("CodeInstallation"); private InstalledCode compileMethodImpl(final OptimizedCallTarget compilable) { final StructuredGraph graph; final GraphBuilderConfiguration config = GraphBuilderConfiguration.getDefault(); config.setSkippedExceptionTypes(skippedExceptionTypes); runtime.evictDeoptedGraphs(); long timeCompilationStarted = System.nanoTime(); Assumptions assumptions = new Assumptions(true); try (TimerCloseable a = PartialEvaluationTime.start()) { graph = partialEvaluator.createGraph(compilable, assumptions); } if (Thread.interrupted()) { return null; } long timePartialEvaluationFinished = System.nanoTime(); int nodeCountPartialEval = graph.getNodeCount(); InstalledCode compiledMethod = compileMethodHelper(graph, config, assumptions); long timeCompilationFinished = System.nanoTime(); int nodeCountLowered = graph.getNodeCount(); if (compiledMethod == null) { throw new BailoutException("Could not install method, code cache is full!"); } if (TraceTruffleCompilation.getValue()) { int nodeCountTruffle = NodeUtil.countNodes(compilable.getRootNode()); System.out.println(compiledMethod.getCode()); OUT.printf("[truffle] optimized %-50s %d |Nodes %7d |Time %5.0f(%4.0f+%-4.0f)ms |Nodes %5d/%5d |CodeSize %d\n", compilable.getRootNode(), compilable.hashCode(), nodeCountTruffle, (timeCompilationFinished - timeCompilationStarted) / 1e6, (timePartialEvaluationFinished - timeCompilationStarted) / 1e6, (timeCompilationFinished - timePartialEvaluationFinished) / 1e6, nodeCountPartialEval, nodeCountLowered, compiledMethod.getCode().length); } return compiledMethod; } public InstalledCode compileMethodHelper(final StructuredGraph graph, final GraphBuilderConfiguration config, final Assumptions assumptions) { final PhasePlan plan = createPhasePlan(config); Debug.scope("TruffleFinal", graph, new Runnable() { @Override public void run() { Debug.dump(graph, "After TruffleTier"); } }); final CompilationResult result = Debug.scope("TruffleGraal", new Callable<CompilationResult>() { @Override public CompilationResult call() { try (TimerCloseable a = CompilationTime.start()) { CodeCacheProvider codeCache = providers.getCodeCache(); CallingConvention cc = getCallingConvention(codeCache, Type.JavaCallee, graph.method(), false); return GraalCompiler.compileGraph(graph, cc, graph.method(), providers, backend, codeCache.getTarget(), null, plan, OptimisticOptimizations.ALL, new SpeculationLog(), suites, new CompilationResult()); } } }); List<AssumptionValidAssumption> validAssumptions = new ArrayList<>(); Assumptions newAssumptions = new Assumptions(true); if (assumptions != null) { for (Assumption assumption : assumptions.getAssumptions()) { processAssumption(newAssumptions, assumption, validAssumptions); } } if (result.getAssumptions() != null) { for (Assumption assumption : result.getAssumptions().getAssumptions()) { processAssumption(newAssumptions, assumption, validAssumptions); } } result.setAssumptions(newAssumptions); InstalledCode compiledMethod = Debug.scope("CodeInstall", new Object[]{graph.method()}, new Callable<InstalledCode>() { @Override public InstalledCode call() throws Exception { try (TimerCloseable a = CodeInstallationTime.start()) { InstalledCode installedCode = providers.getCodeCache().addMethod(graph.method(), result); if (installedCode != null) { Debug.dump(new Object[]{result, installedCode}, "After code installation"); } return installedCode; } } }); for (AssumptionValidAssumption a : validAssumptions) { a.getAssumption().registerInstalledCode(compiledMethod); } if (Debug.isLogEnabled()) { Debug.log(providers.getCodeCache().disassemble(result, compiledMethod)); } return compiledMethod; } private PhasePlan createPhasePlan(final GraphBuilderConfiguration config) { final PhasePlan phasePlan = new PhasePlan(); GraphBuilderPhase graphBuilderPhase = new GraphBuilderPhase(providers.getMetaAccess(), providers.getForeignCalls(), config, TruffleCompilerImpl.Optimizations); phasePlan.addPhase(PhasePosition.AFTER_PARSING, graphBuilderPhase); return phasePlan; } public void processAssumption(Assumptions newAssumptions, Assumption assumption, List<AssumptionValidAssumption> manual) { if (assumption != null) { if (assumption instanceof AssumptionValidAssumption) { AssumptionValidAssumption assumptionValidAssumption = (AssumptionValidAssumption) assumption; manual.add(assumptionValidAssumption); } else { newAssumptions.record(assumption); } } } }
package io.debezium.connector.postgresql; import static io.debezium.connector.postgresql.TestHelper.PK_FIELD; import static io.debezium.connector.postgresql.TestHelper.topicName; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertFalse; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.apache.kafka.connect.data.Decimal; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import io.debezium.config.CommonConnectorConfig; import io.debezium.data.Envelope; import io.debezium.data.VariableScaleDecimal; import io.debezium.data.VerifyRecord; import io.debezium.doc.FixFor; import io.debezium.junit.ConditionalFail; import io.debezium.junit.ShouldFailWhen; import io.debezium.relational.TableId; /** * Integration test for the {@link RecordsStreamProducer} class. This also tests indirectly the PG plugin functionality for * different use cases. * * @author Horia Chiorean (hchiorea@redhat.com) */ public class RecordsStreamProducerIT extends AbstractRecordsProducerTest { private RecordsStreamProducer recordsProducer; private TestConsumer consumer; private final Consumer<Throwable> blackHole = t -> {}; @Rule public TestRule conditionalFail = new ConditionalFail(); @Before public void before() throws Exception { TestHelper.dropAllSchemas(); TestHelper.executeDDL("init_postgis.ddl"); String statements = "CREATE SCHEMA IF NOT EXISTS public;" + "DROP TABLE IF EXISTS test_table;" + "CREATE TABLE test_table (pk SERIAL, text TEXT, PRIMARY KEY(pk));" + "CREATE TABLE table_with_interval (id SERIAL PRIMARY KEY, title VARCHAR(512) NOT NULL, time_limit INTERVAL DEFAULT '60 days'::INTERVAL NOT NULL);" + "INSERT INTO test_table(text) VALUES ('insert');"; TestHelper.execute(statements); PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with(PostgresConnectorConfig.INCLUDE_UNKNOWN_DATATYPES, true) .build()); setupRecordsProducer(config); } @After public void after() throws Exception { if (recordsProducer != null) { recordsProducer.stop(); } } @Test public void shouldReceiveChangesForInsertsWithDifferentDataTypes() throws Exception { TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); //numerical types assertInsert(INSERT_NUMERIC_TYPES_STMT, schemasAndValuesForNumericType()); //numerical decimal types consumer.expects(1); assertInsert(INSERT_NUMERIC_DECIMAL_TYPES_STMT_NO_NAN, schemasAndValuesForBigDecimalEncodedNumericTypes()); // string types consumer.expects(1); assertInsert(INSERT_STRING_TYPES_STMT, schemasAndValuesForStringTypes()); // monetary types consumer.expects(1); assertInsert(INSERT_CASH_TYPES_STMT, schemaAndValuesForMoneyTypes()); // bits and bytes consumer.expects(1); assertInsert(INSERT_BIN_TYPES_STMT, schemaAndValuesForBinTypes()); //date and time consumer.expects(1); assertInsert(INSERT_DATE_TIME_TYPES_STMT, schemaAndValuesForDateTimeTypes()); // text consumer.expects(1); assertInsert(INSERT_TEXT_TYPES_STMT, schemasAndValuesForTextTypes()); // geom types consumer.expects(1); assertInsert(INSERT_GEOM_TYPES_STMT, schemaAndValuesForGeomTypes()); // timezone range types consumer.expects(1); assertInsert(INSERT_TSTZRANGE_TYPES_STMT, schemaAndValuesForTstzRangeTypes()); // custom types + null value consumer.expects(1); assertInsert(INSERT_CUSTOM_TYPES_STMT, schemasAndValuesForCustomTypes()); } @Test(timeout = 30000) public void shouldReceiveChangesForInsertsWithPostgisTypes() throws Exception { TestHelper.executeDDL("postgis_create_tables.ddl"); consumer = testConsumer(1, "public"); // spatial_ref_sys produces a tonne of records in the postgis schema consumer.setIgnoreExtraRecords(true); recordsProducer.start(consumer, blackHole); // need to wait for all the spatial_ref_sys to flow through and be ignored. // this exceeds the normal 2s timeout. TestHelper.execute("INSERT INTO public.dummy_table DEFAULT VALUES;"); consumer.await(TestHelper.waitTimeForRecords() * 10, TimeUnit.SECONDS); while (true) { if (!consumer.isEmpty()) { SourceRecord record = consumer.remove(); if (record.topic().endsWith(".public.dummy_table")) { break; } } } // now do it for actual testing // postgis types consumer.expects(1); assertInsert(INSERT_POSTGIS_TYPES_STMT, schemaAndValuesForPostgisTypes()); } @Test(timeout = 30000) public void shouldReceiveChangesForInsertsWithPostgisArrayTypes() throws Exception { TestHelper.executeDDL("postgis_create_tables.ddl"); consumer = testConsumer(1, "public"); // spatial_ref_sys produces a tonne of records in the postgis schema consumer.setIgnoreExtraRecords(true); recordsProducer.start(consumer, blackHole); // need to wait for all the spatial_ref_sys to flow through and be ignored. // this exceeds the normal 2s timeout. TestHelper.execute("INSERT INTO public.dummy_table DEFAULT VALUES;"); consumer.await(TestHelper.waitTimeForRecords() * 10, TimeUnit.SECONDS); while (true) { if (!consumer.isEmpty()) { SourceRecord record = consumer.remove(); if (record.topic().endsWith(".public.dummy_table")) { break; } } } // now do it for actual testing // postgis types consumer.expects(1); assertInsert(INSERT_POSTGIS_ARRAY_TYPES_STMT, schemaAndValuesForPostgisArrayTypes()); } @Test @ShouldFailWhen(DecoderDifferences.AreQuotedIdentifiersUnsupported.class) // TODO DBZ-493 public void shouldReceiveChangesForInsertsWithQuotedNames() throws Exception { TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); // Quoted column name assertInsert(INSERT_QUOTED_TYPES_STMT, schemasAndValuesForQuotedTypes()); } @Test public void shouldReceiveChangesForInsertsWithArrayTypes() throws Exception { TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); assertInsert(INSERT_ARRAY_TYPES_STMT, schemasAndValuesForArrayTypes()); } @Test @FixFor("DBZ-478") public void shouldReceiveChangesForNullInsertsWithArrayTypes() throws Exception { TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); assertInsert(INSERT_ARRAY_TYPES_WITH_NULL_VALUES_STMT, schemasAndValuesForArrayTypesWithNullValues()); } @Test public void shouldReceiveChangesForNewTable() throws Exception { String statement = "CREATE SCHEMA s1;" + "CREATE TABLE s1.a (pk SERIAL, aa integer, PRIMARY KEY(pk));" + "INSERT INTO s1.a (aa) VALUES (11);"; consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait(statement); assertRecordInserted("s1.a", PK_FIELD, 1); } @Test public void shouldReceiveChangesForRenamedTable() throws Exception { String statement = "DROP TABLE IF EXISTS renamed_test_table;" + "ALTER TABLE test_table RENAME TO renamed_test_table;" + "INSERT INTO renamed_test_table (text) VALUES ('new');"; consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait(statement); assertRecordInserted("public.renamed_test_table", PK_FIELD, 2); } @Test public void shouldReceiveChangesForUpdates() throws Exception { consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait("UPDATE test_table set text='update' WHERE pk=1"); // the update record should be the last record SourceRecord updatedRecord = consumer.remove(); String topicName = topicName("public.test_table"); assertEquals(topicName, updatedRecord.topic()); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // default replica identity only fires previous values for PK changes List<SchemaAndValueField> expectedAfter = Collections.singletonList( new SchemaAndValueField("text", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "update")); assertRecordSchemaAndValues(expectedAfter, updatedRecord, Envelope.FieldName.AFTER); // alter the table and set its replica identity to full the issue another update consumer.expects(1); TestHelper.execute("ALTER TABLE test_table REPLICA IDENTITY FULL"); executeAndWait("UPDATE test_table set text='update2' WHERE pk=1"); updatedRecord = consumer.remove(); assertEquals(topicName, updatedRecord.topic()); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // now we should get both old and new values List<SchemaAndValueField> expectedBefore = Collections.singletonList(new SchemaAndValueField("text", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "update")); assertRecordSchemaAndValues(expectedBefore, updatedRecord, Envelope.FieldName.BEFORE); expectedAfter = Collections.singletonList(new SchemaAndValueField("text", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "update2")); assertRecordSchemaAndValues(expectedAfter, updatedRecord, Envelope.FieldName.AFTER); } @Test public void shouldReceiveChangesForUpdatesWithColumnChanges() throws Exception { // add a new column String statements = "ALTER TABLE test_table ADD COLUMN uvc VARCHAR(2);" + "ALTER TABLE test_table REPLICA IDENTITY FULL;" + "UPDATE test_table SET uvc ='aa' WHERE pk = 1;"; consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait(statements); // the update should be the last record SourceRecord updatedRecord = consumer.remove(); String topicName = topicName("public.test_table"); assertEquals(topicName, updatedRecord.topic()); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // now check we got the updated value (the old value should be null, the new one whatever we set) List<SchemaAndValueField> expectedBefore = Collections.singletonList(new SchemaAndValueField("uvc", null, null)); assertRecordSchemaAndValues(expectedBefore, updatedRecord, Envelope.FieldName.BEFORE); List<SchemaAndValueField> expectedAfter = Collections.singletonList(new SchemaAndValueField("uvc", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "aa")); assertRecordSchemaAndValues(expectedAfter, updatedRecord, Envelope.FieldName.AFTER); // rename a column statements = "ALTER TABLE test_table RENAME COLUMN uvc to xvc;" + "UPDATE test_table SET xvc ='bb' WHERE pk = 1;"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // now check we got the updated value (the old value should be null, the new one whatever we set) expectedBefore = Collections.singletonList(new SchemaAndValueField("xvc", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "aa")); assertRecordSchemaAndValues(expectedBefore, updatedRecord, Envelope.FieldName.BEFORE); expectedAfter = Collections.singletonList(new SchemaAndValueField("xvc", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "bb")); assertRecordSchemaAndValues(expectedAfter, updatedRecord, Envelope.FieldName.AFTER); // drop a column statements = "ALTER TABLE test_table DROP COLUMN xvc;" + "UPDATE test_table SET text ='update' WHERE pk = 1;"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // change a column type statements = "ALTER TABLE test_table ADD COLUMN modtype INTEGER;" + "INSERT INTO test_table (pk,modtype) VALUES (2,1);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 2); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("modtype", SchemaBuilder.OPTIONAL_INT32_SCHEMA, 1)), updatedRecord, Envelope.FieldName.AFTER); statements = "ALTER TABLE test_table ALTER COLUMN modtype TYPE SMALLINT;" + "UPDATE test_table SET modtype = 2 WHERE pk = 2;"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 2); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("modtype", SchemaBuilder.OPTIONAL_INT16_SCHEMA, (short)1)), updatedRecord, Envelope.FieldName.BEFORE); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("modtype", SchemaBuilder.OPTIONAL_INT16_SCHEMA, (short)2)), updatedRecord, Envelope.FieldName.AFTER); } @Test public void shouldReceiveChangesForUpdatesWithPKChanges() throws Exception { consumer = testConsumer(3); recordsProducer.start(consumer, blackHole); executeAndWait("UPDATE test_table SET text = 'update', pk = 2"); String topicName = topicName("public.test_table"); // first should be a delete of the old pk SourceRecord deleteRecord = consumer.remove(); assertEquals(topicName, deleteRecord.topic()); VerifyRecord.isValidDelete(deleteRecord, PK_FIELD, 1); // followed by a tombstone of the old pk SourceRecord tombstoneRecord = consumer.remove(); assertEquals(topicName, tombstoneRecord.topic()); VerifyRecord.isValidTombstone(tombstoneRecord, PK_FIELD, 1); // and finally insert of the new value SourceRecord insertRecord = consumer.remove(); assertEquals(topicName, insertRecord.topic()); VerifyRecord.isValidInsert(insertRecord, PK_FIELD, 2); } @Test @FixFor("DBZ-582") public void shouldReceiveChangesForUpdatesWithPKChangesWithoutTombstone() throws Exception { PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with(PostgresConnectorConfig.INCLUDE_UNKNOWN_DATATYPES, true) .with(CommonConnectorConfig.TOMBSTONES_ON_DELETE, false) .build() ); setupRecordsProducer(config); consumer = testConsumer(2); recordsProducer.start(consumer, blackHole); executeAndWait("UPDATE test_table SET text = 'update', pk = 2"); String topicName = topicName("public.test_table"); // first should be a delete of the old pk SourceRecord deleteRecord = consumer.remove(); assertEquals(topicName, deleteRecord.topic()); VerifyRecord.isValidDelete(deleteRecord, PK_FIELD, 1); // followed by insert of the new value SourceRecord insertRecord = consumer.remove(); assertEquals(topicName, insertRecord.topic()); VerifyRecord.isValidInsert(insertRecord, PK_FIELD, 2); } @Test public void shouldReceiveChangesForDefaultValues() throws Exception { String statements = "ALTER TABLE test_table REPLICA IDENTITY FULL;" + "ALTER TABLE test_table ADD COLUMN default_column TEXT DEFAULT 'default';" + "INSERT INTO test_table (text) VALUES ('update');"; consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait(statements); SourceRecord insertRecord = consumer.remove(); assertEquals(topicName("public.test_table"), insertRecord.topic()); VerifyRecord.isValidInsert(insertRecord, PK_FIELD, 2); List<SchemaAndValueField> expectedSchemaAndValues = Arrays.asList( new SchemaAndValueField("text", SchemaBuilder.OPTIONAL_STRING_SCHEMA, "update"), new SchemaAndValueField("default_column", SchemaBuilder.OPTIONAL_STRING_SCHEMA ,"default")); assertRecordSchemaAndValues(expectedSchemaAndValues, insertRecord, Envelope.FieldName.AFTER); } @Test public void shouldReceiveChangesForTypeConstraints() throws Exception { // add a new column String statements = "ALTER TABLE test_table ADD COLUMN num_val NUMERIC(5,2);" + "ALTER TABLE test_table REPLICA IDENTITY FULL;" + "UPDATE test_table SET num_val = 123.45 WHERE pk = 1;"; consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); executeAndWait(statements); // the update should be the last record SourceRecord updatedRecord = consumer.remove(); String topicName = topicName("public.test_table"); assertEquals(topicName, updatedRecord.topic()); VerifyRecord.isValidUpdate(updatedRecord, PK_FIELD, 1); // now check we got the updated value (the old value should be null, the new one whatever we set) List<SchemaAndValueField> expectedBefore = Collections.singletonList(new SchemaAndValueField("num_val", null, null)); assertRecordSchemaAndValues(expectedBefore, updatedRecord, Envelope.FieldName.BEFORE); List<SchemaAndValueField> expectedAfter = Collections.singletonList(new SchemaAndValueField("num_val", Decimal.builder(2).parameter(TestHelper.PRECISION_PARAMETER_KEY, "5").optional().build(), new BigDecimal("123.45"))); assertRecordSchemaAndValues(expectedAfter, updatedRecord, Envelope.FieldName.AFTER); // change a constraint statements = "ALTER TABLE test_table ALTER COLUMN num_val TYPE NUMERIC(6,1);" + "INSERT INTO test_table (pk,num_val) VALUES (2,123.41);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 2); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("num_val", Decimal.builder(1).parameter(TestHelper.PRECISION_PARAMETER_KEY, "6").optional().build(), new BigDecimal("123.4"))), updatedRecord, Envelope.FieldName.AFTER); statements = "ALTER TABLE test_table ALTER COLUMN num_val TYPE NUMERIC;" + "INSERT INTO test_table (pk,num_val) VALUES (3,123.4567);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); final Struct dvs = new Struct(VariableScaleDecimal.schema()); dvs.put("scale", 4).put("value", new BigDecimal("123.4567").unscaledValue().toByteArray()); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 3); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("num_val", VariableScaleDecimal.builder().optional().build(), dvs)), updatedRecord, Envelope.FieldName.AFTER); statements = "ALTER TABLE test_table ALTER COLUMN num_val TYPE DECIMAL(12,4);" + "INSERT INTO test_table (pk,num_val) VALUES (4,2.48);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 4); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("num_val", Decimal.builder(4).parameter(TestHelper.PRECISION_PARAMETER_KEY, "12").optional().build(), new BigDecimal("2.4800"))), updatedRecord, Envelope.FieldName.AFTER); statements = "ALTER TABLE test_table ALTER COLUMN num_val TYPE DECIMAL(12);" + "INSERT INTO test_table (pk,num_val) VALUES (5,1238);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 5); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("num_val", Decimal.builder(0).parameter(TestHelper.PRECISION_PARAMETER_KEY, "12").optional().build(), new BigDecimal("1238"))), updatedRecord, Envelope.FieldName.AFTER); statements = "ALTER TABLE test_table ALTER COLUMN num_val TYPE DECIMAL;" + "INSERT INTO test_table (pk,num_val) VALUES (6,1225.1);"; consumer.expects(1); executeAndWait(statements); updatedRecord = consumer.remove(); final Struct dvs2 = new Struct(VariableScaleDecimal.schema()); dvs2.put("scale", 1).put("value", new BigDecimal("1225.1").unscaledValue().toByteArray()); VerifyRecord.isValidInsert(updatedRecord, PK_FIELD, 6); assertRecordSchemaAndValues( Collections.singletonList(new SchemaAndValueField("num_val", VariableScaleDecimal.builder().optional().build(), dvs2)), updatedRecord, Envelope.FieldName.AFTER); } @Test public void shouldReceiveChangesForDeletes() throws Exception { // add a new entry and remove both String statements = "INSERT INTO test_table (text) VALUES ('insert2');" + "DELETE FROM test_table WHERE pk > 0;"; consumer = testConsumer(5); recordsProducer.start(consumer, blackHole); executeAndWait(statements); String topicPrefix = "public.test_table"; String topicName = topicName(topicPrefix); assertRecordInserted(topicPrefix, PK_FIELD, 2); // first entry removed SourceRecord record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidDelete(record, PK_FIELD, 1); // followed by a tombstone record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidTombstone(record, PK_FIELD, 1); // second entry removed record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidDelete(record, PK_FIELD, 2); // followed by a tombstone record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidTombstone(record, PK_FIELD, 2); } @Test @FixFor("DBZ-582") public void shouldReceiveChangesForDeletesWithoutTombstone() throws Exception { PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with(PostgresConnectorConfig.INCLUDE_UNKNOWN_DATATYPES, true) .with(CommonConnectorConfig.TOMBSTONES_ON_DELETE, false) .build() ); setupRecordsProducer(config); // add a new entry and remove both String statements = "INSERT INTO test_table (text) VALUES ('insert2');" + "DELETE FROM test_table WHERE pk > 0;"; consumer = testConsumer(3); recordsProducer.start(consumer, blackHole); executeAndWait(statements); String topicPrefix = "public.test_table"; String topicName = topicName(topicPrefix); assertRecordInserted(topicPrefix, PK_FIELD, 2); // first entry removed SourceRecord record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidDelete(record, PK_FIELD, 1); // second entry removed record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidDelete(record, PK_FIELD, 2); } @Test public void shouldReceiveNumericTypeAsDouble() throws Exception { PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with(PostgresConnectorConfig.DECIMAL_HANDLING_MODE, PostgresConnectorConfig.DecimalHandlingMode.DOUBLE) .build()); setupRecordsProducer(config); TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); assertInsert(INSERT_NUMERIC_DECIMAL_TYPES_STMT, schemasAndValuesForDoubleEncodedNumericTypes()); } @Test @FixFor("DBZ-611") public void shouldReceiveNumericTypeAsString() throws Exception { PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with(PostgresConnectorConfig.DECIMAL_HANDLING_MODE, PostgresConnectorConfig.DecimalHandlingMode.STRING) .build()); setupRecordsProducer(config); TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); assertInsert(INSERT_NUMERIC_DECIMAL_TYPES_STMT, schemasAndValuesForStringEncodedNumericTypes()); } @Test @FixFor("DBZ-259") public void shouldProcessIntervalDelete() throws Exception { final String statements = "INSERT INTO table_with_interval VALUES (default, 'Foo', default);" + "INSERT INTO table_with_interval VALUES (default, 'Bar', default);" + "DELETE FROM table_with_interval WHERE id = 1;"; consumer = testConsumer(4); recordsProducer.start(consumer, blackHole); executeAndWait(statements); final String topicPrefix = "public.table_with_interval"; final String topicName = topicName(topicPrefix); final String pk = "id"; assertRecordInserted(topicPrefix, pk, 1); assertRecordInserted(topicPrefix, pk, 2); // first entry removed SourceRecord record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidDelete(record, pk, 1); // followed by a tombstone record = consumer.remove(); assertEquals(topicName, record.topic()); VerifyRecord.isValidTombstone(record, pk, 1); } @Test @FixFor("DBZ-501") public void shouldNotStartAfterStop() throws Exception { recordsProducer.stop(); recordsProducer.start(consumer, blackHole); // Need to remove record created in @Before PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig().with(PostgresConnectorConfig.INCLUDE_UNKNOWN_DATATYPES, true).build()); setupRecordsProducer(config); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); } @Test @FixFor("DBZ-644") public void shouldPropagateSourceColumnTypeToSchemaParameter() throws Exception { PostgresConnectorConfig config = new PostgresConnectorConfig(TestHelper.defaultConfig() .with("column.propagate.source.type", ".*vc.*") .build()); setupRecordsProducer(config); TestHelper.executeDDL("postgres_create_tables.ddl"); consumer = testConsumer(1); recordsProducer.start(consumer, blackHole); assertInsert(INSERT_STRING_TYPES_STMT, schemasAndValuesForStringTypesWithSourceColumnTypeInfo()); } private void setupRecordsProducer(PostgresConnectorConfig config) { if (recordsProducer != null) { recordsProducer.stop(); } PostgresTopicSelector selector = PostgresTopicSelector.create(config); PostgresTaskContext context = new PostgresTaskContext( config, new PostgresSchema(config, TestHelper.getTypeRegistry(), selector), selector ); recordsProducer = new RecordsStreamProducer(context, new SourceInfo(config.getLogicalName())); } private void assertInsert(String statement, List<SchemaAndValueField> expectedSchemaAndValuesByColumn) { assertInsert(statement, 1, expectedSchemaAndValuesByColumn); } private void assertInsert(String statement, int pk, List<SchemaAndValueField> expectedSchemaAndValuesByColumn) { TableId table = tableIdFromInsertStmt(statement); String expectedTopicName = table.schema() + "." + table.table(); try { executeAndWait(statement); SourceRecord record = assertRecordInserted(expectedTopicName, PK_FIELD, pk); assertRecordOffset(record, false, false); assertRecordSchemaAndValues(expectedSchemaAndValuesByColumn, record, Envelope.FieldName.AFTER); } catch (Exception e) { throw new RuntimeException(e); } } private SourceRecord assertRecordInserted(String expectedTopicName, String pkColumn, int pk) throws InterruptedException { assertFalse("records not generated", consumer.isEmpty()); SourceRecord insertedRecord = consumer.remove(); assertEquals(topicName(expectedTopicName), insertedRecord.topic()); VerifyRecord.isValidInsert(insertedRecord, pkColumn, pk); return insertedRecord; } private void executeAndWait(String statements) throws Exception { TestHelper.execute(statements); consumer.await(TestHelper.waitTimeForRecords(), TimeUnit.SECONDS); } }
package org.jnosql.artemis.graph; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import javax.enterprise.inject.Alternative; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; import javax.annotation.Priority; @Transactional @Interceptor @Alternative @Priority(Interceptor.Priority.APPLICATION) class TransactionalInterceptor { @Inject private Instance<Graph> graph; @AroundInvoke public Object manageTransaction(InvocationContext context) throws Exception { Transaction transaction = graph.get().tx(); if (!transaction.isOpen()) { transaction.open(); } try { Object proceed = context.proceed(); transaction.commit(); return proceed; } catch (Exception exception) { transaction.rollback(); throw exception; } } }
package org.eclipse.collections.impl.bag.immutable; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.collections.api.bag.Bag; import org.eclipse.collections.api.bag.ImmutableBag; import org.eclipse.collections.api.block.function.Function; import org.eclipse.collections.api.block.function.Function0; import org.eclipse.collections.api.block.function.Function2; import org.eclipse.collections.api.block.predicate.Predicate; import org.eclipse.collections.api.block.predicate.Predicate2; import org.eclipse.collections.api.block.predicate.primitive.IntPredicate; import org.eclipse.collections.api.block.procedure.Procedure; import org.eclipse.collections.api.block.procedure.Procedure2; import org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure; import org.eclipse.collections.api.map.MutableMap; import org.eclipse.collections.api.multimap.MutableMultimap; import org.eclipse.collections.api.multimap.bag.ImmutableBagMultimap; import org.eclipse.collections.api.ordered.OrderedIterable; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.bag.mutable.HashBag; import org.eclipse.collections.impl.block.factory.Comparators; import org.eclipse.collections.impl.block.factory.Predicates; import org.eclipse.collections.impl.block.procedure.MultimapEachPutProcedure; import org.eclipse.collections.impl.factory.Bags; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.map.mutable.UnifiedMap; import org.eclipse.collections.impl.multimap.bag.HashBagMultimap; import org.eclipse.collections.impl.tuple.Tuples; import org.eclipse.collections.impl.utility.ArrayIterate; import org.eclipse.collections.impl.utility.Iterate; /** * @since 1.0 */ final class ImmutableSingletonBag<T> extends AbstractImmutableBag<T> implements Serializable { private static final long serialVersionUID = 1L; private final T value; ImmutableSingletonBag(T object) { this.value = object; } @Override public boolean allSatisfy(Predicate<? super T> predicate) { return predicate.accept(this.value); } @Override public boolean noneSatisfy(Predicate<? super T> predicate) { return !predicate.accept(this.value); } @Override public <IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super T, ? extends IV> function) { return function.value(injectedValue, this.value); } @Override public T min(Comparator<? super T> comparator) { return this.value; } @Override public T max(Comparator<? super T> comparator) { return this.value; } @Override public T min() { return this.value; } @Override public T max() { return this.value; } @Override public <V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function) { return this.value; } @Override public <V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function) { return this.value; } public ImmutableBag<T> newWith(T element) { return Bags.immutable.with(this.value, element); } public ImmutableBag<T> newWithout(T element) { return this.emptyIfMatchesOrThis(Predicates.equal(element)); } private ImmutableBag<T> emptyIfMatchesOrThis(Predicate<Object> predicate) { return predicate.accept(this.value) ? Bags.immutable.<T>empty() : this; } public ImmutableBag<T> newWithAll(Iterable<? extends T> elements) { return HashBag.newBag(elements).with(this.value).toImmutable(); } @Override public ImmutableBag<T> newWithoutAll(Iterable<? extends T> elements) { return this.emptyIfMatchesOrThis(Predicates.in(elements)); } public int size() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean notEmpty() { return true; } public T getFirst() { return this.value; } public T getLast() { return this.value; } @Override public boolean contains(Object object) { return Comparators.nullSafeEquals(this.value, object); } @Override public boolean containsAllIterable(Iterable<?> source) { return Iterate.allSatisfy(source, Predicates.equal(this.value)); } @Override public boolean containsAllArguments(Object... elements) { return ArrayIterate.allSatisfy(elements, Predicates.equal(this.value)); } public ImmutableBag<T> selectByOccurrences(IntPredicate predicate) { return predicate.accept(1) ? this : Bags.immutable.<T>empty(); } public ImmutableBag<T> select(Predicate<? super T> predicate) { return predicate.accept(this.value) ? this : Bags.immutable.<T>empty(); } @Override public <R extends Collection<T>> R select(Predicate<? super T> predicate, R target) { if (predicate.accept(this.value)) { target.add(this.value); } return target; } @Override public <P, R extends Collection<T>> R selectWith( Predicate2<? super T, ? super P> predicate, P parameter, R target) { if (predicate.accept(this.value, parameter)) { target.add(this.value); } return target; } public ImmutableBag<T> reject(Predicate<? super T> predicate) { return predicate.accept(this.value) ? Bags.immutable.<T>empty() : this; } @Override public <R extends Collection<T>> R reject(Predicate<? super T> predicate, R target) { if (!predicate.accept(this.value)) { target.add(this.value); } return target; } @Override public <P, R extends Collection<T>> R rejectWith( Predicate2<? super T, ? super P> predicate, P parameter, R target) { if (!predicate.accept(this.value, parameter)) { target.add(this.value); } return target; } public <S> ImmutableBag<S> selectInstancesOf(Class<S> clazz) { return clazz.isInstance(this.value) ? (ImmutableBag<S>) this : Bags.immutable.<S>empty(); } public <V> ImmutableBag<V> collect(Function<? super T, ? extends V> function) { return Bags.immutable.with(function.valueOf(this.value)); } public <V> ImmutableBag<V> collectIf( Predicate<? super T> predicate, Function<? super T, ? extends V> function) { return predicate.accept(this.value) ? Bags.immutable.with(function.valueOf(this.value)) : Bags.immutable.<V>empty(); } @Override public <V, R extends Collection<V>> R collectIf( Predicate<? super T> predicate, Function<? super T, ? extends V> function, R target) { if (predicate.accept(this.value)) { target.add(function.valueOf(this.value)); } return target; } public <V> ImmutableBag<V> flatCollect(Function<? super T, ? extends Iterable<V>> function) { return this.flatCollect(function, HashBag.<V>newBag()).toImmutable(); } @Override public <V, R extends Collection<V>> R flatCollect( Function<? super T, ? extends Iterable<V>> function, R target) { Iterate.addAllTo(function.valueOf(this.value), target); return target; } @Override public T detect(Predicate<? super T> predicate) { return predicate.accept(this.value) ? this.value : null; } @Override public T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function) { return predicate.accept(this.value) ? this.value : function.value(); } @Override public int count(Predicate<? super T> predicate) { return predicate.accept(this.value) ? 1 : 0; } @Override public boolean anySatisfy(Predicate<? super T> predicate) { return predicate.accept(this.value); } public <V> ImmutableBagMultimap<V, T> groupBy(Function<? super T, ? extends V> function) { return this.groupBy(function, HashBagMultimap.<V, T>newMultimap()).toImmutable(); } @Override public <V, R extends MutableMultimap<V, T>> R groupBy(Function<? super T, ? extends V> function, R target) { target.putAll(function.valueOf(this.value), this); return target; } public <V> ImmutableBagMultimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function) { return this.groupByEach(function, HashBagMultimap.<V, T>newMultimap()).toImmutable(); } @Override public <V, R extends MutableMultimap<V, T>> R groupByEach(Function<? super T, ? extends Iterable<V>> function, R target) { this.forEach(MultimapEachPutProcedure.on(target, function)); return target; } public int sizeDistinct() { return 1; } public int occurrencesOf(Object item) { return Comparators.nullSafeEquals(this.value, item) ? 1 : 0; } public void forEachWithOccurrences(ObjectIntProcedure<? super T> objectIntProcedure) { objectIntProcedure.value(this.value, 1); } public MutableMap<T, Integer> toMapOfItemToCount() { return UnifiedMap.newWithKeysValues(this.value, 1); } @Override public ImmutableBag<T> toImmutable() { return this; } public void each(Procedure<? super T> procedure) { procedure.value(this.value); } @Override public void forEachWithIndex(ObjectIntProcedure<? super T> objectIntProcedure) { objectIntProcedure.value(this.value, 0); } @Override public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter) { procedure.value(this.value, parameter); } /** * @deprecated in 6.0. Use {@link OrderedIterable#zip(Iterable)} instead. */ @Deprecated public <S> ImmutableBag<Pair<T, S>> zip(Iterable<S> that) { Iterator<S> iterator = that.iterator(); if (!iterator.hasNext()) { return Bags.immutable.empty(); } return Bags.immutable.with(Tuples.pair(this.value, iterator.next())); } /** * @deprecated in 6.0. Use {@link OrderedIterable#zipWithIndex()} instead. */ @Deprecated public ImmutableSet<Pair<T, Integer>> zipWithIndex() { return Sets.immutable.with(Tuples.pair(this.value, 0)); } public Iterator<T> iterator() { return new SingletonIterator(); } private class SingletonIterator implements Iterator<T> { private boolean next = true; public boolean hasNext() { return this.next; } public T next() { if (this.next) { this.next = false; return ImmutableSingletonBag.this.value; } throw new NoSuchElementException("i=" + this.next); } public void remove() { throw new UnsupportedOperationException("Cannot remove from an ImmutableBag"); } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Bag)) { return false; } Bag<?> bag = (Bag<?>) obj; if (this.size() != bag.size()) { return false; } return this.occurrencesOf(this.value) == bag.occurrencesOf(this.value); } @Override public String toString() { return '[' + this.makeString() + ']'; } @Override public int hashCode() { return (this.value == null ? 0 : this.value.hashCode()) ^ 1; } private Object writeReplace() { return new ImmutableBagSerializationProxy<T>(this); } }
package org.bouncycastle.asn1.x509; import java.util.Enumeration; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERGeneralizedTime; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DERUTCTime; /** * PKIX RFC-2459 - TBSCertList object. * <pre> * TBSCertList ::= SEQUENCE { * version Version OPTIONAL, * -- if present, shall be v2 * signature AlgorithmIdentifier, * issuer Name, * thisUpdate Time, * nextUpdate Time OPTIONAL, * revokedCertificates SEQUENCE OF SEQUENCE { * userCertificate CertificateSerialNumber, * revocationDate Time, * crlEntryExtensions Extensions OPTIONAL * -- if present, shall be v2 * } OPTIONAL, * crlExtensions [0] EXPLICIT Extensions OPTIONAL * -- if present, shall be v2 * } * </pre> */ public class TBSCertList extends ASN1Encodable { public static class CRLEntry extends ASN1Encodable { ASN1Sequence seq; DERInteger userCertificate; Time revocationDate; X509Extensions crlEntryExtensions; public CRLEntry( ASN1Sequence seq) { if (seq.size() < 2 || seq.size() > 3) { throw new IllegalArgumentException("Bad sequence size: " + seq.size()); } this.seq = seq; userCertificate = DERInteger.getInstance(seq.getObjectAt(0)); revocationDate = Time.getInstance(seq.getObjectAt(1)); } public DERInteger getUserCertificate() { return userCertificate; } public Time getRevocationDate() { return revocationDate; } public X509Extensions getExtensions() { if (crlEntryExtensions == null && seq.size() == 3) { crlEntryExtensions = X509Extensions.getInstance(seq.getObjectAt(2)); } return crlEntryExtensions; } public DERObject toASN1Object() { return seq; } } private class RevokedCertificatesEnumeration implements Enumeration { private final Enumeration en; RevokedCertificatesEnumeration(Enumeration en) { this.en = en; } public boolean hasMoreElements() { return en.hasMoreElements(); } public Object nextElement() { return new CRLEntry(ASN1Sequence.getInstance(en.nextElement())); } } private class EmptyEnumeration implements Enumeration { public boolean hasMoreElements() { return false; } public Object nextElement() { return null; // TODO: check exception handling } } ASN1Sequence seq; DERInteger version; AlgorithmIdentifier signature; X509Name issuer; Time thisUpdate; Time nextUpdate; ASN1Sequence revokedCertificates; X509Extensions crlExtensions; public static TBSCertList getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } public static TBSCertList getInstance( Object obj) { if (obj instanceof TBSCertList) { return (TBSCertList)obj; } else if (obj instanceof ASN1Sequence) { return new TBSCertList((ASN1Sequence)obj); } throw new IllegalArgumentException("unknown object in factory: " + obj.getClass().getName()); } public TBSCertList( ASN1Sequence seq) { if (seq.size() < 3 || seq.size() > 7) { throw new IllegalArgumentException("Bad sequence size: " + seq.size()); } int seqPos = 0; this.seq = seq; if (seq.getObjectAt(seqPos) instanceof DERInteger) { version = DERInteger.getInstance(seq.getObjectAt(seqPos++)); } else { version = new DERInteger(0); } signature = AlgorithmIdentifier.getInstance(seq.getObjectAt(seqPos++)); issuer = X509Name.getInstance(seq.getObjectAt(seqPos++)); thisUpdate = Time.getInstance(seq.getObjectAt(seqPos++)); if (seqPos < seq.size() && (seq.getObjectAt(seqPos) instanceof DERUTCTime || seq.getObjectAt(seqPos) instanceof DERGeneralizedTime || seq.getObjectAt(seqPos) instanceof Time)) { nextUpdate = Time.getInstance(seq.getObjectAt(seqPos++)); } if (seqPos < seq.size() && !(seq.getObjectAt(seqPos) instanceof DERTaggedObject)) { revokedCertificates = ASN1Sequence.getInstance(seq.getObjectAt(seqPos++)); } if (seqPos < seq.size() && seq.getObjectAt(seqPos) instanceof DERTaggedObject) { crlExtensions = X509Extensions.getInstance(seq.getObjectAt(seqPos)); } } public int getVersion() { return version.getValue().intValue() + 1; } public DERInteger getVersionNumber() { return version; } public AlgorithmIdentifier getSignature() { return signature; } public X509Name getIssuer() { return issuer; } public Time getThisUpdate() { return thisUpdate; } public Time getNextUpdate() { return nextUpdate; } public CRLEntry[] getRevokedCertificates() { if (revokedCertificates == null) { return new CRLEntry[0]; } CRLEntry[] entries = new CRLEntry[revokedCertificates.size()]; for (int i = 0; i < entries.length; i++) { entries[i] = new CRLEntry(ASN1Sequence.getInstance(revokedCertificates.getObjectAt(i))); } return entries; } public Enumeration getRevokedCertificateEnumeration() { if (revokedCertificates == null) { return new EmptyEnumeration(); } return new RevokedCertificatesEnumeration(revokedCertificates.getObjects()); } public X509Extensions getExtensions() { return crlExtensions; } public DERObject toASN1Object() { return seq; } }
package org.grobid.service.process; import java.util.List; import java.util.NoSuchElementException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.grobid.core.data.Affiliation; import org.grobid.core.data.BiblioItem; import org.grobid.core.data.Date; import org.grobid.core.data.Person; import org.grobid.core.engines.Engine; import org.grobid.core.factory.GrobidPoolingFactory; import org.grobid.service.util.GrobidRestUtils; import org.grobid.service.util.GrobidServiceProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Damien * */ public class GrobidRestProcessString { /** * The class Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestProcessString.class); /** * Parse a raw date and return the corresponding normalized date. * * @param the * raw date string * @return a response object containing the structured xml representation of * the date */ public static Response processDate(String date) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; boolean isparallelExec = GrobidServiceProperties.isParallelExec(); Engine engine = null; try { LOGGER.debug(">> set raw date for stateless service'..."); engine = GrobidRestUtils.getEngine(isparallelExec); List<Date> dates; date = date.replaceAll("\\n", " ").replaceAll("\\t", " "); if (isparallelExec) { dates = engine.processDate(date); } else { synchronized (engine) { dates = engine.processDate(date); } } if (dates != null) { if (dates.size() == 1) retVal = dates.get(0).toString(); else retVal = dates.toString(); } if (!GrobidRestUtils.isResultOK(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (isparallelExec && engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of names from a header section and return the * corresponding normalized authors. * * @param the * string of the raw sequence of header authors * @return a response object containing the structured xml representation of * the authors */ public static Response processNamesHeader(String names) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; boolean isparallelExec = GrobidServiceProperties.isParallelExec(); Engine engine = null; try { LOGGER.debug(">> set raw header author sequence for stateless service'..."); engine = GrobidRestUtils.getEngine(isparallelExec); List<Person> authors; names = names.replaceAll("\\n", " ").replaceAll("\\t", " "); if (isparallelExec) { authors = engine.processAuthorsHeader(names); } else { synchronized (engine) { authors = engine.processAuthorsHeader(names); } } if (authors != null) { if (authors.size() == 1) retVal = authors.get(0).toString(); else retVal = authors.toString(); } if (!GrobidRestUtils.isResultOK(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (isparallelExec && engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of names from a header section and return the * corresponding normalized authors. * * @param the * string of the raw sequence of header authors. * @return a response object containing the structured xml representation of * the authors */ public static Response processNamesCitation(String names) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; boolean isparallelExec = GrobidServiceProperties.isParallelExec(); Engine engine = null; try { LOGGER.debug(">> set raw citation author sequence for stateless service'..."); engine = GrobidRestUtils.getEngine(isparallelExec); List<Person> authors; names = names.replaceAll("\\n", " ").replaceAll("\\t", " "); if (isparallelExec) { authors = engine.processAuthorsCitation(names); } else { synchronized (engine) { authors = engine.processAuthorsCitation(names); } } if (authors != null) { if (authors.size() == 1) retVal = authors.get(0).toString(); else retVal = authors.toString(); } if (!GrobidRestUtils.isResultOK(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (isparallelExec && engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of affiliations and return the corresponding * normalized affiliations with address. * * @param the * string of the raw sequence of affiliation+address * @return a response object containing the structured xml representation of * the affiliation */ public static Response processAffiliations(String affiliation) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; boolean isparallelExec = GrobidServiceProperties.isParallelExec(); Engine engine = null; try { LOGGER.debug(">> set raw affiliation + address blocks for stateless service'..."); engine = GrobidRestUtils.getEngine(isparallelExec); List<Affiliation> affiliationList; affiliation = affiliation.replaceAll("\\n", " ").replaceAll("\\t", " "); if (isparallelExec) { affiliationList = engine.processAffiliation(affiliation); } else { synchronized (engine) { affiliationList = engine.processAffiliation(affiliation); } } if (affiliationList != null) { if (affiliationList.size() == 1) retVal = affiliationList.get(0).toString(); else retVal = affiliationList.toString(); } if (!GrobidRestUtils.isResultOK(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (isparallelExec && engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of affiliations and return the corresponding * normalized affiliations with address. * * @param the * string of the raw sequence of affiliation+address * @return a response object containing the structured xml representation of * the affiliation */ public static Response processCitations(String citation) { LOGGER.debug(methodLogIn()); Response response = null; boolean isparallelExec = GrobidServiceProperties.isParallelExec(); Engine engine = null; try { engine = GrobidRestUtils.getEngine(isparallelExec); BiblioItem biblioItem; citation = citation.replaceAll("\\n", " ").replaceAll("\\t", " "); if (isparallelExec) { biblioItem = engine.processRawReference(citation, false); } else { synchronized (engine) { biblioItem = engine.processRawReference(citation, false); } } if (biblioItem == null) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).entity(biblioItem.toTEI(-1)).type(MediaType.APPLICATION_XML).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (isparallelExec && engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * @return */ public static String methodLogIn() { return ">> " + GrobidRestProcessString.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } /** * @return */ public static String methodLogOut() { return "<< " + GrobidRestProcessString.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } }
package ee.stacc.productivity.edsl.string; import java.util.Iterator; import java.util.List; public class AbstractStringEqualsVisitor implements IAbstractStringVisitor<Boolean, IAbstractString> { @Override public Boolean visitStringCharacterSet( StringCharacterSet me, IAbstractString data) { if (data instanceof StringCharacterSet) { StringCharacterSet other = (StringCharacterSet) data; return areEqual(me.getContents(), other.getContents()) && positionEquals(me, other); } return false; } @Override public Boolean visitStringChoice(StringChoice me, IAbstractString data) { if (data instanceof StringChoice) { StringChoice other = (StringChoice) data; return positionEquals(me, other) && contentEquals(me.getItems(), other.getItems()); } return false; } @Override public Boolean visitStringConstant(StringConstant me, IAbstractString data) { if (data instanceof StringConstant) { StringConstant other = (StringConstant) data; return positionEquals(me, other) && areEqual(me.getEscapedValue(), other.getEscapedValue()); } return false; } @Override public Boolean visitStringParameter( StringParameter me, IAbstractString data) { throw new UnsupportedOperationException(); } @Override public Boolean visitStringRepetition( StringRepetition me, IAbstractString data) { if (data instanceof StringRepetition) { StringRepetition other = (StringRepetition) data; return positionEquals(me, other) && abstractStringEquals(me.getBody(), other.getBody()); } return false; } protected boolean abstractStringEquals(IAbstractString a, IAbstractString b) { return a.accept(this, b); } @Override public Boolean visitStringSequence(StringSequence me, IAbstractString data) { if (data instanceof StringSequence) { StringSequence other = (StringSequence) data; return positionEquals(me, other) && contentEquals(me.getItems(), other.getItems()); } return false; } private boolean contentEquals(List<IAbstractString> a, List<IAbstractString> b) { if (a.size() != b.size()) { return false; } Iterator<IAbstractString> ai = a.iterator(); Iterator<IAbstractString> bi = b.iterator(); for (;ai.hasNext();) { IAbstractString as = ai.next(); IAbstractString bs = bi.next(); if (!abstractStringEquals(as, bs)) { return false; } } return true; } private static <T> boolean areEqual(T a, T b) { if (a == b) { return true; } if (a != null) { return a.equals(b); } return false; } protected static boolean positionEquals(IAbstractString a, IAbstractString b) { return areEqual(a.getPosition(), b.getPosition()); } }
package org.callimachusproject.setup; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.mail.MessagingException; import javax.naming.NamingException; import org.callimachusproject.Version; import org.callimachusproject.repository.CalliRepository; import org.callimachusproject.util.CallimachusConf; import org.callimachusproject.util.Mailer; import org.openrdf.OpenRDFException; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.RDFS; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.Update; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.rio.RDFFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SetupTool { private static final String ADMIN_GROUP = "/auth/groups/admin"; private static final String REALM_TYPE = "types/Realm"; private static final String FOLDER_TYPE = "types/Folder"; private static final String CALLI = "http://callimachusproject.org/rdf/2009/framework private static final String CALLI_FOLDER = CALLI + "Folder"; private static final String CALLI_REALM = CALLI + "Realm"; private static final String CALLI_HASCOMPONENT = CALLI + "hasComponent"; private static final String CALLI_AUTHENTICATION = CALLI + "authentication"; private static final String PREFIX = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema + "PREFIX calli:<http://callimachusproject.org/rdf/2009/framework private static final String COPY_FILE_PERM = PREFIX + "INSERT { $file\n" + "calli:reader ?reader; calli:subscriber ?subscriber; calli:contributor ?contributor; calli:editor ?editor; calli:administrator ?administrator\n" + "} WHERE { ?parent calli:hasComponent $file\n" + "OPTIONAL { ?parent calli:reader ?reader }\n" + "OPTIONAL { ?parent calli:subscriber ?subscriber }\n" + "OPTIONAL { ?parent calli:contributor ?contributor }\n" + "OPTIONAL { ?parent calli:editor ?editor }\n" + "OPTIONAL { ?parent calli:administrator ?administrator }\n" + "}"; private static final String COPY_REALM_PROPS = PREFIX + "INSERT { $realm\n" + "calli:authentication ?auth; calli:unauthorized ?unauth; calli:forbidden ?forbid; calli:error ?error; calli:layout ?layout; calli:allowOrigin ?allowed\n" + "} WHERE { {SELECT ?origin { ?origin a calli:Realm; calli:hasComponent+ $realm} ORDER BY desc(?origin) LIMIT 1}\n" + "{ ?origin calli:authentication ?auth }\n" + "UNION { ?origin calli:unauthorized ?unauth }\n" + "UNION { ?origin calli:forbidden ?forbid }\n" + "UNION { ?origin calli:error ?error }\n" + "UNION { ?origin calli:layout ?layout }\n" + "UNION { ?origin calli:allowOrigin ?allowed }\n" + "}"; private static final String SELECT_REALM = PREFIX + "SELECT ?realm\n" + "(group_concat(if(bound(?layout),str(?layout),\"\")) AS ?layout)\n" + "(group_concat(if(bound(?errorPipe),str(?errorPipe),\"\")) AS ?errorPipe)\n" + "(group_concat(if(bound(?forbiddenPage),str(?forbiddenPage),\"\")) AS ?forbiddenPage)\n" + "(group_concat(if(bound(?unauthorizedPage),str(?unauthorizedPage),\"\")) AS ?unauthorizedPage)\n" + "(group_concat(if(bound(?authentication),str(?authentication),\"\")) AS ?authentication)\n" + "WHERE {\n" + "{ ?realm a </callimachus/1.0/types/Realm> }\n" + "UNION { ?realm a </callimachus/1.0/types/Origin> }\n" + "OPTIONAL { { ?realm calli:layout ?layout }\n" + "UNION { ?realm calli:error ?errorPipe }\n" + "UNION { ?realm calli:forbidden ?forbiddenPage }\n" + "UNION { ?realm calli:unauthorized ?unauthorizedPage }\n" + "UNION { ?realm calli:authentication ?authentication } }\n" + "} GROUP BY ?realm ORDER BY ?realm"; private static final String SELECT_EMAIL = PREFIX + "SELECT ?label ?email { </> calli:authentication [calli:authNamespace [calli:hasComponent [rdfs:label ?label; calli:email ?email]]] }"; private static final String SELECT_USERNAME = PREFIX + "SELECT ?username { </> calli:authentication [calli:authNamespace [calli:hasComponent [calli:name ?username; calli:email $email]]] }"; private final Logger logger = LoggerFactory.getLogger(SetupTool.class); private final String repositoryID; private final CalliRepository repository; private final CallimachusConf conf; public SetupTool(String repositoryID, CalliRepository repository, CallimachusConf conf) throws OpenRDFException { this.repositoryID = repositoryID; this.repository = repository; this.conf = conf; } public String toString() { return repository.toString(); } public String getRepositoryID() { return repositoryID; } public CalliRepository getRepository() { return repository; } public SetupRealm[] getRealms() throws IOException, OpenRDFException { List<SetupRealm> list = new ArrayList<SetupRealm>(); CallimachusSetup setup = new CallimachusSetup(repository); RepositoryConnection con = setup.openConnection(); try { Map<String, String> idsByOrigin = conf.getOriginRepositoryIDs(); for (Map.Entry<String, String> e : idsByOrigin.entrySet()) { if (!repositoryID.equals(e.getValue())) continue; String root = e.getKey() + "/"; TupleQueryResult results = con.prepareTupleQuery( QueryLanguage.SPARQL, SELECT_REALM, root).evaluate(); try { while (results.hasNext()) { BindingSet result = results.next(); SetupRealm o = createSetupRealm(e.getKey(), result); if (o != null) { list.add(o); } } } finally { results.close(); } } } finally { con.close(); } return list.toArray(new SetupRealm[list.size()]); } public synchronized void setupWebappOrigin(String origin) throws IOException, OpenRDFException, NoSuchMethodException, InvocationTargetException { Map<String, String> map = conf.getOriginRepositoryIDs(); if (map.containsKey(origin) && !repositoryID.equals(map.get(origin))) throw new IllegalArgumentException( "Origin already exists in repository: " + map.get(origin)); map = new LinkedHashMap<String, String>(map); map.put(origin, repositoryID); conf.setOriginRepositoryIDs(map); for (SetupRealm o : getRealms()) { if (o.getWebappOrigin().equals(origin)) return; // already exists in store } // if origin is undefined in RDF store, create it createWebappOrigin(origin); } public synchronized void setupRealm(String realm, String webappOrigin) throws IOException, OpenRDFException { java.net.URI uri = java.net.URI.create(realm); if (!realm.startsWith(uri.toASCIIString())) throw new IllegalArgumentException("Invalid realm: " + realm); if (!realm.endsWith("/")) throw new IllegalArgumentException("Realms must end with a slash: " + realm); String origin = uri.getScheme() + "://" + uri.getAuthority(); CallimachusSetup setup = new CallimachusSetup(repository); setup.prepareWebappOrigin(webappOrigin); setup.createOrigin(origin, webappOrigin); setup.finalizeWebappOrigin(webappOrigin); createRealm(realm, webappOrigin); } public void addAuthentication(String realm, String manager) throws OpenRDFException, IOException { ObjectConnection con = repository.getConnection(); try { con.setAutoCommit(false); ValueFactory vf = con.getValueFactory(); URI s = vf.createURI(realm); URI p = vf.createURI(CALLI_AUTHENTICATION); URI o = vf.createURI(manager); if (!con.hasStatement(s, p, o)) { con.add(s, p, o); } con.setAutoCommit(true); } finally { con.close(); } } public void removeAuthentication(String realm, String manager) throws OpenRDFException, IOException { ObjectConnection con = repository.getConnection(); try { ValueFactory vf = con.getValueFactory(); URI s = vf.createURI(realm); URI p = vf.createURI(CALLI_AUTHENTICATION); URI o = vf.createURI(manager); con.remove(s, p, o); } finally { con.close(); } } public boolean createResource(String graph, String systemId, String type, String webappOrigin) throws OpenRDFException, IOException { ObjectConnection con = repository.getConnection(); try { ValueFactory vf = con.getValueFactory(); URI target = vf.createURI(systemId); URI folder = createFolder(getParentFolder(systemId), webappOrigin, con); URI hasComponent = vf.createURI(CALLI_HASCOMPONENT); con.setAutoCommit(false); if (con.hasStatement(folder, hasComponent, target)) return false; con.add(new StringReader(graph), systemId, RDFFormat.forMIMEType(type)); con.add(folder, hasComponent, target); Update perm = con.prepareUpdate(QueryLanguage.SPARQL, COPY_FILE_PERM); perm.setBinding("file", target); perm.execute(); con.setAutoCommit(true); return true; } finally { con.close(); } } public synchronized String[] getDigestEmailAddresses(String webappOrigin) throws OpenRDFException, IOException { CallimachusSetup setup = new CallimachusSetup(repository); RepositoryConnection con = setup.openConnection(); try { List<String> list = new ArrayList<String>(); TupleQueryResult results = con.prepareTupleQuery( QueryLanguage.SPARQL, SELECT_EMAIL, webappOrigin + "/") .evaluate(); try { while (results.hasNext()) { BindingSet result = results.next(); Value l = result.getValue("label"); Value e = result.getValue("email"); list.add(l.stringValue() + " <" + e.stringValue() + ">"); } } finally { results.close(); } return list.toArray(new String[list.size()]); } finally { con.close(); } } public synchronized void inviteAdminUser(String email, String subject, String body, String webappOrigin) throws IOException, OpenRDFException, MessagingException, NamingException, GeneralSecurityException { CallimachusSetup setup = new CallimachusSetup(repository); setup.inviteUser(email, webappOrigin); setup.addInvitedUserToGroup(email, ADMIN_GROUP, webappOrigin); Set<String> links = setup.getUserRegistrationLinks(email, webappOrigin); for (String link : links) { String emailBody; if (body.contains("?register")) { emailBody = body.replaceAll("[^<\"\\s]*\\?register", link); } else { emailBody = body + "\n" + link; } new Mailer().sendMessage(subject + "\n" + emailBody, email); } } public synchronized boolean registerDigestUser(String email, String password, String webappOrigin) throws OpenRDFException, IOException { CallimachusSetup setup = new CallimachusSetup(repository); RepositoryConnection con = setup.openConnection(); try { int b = email.indexOf('<'); int e = email.indexOf('>'); if (b >= 0 && e > 0) { email = email.substring(b + 1, e); } return registeDigestUser(email, password.toCharArray(), webappOrigin, setup, con); } finally { con.close(); } } private SetupRealm createSetupRealm(String webappOrigin, BindingSet result) { String realm = stringValue(result.getValue("realm")); if (realm == null) return null; String layout = stringValue(result.getValue("layout")); String error = stringValue(result.getValue("errorPipe")); String forb = stringValue(result.getValue("forbiddenPage")); String unauth = stringValue(result.getValue("unauthorizedPage")); String auth = stringValue(result.getValue("authentication")); String[] split = new String[0]; if (auth != null && auth.length() > 0) { split = auth.trim().split("\\s+"); } return new SetupRealm(realm, webappOrigin, layout, error, forb, unauth, split, repositoryID); } private String stringValue(Value value) { if (value == null || value.stringValue().length() == 0) return null; return value.stringValue(); } private boolean registeDigestUser(String email, char[] password, String webappOrigin, CallimachusSetup setup, RepositoryConnection con) throws RepositoryException, MalformedQueryException, QueryEvaluationException, OpenRDFException, IOException { boolean changed = false; TupleQuery qry = con.prepareTupleQuery(QueryLanguage.SPARQL, SELECT_USERNAME, webappOrigin + "/"); qry.setBinding("email", con.getValueFactory().createLiteral(email)); TupleQueryResult results = qry.evaluate(); try { while (results.hasNext()) { String username = results.next().getValue("username") .stringValue(); changed |= setup.registerDigestUser(email, username, password, webappOrigin); } } finally { results.close(); } return changed; } private void createWebappOrigin(final String origin) throws OpenRDFException, IOException, NoSuchMethodException, InvocationTargetException { CallimachusSetup setup = new CallimachusSetup(repository); setup.prepareWebappOrigin(origin); boolean created = setup.createWebappOrigin(origin); setup.finalizeWebappOrigin(origin); if (conf.getAppVersion() == null) { conf.setAppVersion(Version.getInstance().getVersionCode()); } if (created) { logger.info("Callimachus installed at {}", origin); } else { logger.info("Callimachus already appears to be installed at {}", origin); } } private boolean createRealm(String realm, String webappOrigin) throws OpenRDFException { ObjectConnection con = repository.getConnection(); try { ValueFactory vf = con.getValueFactory(); URI subj = vf.createURI(realm); if (con.hasStatement(subj, RDF.TYPE, vf.createURI(CALLI_REALM), true)) return false; con.add(subj, RDF.TYPE, vf.createURI(CALLI_REALM)); con.add(subj, RDF.TYPE, webapp(webappOrigin, REALM_TYPE)); createFolder(realm, webappOrigin, con); Update props = con.prepareUpdate(QueryLanguage.SPARQL, COPY_REALM_PROPS); props.setBinding("realm", subj); props.execute(); return true; } finally { con.close(); } } private URI webapp(String webappOrigin, String path) throws OpenRDFException { return repository.getValueFactory().createURI(repository.getCallimachusUrl(webappOrigin, path)); } private URI createFolder(String folder, String webappOrigin, ObjectConnection con) throws OpenRDFException { ValueFactory vf = con.getValueFactory(); URI uri = vf.createURI(folder); if (con.hasStatement(uri, RDF.TYPE, vf.createURI(CALLI_FOLDER))) return uri; String parent = getParentFolder(folder); if (parent == null) throw new IllegalStateException( "Can only import a CAR within a previously defined origin or realm"); URI parentUri = createFolder(parent, webappOrigin, con); con.add(parentUri, vf.createURI(CALLI_HASCOMPONENT), uri); String label = folder.substring(parent.length()).replace("/", "") .replace('-', ' '); con.add(uri, RDFS.LABEL, vf.createLiteral(label)); con.add(uri, RDF.TYPE, vf.createURI(CALLI_FOLDER)); if (!con.hasStatement(uri, RDF.TYPE, webapp(webappOrigin, REALM_TYPE))) { con.add(uri, RDF.TYPE, webapp(webappOrigin, FOLDER_TYPE)); } Update perm = con.prepareUpdate(QueryLanguage.SPARQL, COPY_FILE_PERM); perm.setBinding("file", uri); perm.execute(); return uri; } private String getParentFolder(String folder) { int idx = folder.lastIndexOf('/', folder.length() - 2); if (idx < 0) return null; String parent = folder.substring(0, idx + 1); if (parent.endsWith(": return null; return parent; } }
// This file is part of the "OPeNDAP Web Coverage Service Project." // Authors: // Haibo Liu <haibo@iri.columbia.edu> // Nathan David Potter <ndp@opendap.org> // M. Benno Blumenthal <benno@iri.columbia.edu> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. package opendap.semantics.IRISail; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.jdom.Document; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.ProcessingInstruction; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used to create a JDOM document by querying against Sesame-OWLIM RDF store. * The <code>rootElementStr</code> * is the outer wrapper of the document. The <code>topURI</code> is the top element to retrieve * from the repository. * */ public class XMLfromRDF { private RepositoryConnection con; private Document doc; private Element root; private String queryString0; private Logger log; /** * Constructor, create the top query and the outer wrapper of the document. * @param con-connection to the repository. * @param rootElementStr-the outer wrapper of the document. * @param topURI-the top element in the document. */ public XMLfromRDF(RepositoryConnection con, String rootElementStr, String topURI) throws InterruptedException { this.log = LoggerFactory.getLogger(getClass()); //URI uri = new URIImpl(topURI); int pl = topURI.lastIndexOf(" String ns; if(pl > 0){ ns = topURI.substring(0,pl); }else{ pl = topURI.lastIndexOf("/"); ns = topURI.substring(0,pl); } this.root = new Element(rootElementStr,ns); this.doc = new Document(root); this.con = con; this.queryString0 = "SELECT DISTINCT topprop:, obj, valueclass, targetns "+ "FROM "+ "{containerclass} rdfs:subClassOf {} owl:onProperty {topprop:}; owl:allValuesFrom {valueclass}, "+ "{subject} topprop: {obj} rdf:type {valueclass}, "+ "[{topprop:} rdfs:isDefinedBy {} xsd:targetNamespace {targetns}] " + "using namespace "+ "xsd2owl = <http://iridl.ldeo.columbia.edu/ontologies/xsd2owl.owl "owl = <http://www.w3.org/2002/07/owl "xsd = <http://www.w3.org/2001/XMLSchema "rdfs = <http://www.w3.org/2000/01/rdf-schema "topprop = <"+topURI+">"; } /** * Constructor, sets the repository connection. Query string will be passed in through * getXMLfromRDF(String, String). * @param con-connection to the repository. * */ public XMLfromRDF(RepositoryConnection con) { this.log = LoggerFactory.getLogger(getClass()); this.con = con; } /** * Start the process of building the document. First level children are retrieved through * query zero and added to the document. * * @param topURI-searching phrase for the first level children */ public void getXMLfromRDF(String topURI, String serfqString0) throws InterruptedException{ TupleQueryResult result0 = null; try{ log.debug("queryString0: " +serfqString0); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, serfqString0); result0 = tupleQuery.evaluate(); while ( result0.hasNext()) { BindingSet bindingSet = (BindingSet) result0.next(); if (bindingSet.getValue("element") != null && bindingSet.getValue("uri") != null && bindingSet.getValue("class") != null){ Value valueOfElement = (Value) bindingSet.getValue("element"); Value valueOfUri = (Value) bindingSet.getValue("uri"); Value valueOfClass = (Value) bindingSet.getValue("class"); String queryString1 = createQueryString(valueOfUri.stringValue(), valueOfClass); String parent,ns; log.debug("queryString1: " +queryString1); if (topURI.lastIndexOf(" int pl = topURI.lastIndexOf(" ns = topURI.substring(0,pl); parent = topURI.substring(pl+1); }else if(topURI.lastIndexOf("/") >= 0){ int pl = topURI.lastIndexOf("/"); ns = topURI.substring(0,pl); parent = topURI.substring(pl+1); }else{ parent = topURI; ns = topURI; } URI uri = new URIImpl(valueOfElement.toString()); Value targetNS = (Value) bindingSet.getValue("targetns"); ns = uri.getNamespace(); if(targetNS != null){ ns = targetNS.stringValue(); } this.root = new Element(uri.getLocalName(),ns); this.doc = new Document(root); Map <String,String> docAttributes = new HashMap<String,String>(); String type = "text/xsl"; String href = "xsd2owl.xsl"; docAttributes.put("type", type); docAttributes.put("href", href); ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet",docAttributes); this.doc.addContent(pi); this.addChildren(queryString1, root, con,doc); } //if (bindingSet.getValue("topnameprop") } //while ( result0.hasNext()) }catch ( QueryEvaluationException e){ log.error(e.getMessage()); }catch (RepositoryException e){ log.error(e.getMessage()); }catch (MalformedQueryException e) { log.error(e.getMessage()); }finally{ if(result0!=null){ try { result0.close(); } catch (Exception e) { log.error("Caught an "+e.getClass().getName()+" Msg: " + e.getMessage()); } } } } /** * Start the process of building the document. First level children are retrieved through * query zero and added to the document. * * @param topURI-searching phrase for the first level children */ public void getXMLfromRDF(String topURI) throws InterruptedException{ TupleQueryResult result0 = null; try{ log.debug("queryString0: " +queryString0); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString0); result0 = tupleQuery.evaluate(); while ( result0.hasNext()) { BindingSet bindingSet = (BindingSet) result0.next(); if (bindingSet.getValue("obj") != null && bindingSet.getValue("valueclass") != null){ Value valueOfobj = (Value) bindingSet.getValue("obj"); Value valueOfobjtype = (Value) bindingSet.getValue("objtype"); Value valueOfvalueclass = (Value) bindingSet.getValue("valueclass"); String uritypestr; if (valueOfobjtype!= null){uritypestr= valueOfobjtype.stringValue();} else{ uritypestr= "nullstring"; } String queryString1 = createQueryString(valueOfobj.toString(), valueOfvalueclass); String parent,ns; log.debug("queryString1: " +queryString1); if (topURI.lastIndexOf(" int pl = topURI.lastIndexOf(" ns = topURI.substring(0,pl); parent = topURI.substring(pl+1); }else if(topURI.lastIndexOf("/") >= 0){ int pl = topURI.lastIndexOf("/"); ns = topURI.substring(0,pl); parent = topURI.substring(pl+1); }else{ parent = topURI; ns = topURI; } Value targetNS = (Value) bindingSet.getValue("targetns"); if(targetNS != null){ ns = targetNS.stringValue(); } Element chd1 = new Element(parent,ns); //first level children root.addContent(chd1); this.addChildren(queryString1, chd1, con,doc); } //if (bindingSet.getValue("topnameprop") } //while ( result0.hasNext()) }catch ( QueryEvaluationException e){ log.error(e.getMessage()); }catch (RepositoryException e){ log.error(e.getMessage()); }catch (MalformedQueryException e) { log.error(e.getMessage()); }finally{ if(result0!=null){ try { result0.close(); } catch (Exception e) { log.error(e.getMessage()); } } } } /** * Recursively retrieve children and add to the document. * * @param qString-query string for retrieving children * @param prt-parent * @param con-connection to the repository * @param doc-the document to build */ private void addChildren(String qString, Element prt, RepositoryConnection con, Document doc) throws InterruptedException{ TupleQueryResult result = null; boolean objisURI = false; //true if ojb is a URI/URL try{ TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, qString); result = tupleQuery.evaluate(); SortedMap<String,BindingSet > mapOrderObj = new TreeMap<String, BindingSet>(); while ( result.hasNext()) { BindingSet bindingSet = (BindingSet) result.next(); Value valueOfnameprop; Value valueOfobj; Value valueOfvalueclass; Value valueOforder; Value valueOfobjtype; Value valueOfform; if (bindingSet.getValue("nameprop") != null && bindingSet.getValue("obj") != null && bindingSet.getValue("valueclass") != null){ valueOfnameprop = (Value) bindingSet.getValue("nameprop"); valueOfobj = (Value) bindingSet.getValue("obj"); valueOfvalueclass = (Value) bindingSet.getValue("valueclass"); valueOforder = (Value) bindingSet.getValue("order1"); valueOfobjtype = (Value) bindingSet.getValue("objtype"); valueOfform = (Value) bindingSet.getValue("form"); }else{ valueOfnameprop = (Value) bindingSet.getValue("prop"); valueOfobj = (Value) bindingSet.getValue("obj"); valueOfvalueclass = (Value) bindingSet.getValue("rangeclass"); valueOforder = (Value) bindingSet.getValue("order1"); valueOfobjtype = (Value) bindingSet.getValue("objtype"); valueOfform = (Value) bindingSet.getValue("form"); } String formtypestr = valueOfform.stringValue(); URI formtype = new URIImpl(formtypestr); if(valueOfobjtype != null){ //have type description (element,attribute ...) String uritypestr = valueOfobjtype.stringValue(); String parent,ns; if (valueOfnameprop.toString().lastIndexOf(" int pl = valueOfnameprop.toString().lastIndexOf(" ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else if(valueOfnameprop.toString().lastIndexOf("/") >= 0){ int pl = valueOfnameprop.toString().lastIndexOf("/"); ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else{ parent = valueOfnameprop.toString(); ns = valueOfnameprop.toString(); } Value targetNS = (Value) bindingSet.getValue("targetns"); if(targetNS != null){ ns = targetNS.stringValue(); } URI uritype = new URIImpl(uritypestr); if(uritype.getLocalName().equalsIgnoreCase("attribute")){ URI urinameprop= new URIImpl(valueOfnameprop.stringValue()); if(formtype.getLocalName().equalsIgnoreCase("qualified")){ Namespace attributeNS = Namespace.getNamespace("attributeNS",urinameprop.getNamespace()); prt.setAttribute(urinameprop.getLocalName(),valueOfobj.stringValue(),attributeNS); } else{ prt.setAttribute(urinameprop.getLocalName(),valueOfobj.stringValue()); } }else if(uritype.getLocalName().equalsIgnoreCase("simpleContent")){ prt.setText(valueOfobj.stringValue()); } else{ Element chd; if (valueOforder != null){//order matters String mapkeydigit = null; if (valueOforder.stringValue().length() == 1) mapkeydigit = "00" +valueOforder.stringValue(); if (valueOforder.stringValue().length() == 2) mapkeydigit = "0" +valueOforder.stringValue(); if (valueOforder.stringValue().length() == 3) mapkeydigit = valueOforder.stringValue(); String mapkey = mapkeydigit+"-"+valueOfnameprop.stringValue()+valueOfobj.stringValue(); //key=0001-http mapOrderObj.put(mapkey,bindingSet); }else{//order does not matter if(formtype.getLocalName().equalsIgnoreCase("unqualified")){ chd = new Element(parent); }else{ chd = new Element(parent,ns); } String objURI = valueOfobj.toString().substring(0, 1); if (objURI.equalsIgnoreCase("\"")) //literal { chd.setText(valueOfobj.stringValue()); } else{ String queryStringc = createQueryString(valueOfobj.toString(), valueOfvalueclass); addChildren(queryStringc, chd, con,doc); }//if (obj3isURI/bnode) prt.addContent(chd); } } }else{ //no type description (element, attribute ...) String parent,ns; String uritypestr = "nullstring"; if (valueOfnameprop.toString().lastIndexOf(" int pl = valueOfnameprop.toString().lastIndexOf(" ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else if(valueOfnameprop.toString().lastIndexOf("/") >= 0){ int pl = valueOfnameprop.toString().lastIndexOf("/"); ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else{ parent = valueOfnameprop.toString(); ns = valueOfnameprop.toString(); } Element chd; if(formtype.getLocalName().equalsIgnoreCase("unqualified")){ chd = new Element(parent); }else{ chd = new Element(parent,ns); } prt.addContent(chd); String queryStringc = createQueryString(valueOfobj.toString(), valueOfvalueclass); String objURI = valueOfobj.toString().substring(0, 1); if(objURI.equalsIgnoreCase("\"")) { chd.setText(valueOfobj.stringValue()); } else{ objisURI = true; } if (objisURI){ addChildren(queryStringc, chd, con,doc); } } } //while ( result4.hasNext()) Iterator<String> iterator = mapOrderObj.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); BindingSet bindingSet = (BindingSet) mapOrderObj.get(key); Value valueOfnameprop; Value valueOfobj; Value valueOfvalueclass; Value valueOforder; Value valueOfobjtype; Value valueOfform; if (bindingSet.getValue("nameprop") != null && bindingSet.getValue("obj") != null && bindingSet.getValue("valueclass") != null){ valueOfnameprop = (Value) bindingSet.getValue("nameprop"); valueOfobj = (Value) bindingSet.getValue("obj"); valueOfvalueclass = (Value) bindingSet.getValue("valueclass"); valueOforder = (Value) bindingSet.getValue("order1"); valueOfobjtype = (Value) bindingSet.getValue("objtype"); valueOfform = (Value) bindingSet.getValue("form"); }else{ valueOfnameprop = (Value) bindingSet.getValue("prop"); valueOfobj = (Value) bindingSet.getValue("obj"); valueOfvalueclass = (Value) bindingSet.getValue("rangeclass"); valueOforder = (Value) bindingSet.getValue("order1"); valueOfobjtype = (Value) bindingSet.getValue("objtype"); valueOfform = (Value) bindingSet.getValue("form"); } String parent,ns; if (valueOfnameprop.toString().lastIndexOf(" int pl = valueOfnameprop.toString().lastIndexOf(" ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else if(valueOfnameprop.toString().lastIndexOf("/") >= 0){ int pl = valueOfnameprop.toString().lastIndexOf("/"); ns = valueOfnameprop.toString().substring(0,pl); parent = valueOfnameprop.toString().substring(pl+1); }else{ parent = valueOfnameprop.toString(); ns = valueOfnameprop.toString(); } Value targetNS = (Value) bindingSet.getValue("targetns"); if(targetNS != null){ ns = targetNS.stringValue(); } Element chd; String formtypestr = valueOfform.stringValue(); URI formtype = new URIImpl(formtypestr); if(formtype.getLocalName().equalsIgnoreCase("unqualified")){ chd = new Element(parent); }else{ chd = new Element(parent,ns); } if(valueOfobjtype.stringValue().equalsIgnoreCase("attribute")){ prt.setAttribute(valueOfnameprop.stringValue(),valueOfobjtype.stringValue()); } String objURI = valueOfobj.toString().substring(0, 1); if (objURI.equalsIgnoreCase("\"")) { chd.setText(valueOfobj.stringValue()); } else{ String queryStringc = createQueryString(valueOfobj.toString(), valueOfvalueclass); addChildren(queryStringc, chd, con,doc); } //if (obj3isURI) prt.addContent(chd); } //for (int i = 0; i < key.length; }catch ( QueryEvaluationException e){ log.error(e.getMessage()); }catch (RepositoryException e){ log.error(e.getMessage()); }catch (MalformedQueryException e) { log.error(e.getMessage()); } finally { if(result!=null){ try { result.close(); } catch (Exception e) { log.error(e.getMessage()); } } } }//void addChildren /** * Create the SeRQLquery string using the parent (URI) and the parent class (URI). * @param parentstr * @param parentclassstr * @return a SeRQL query string */ private String createQueryString(String parentstr, Value parentclassstr) throws InterruptedException{ String queryStringc; String objURI = parentstr.substring(0, 7); if (objURI.equalsIgnoreCase("http: queryStringc = "SELECT DISTINCT nameprop, obj, valueclass, order1, objtype, form, targetns "+ "FROM "+ "{parent:} nameprop {obj}, "+ "{parentclass:} xsd2owl:isConstrainedBy {restriction} owl:onProperty {nameprop}; "+ "owl:allValuesFrom {valueclass}, "+ "{subprop} rdfs:subPropertyOf {xsd2owl:isConstrainedBy}; "+ "xsd2owl:hasTarget {objtype}; xsd2owl:hasTargetForm {form}, "+ "{parentclass:} rdfs:subClassOf {} subprop {restriction}, "+ "[{parentclass:} xsd2owl:uses {nameprop},{{parentclass:} xsd2owl:uses {nameprop}} "+ "xsd2owl:useCount {order1}], "+ "[{nameprop} rdfs:isDefinedBy {} xsd:targetNamespace {targetns}] " + "using namespace "+ "xsd2owl = <http://iridl.ldeo.columbia.edu/ontologies/xsd2owl.owl "owl = <http://www.w3.org/2002/07/owl "xsd = <http://www.w3.org/2001/XMLSchema "rdfs = <http://www.w3.org/2000/01/rdf-schema "parent = <" + parentstr + ">," + "parentclass = <"+ parentclassstr + ">"; } else{ queryStringc = "SELECT DISTINCT nameprop, obj, valueclass, order1, objtype, form, targetns "+ "FROM "+ "{" + parentstr + "} nameprop {obj}, "+ "{parentclass:} xsd2owl:isConstrainedBy {restriction} owl:onProperty {nameprop}; "+ "owl:allValuesFrom {valueclass}, "+ "{subprop} rdfs:subPropertyOf {xsd2owl:isConstrainedBy}; "+ "xsd2owl:hasTarget {objtype}; xsd2owl:hasTargetForm {form}, "+ "{parentclass:} rdfs:subClassOf {} subprop {restriction}, "+ "[{parentclass:} xsd2owl:uses {nameprop},{{parentclass:} xsd2owl:uses {nameprop}} "+ "xsd2owl:useCount {order1}], "+ "[{nameprop} rdfs:isDefinedBy {} xsd:targetNamespace {targetns}] " + "using namespace "+ "xsd2owl = <http://iridl.ldeo.columbia.edu/ontologies/xsd2owl.owl "owl = <http://www.w3.org/2002/07/owl "xsd = <http://www.w3.org/2001/XMLSchema "rdfs = <http://www.w3.org/2000/01/rdf-schema "parentclass = <"+ parentclassstr + ">"; } return queryStringc; } public Document getDoc(){ return this.doc; } public Element getRootElement(){ return this.doc.getRootElement(); } }
package io.jenkins.blueocean.service.embedded.rest; import hudson.Extension; import io.jenkins.blueocean.api.profile.CreateOrganizationRequest; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.commons.stapler.JsonBody; import io.jenkins.blueocean.rest.sandbox.Organization; import io.jenkins.blueocean.rest.sandbox.OrganizationContainer; import jenkins.model.Jenkins; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.verb.POST; import java.util.Iterator; /** * {@link OrganizationContainer} for the embedded use * * @author Vivek Pandey * @author Kohsuke Kawaguchi */ @Extension public class OrganizationContainerImpl extends OrganizationContainer { @Override public Organization get(String name) { validateOrganization(name); return new OrganizationImpl(); } @Override @WebMethod(name="") @POST public Organization create(@JsonBody CreateOrganizationRequest req) { throw new ServiceException.NotImplementedException("Not implemented yet"); } @Override public Iterator<Organization> iterator() { return null; } protected void validateOrganization(String organization){ if (!organization.equals(Jenkins.getActiveInstance().getDisplayName().toLowerCase())) { throw new ServiceException.UnprocessableEntityException(String.format("Organization %s not found", organization)); } } }
package net.slreynolds.ds; /** * Base class for timing tests. * * @param <S> Type parameter of Result that has memory reference accumulated during * doWork * @param <T> Type of object returned from setUp and passed as an argument to doWork */ public abstract class AbstractTiming<S,T> { protected abstract T setUp(); protected abstract Result<S> doWork(T o); private int warmUp(int N) { T o; int computation = 7; for (int i = 0; i < N; i++) { o = setUp(); Result<S> res = doWork(o); computation |= res.getIntParam(); } return computation; } private void sleep() { try { Thread.sleep(3000); } catch (InterruptedException e) { // don't care } } /* * Results from this method are fairly bogus */ private long getMemoryUsed() { Runtime runt = Runtime.getRuntime(); System.gc(); System.gc(); System.gc(); sleep(); System.gc(); System.gc(); sleep(); return runt.totalMemory(); } private long measureSpace() { int computation = 7; T o = setUp(); long before = getMemoryUsed(); Result<S> res = doWork(o); long after = getMemoryUsed(); computation |= res.getIntParam(); System.out.printf("%d\n", computation); return Math.max(0,(after - before)); } private long[] timeIt(int N) { final long[] times = new long[N]; int computation = 7; long before = 0; long after = 0; T o = null; Result<S> res = null; for(int i = 0; i < N; i++) { o = setUp(); before = System.nanoTime(); res = doWork(o); after = System.nanoTime(); computation |= res.getIntParam(); times[i] = after - before; } System.out.printf("%d\n", computation); return times; } public void run(String title) { int res = warmUp(20); System.out.printf("res (%d)\n",res); // Don't print space statistics; they're unreliable //System.out.printf("%s uses %d, %d, %d bytes\n",title, measureSpace(), measureSpace(), measureSpace()); long[] times = timeIt(5); System.out.printf("Times (seconds)\n"); for (int i = 0; i < times.length; i++) { System.out.printf("%f ", times[i]/1.0E9); } System.out.printf("\n"); } }
package parser; import java.io.Serializable; public class Options implements Cloneable, Serializable { private static final long serialVersionUID = 1L; public enum LearningMode { Basic, // 1st order arc factored model Standard, // 2nd order model (3rd order?) Full // full model with global features } public String trainFile = null; public String testFile = null; public String outFile = null; public boolean train = false; public boolean test = false; public String wordVectorFile = null; public String modelFile = "model.out"; public String format = "CONLL"; //public boolean evalWithPunc = true; public int maxNumSent = -1; public int numPretrainIters = 1; public int maxNumIters = 10; public boolean initTensorWithPretrain = true; //public LearningMode learningMode = LearningMode.Basic; public LearningMode learningMode = LearningMode.Full; public boolean projective = false; public boolean learnLabel = true; public boolean pruning = false; public double pruningCoeff = 0.01; public int numHcThreads = 10; // hill climbing: number of threads public int numHcConverge = 300; // hill climbing: number of restarts to converge public boolean average = true; public double C = 0.01; public double gamma = 1; public int R = 50; // feature set public boolean useCS = true; // use consecutive siblings public boolean useGP = true; // use grandparent public boolean useHB = true; // use head bigram public boolean useGS = true; // use grand sibling public boolean useTS = true; // use tri-sibling public Options() { } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public void processArguments(String[] args) { for (String arg : args) { if (arg.equals("train")) { train = true; } else if (arg.equals("test")) { test = true; } else if (arg.equals("label")) { learnLabel = true; } else if (arg.equals("non-proj")) { projective = false; } else if (arg.equals("average:")) { average = Boolean.parseBoolean(arg.split(":")[1]); } else if (arg.startsWith("train-file:")) { trainFile = arg.split(":")[1]; } else if (arg.startsWith("test-file:")) { testFile = arg.split(":")[1]; } else if (arg.startsWith("output-file:")) { outFile = arg.split(":")[1]; } else if (arg.startsWith("model-file:")) { modelFile = arg.split(":")[1]; } else if (arg.startsWith("max-sent:")) { maxNumSent = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("C:")) { C = Double.parseDouble(arg.split(":")[1]); } else if (arg.startsWith("gamma:")) { gamma = Double.parseDouble(arg.split(":")[1]); } else if (arg.startsWith("R:")) { R = Integer.parseInt(arg.split(":")[1]); //Parameters.rank = R; } else if (arg.startsWith("word-vector:")) { wordVectorFile = arg.split(":")[1]; } else if (arg.startsWith("iters:")) { maxNumIters = Integer.parseInt(arg.split(":")[1]); } else if (arg.startsWith("pre-iters:")) { numPretrainIters = Integer.parseInt(arg.split(":")[1]); } } switch (learningMode) { case Basic: useCS = false; useGP = false; useHB = false; useGS = false; useTS = false; break; case Standard: useGS = false; useTS = false; break; case Full: break; default: break; } } public void printOptions() { System.out.println(" System.out.println("train-file: " + trainFile); System.out.println("test-file: " + testFile); System.out.println("model-name: " + modelFile); System.out.println("output-file: " + outFile); System.out.println("train: " + train); System.out.println("test: " + test); System.out.println("iters: " + maxNumIters); System.out.println("label: " + learnLabel); System.out.println("max-sent: " + maxNumSent); System.out.println("C: " + C); System.out.println("gamma: " + gamma); System.out.println("R: " + R); System.out.println("word-vector:" + wordVectorFile); System.out.println("projective: " + projective); System.out.println(); System.out.println("use consecutive siblings: " + useCS); System.out.println("use grandparent: " + useGP); System.out.println("use head bigram: " + useHB); System.out.println("use grand siblings: " + useGS); System.out.println("use tri-siblings: " + useTS); System.out.println(" } }
package org.eclipse.birt.report.engine.executor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.format.DateFormatter; import org.eclipse.birt.core.format.NumberFormatter; import org.eclipse.birt.core.format.StringFormatter; import org.eclipse.birt.core.script.BirtHashMap; import org.eclipse.birt.core.script.ICompiledScript; import org.eclipse.birt.core.script.IScriptContext; import org.eclipse.birt.core.script.ParameterAttribute; import org.eclipse.birt.core.script.ScriptContext; import org.eclipse.birt.core.script.ScriptExpression; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.script.ScriptEvalUtil; import org.eclipse.birt.report.data.adapter.api.AdapterException; import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil; import org.eclipse.birt.report.data.adapter.api.DataRequestSession; import org.eclipse.birt.report.data.adapter.api.ILinkedResult; import org.eclipse.birt.report.engine.adapter.ProgressMonitorProxy; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.api.IEngineTask; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.IHTMLImageHandler; import org.eclipse.birt.report.engine.api.IProgressMonitor; import org.eclipse.birt.report.engine.api.IRenderOption; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.engine.api.IStatusHandler; import org.eclipse.birt.report.engine.api.impl.EngineTask; import org.eclipse.birt.report.engine.api.impl.ReportDocumentWriter; import org.eclipse.birt.report.engine.api.impl.ReportEngine; import org.eclipse.birt.report.engine.api.impl.ReportRunnable; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.impl.ReportContent; import org.eclipse.birt.report.engine.data.IDataEngine; import org.eclipse.birt.report.engine.data.dte.DocumentDataSource; import org.eclipse.birt.report.engine.executor.optimize.ExecutionOptimize; import org.eclipse.birt.report.engine.executor.optimize.ExecutionPolicy; import org.eclipse.birt.report.engine.extension.IBaseResultSet; import org.eclipse.birt.report.engine.extension.ICubeResultSet; import org.eclipse.birt.report.engine.extension.IQueryResultSet; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.ir.Expression; import org.eclipse.birt.report.engine.ir.Report; import org.eclipse.birt.report.engine.ir.ReportElementDesign; import org.eclipse.birt.report.engine.ir.ReportItemDesign; import org.eclipse.birt.report.engine.parser.ReportParser; import org.eclipse.birt.report.engine.toc.TOCBuilder; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.IResourceLocator; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.simpleapi.IDesignElement; import org.eclipse.birt.report.model.api.simpleapi.SimpleElementFactory; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; /** * Captures the report execution context. This class is needed for accessing * global information during execution as well as for for scripting. It * implements the <code>report</code> Javascript object, as well as other * objects such as <code>report.params</code>,<code>report.config</code>, * <code>report.design</code>, etc. * */ public class ExecutionContext { /** * how many errors or exceptions will be registered. */ protected static final int ERROR_TOTAL_COUNT = 60; // engines used to create the context /** the engine used to create this context */ private ReportEngine engine; /** * task which uses this context. */ private EngineTask task; /** * logger used to log out the excepitons */ private Logger log; /** * execution mode, in this mode, the render operation should be executed. */ private boolean presentationMode = false; /** * execution mode, in this mode, the genreation opration should be executed. */ private boolean factoryMode = true; // utilitis used in this context. /** * The scripting context, used to evaluate the script. */ private ScriptContext scriptContext; /** * data engine, used to evaluate the data related expressions. */ private IDataEngine dataEngine; /** * utility used to create the report content */ private IReportExecutor executor; /** * utility used to create the TOC */ private TOCBuilder tocBuilder; // then is the input content /** * report runnable used to create the report content */ protected ReportRunnable runnable; protected ReportRunnable originalRunnable; /** * Global configuration variables */ private Map configs = new BirtHashMap( ); /** * Report parameters used to create the report content */ private Map params = new BirtHashMap( ); private Map persistentBeans = new HashMap( ); private Map transientBeans = new HashMap( ); private Map<String, PageVariable> pageVariables = new HashMap<String, PageVariable>( ); private ReportDocumentWriter docWriter; protected Report reportIR; /** * app context */ private Map appContext = new HashMap( ); /** * report context used to evaluate the java-based script. */ private IReportContext reportContext; /** * options used to render the report content */ private IRenderOption renderOption; /** * the locale from user level. */ private ULocale ulocale; /** * the locale defined in report level */ private ULocale rlocale; private static final String USER_LOCALE = "user_locale"; /** * define a time zone */ private TimeZone timeZone; // at last the output objects /** * report document, may be the output or input. */ private IReportDocument reportDoc; /** * the created report content */ private IReportContent reportContent; /** * the current executed design. */ private ReportItemDesign design; /** * The current content element to be executed or loaded */ private IContent content; /** * the current opened result set */ private IBaseResultSet[] rsets; /** * A stack of handle objects, with the current one on the top */ private Stack reportHandles = new Stack( ); /** * total page */ private long totalPage; /** * current page number */ private long pageNumber; private long filteredTotalPage; private long filteredPageNumber; /** * Flag to indicate whether task is canceled. */ private boolean isCancelled = false; /** * flag to indicate if the task should be canceled on error */ private boolean cancelOnError = false; /** * utilities used in the report execution. */ private HashMap<String, StringFormatter> stringFormatters = new HashMap<String, StringFormatter>( ); private HashMap<String, NumberFormatter> numberFormatters = new HashMap<String, NumberFormatter>( ); private HashMap<String, DateFormatter> dateFormatters = new HashMap<String, DateFormatter>( ); private ClassLoader applicationClassLoader; private boolean closeClassLoader; private int MAX_ERRORS = 100; private DocumentDataSource dataSource; /** * All page break listeners. */ private List pageBreakListeners; /** * an instance of ExtendedItemManager */ private ExtendedItemManager extendedItemManager = new ExtendedItemManager( ); /** * an instance of engine extension manager */ private EngineExtensionManager engineExtensionManager = new EngineExtensionManager( this ); /** * max rows per query. An initial value -1 means it is not set */ private int maxRowsPerQuery = -1; private EventHandlerManager eventHandlerManager; private IProgressMonitor progressMonitor; private boolean needOutputResultSet; private boolean isFixedLayout = false; private IDesignElement element = null; private boolean refreshData = false; /** * create a new context. Call close to finish using the execution context */ public ExecutionContext( ) { this( null ); } /** * create a new context. Call close to finish using the execution context */ public ExecutionContext( EngineTask engineTask ) { if ( engineTask != null ) { task = engineTask; engine = (ReportEngine) task.getEngine( ); log = task.getLogger( ); } else { log = Logger.getLogger( ExecutionContext.class.getName( ) ); } ulocale = ULocale.getDefault( ); timeZone = TimeZone.getDefault( ); eventHandlerManager = new EventHandlerManager( ); } private void initializeScriptContext( ) { // FIXME: the root scope defined in the report engine is not used. scriptContext = new ScriptContext( ); if ( engine != null ) { EngineConfig config = engine.getConfig( ); IStatusHandler statusHandler = config.getStatusHandler( ); if ( statusHandler != null ) { scriptContext.setAttribute( "statusHandle", statusHandler ); } } scriptContext.setLocale( ulocale.toLocale( ) ); // create script context used to execute the script statements // register the global variables in the script context scriptContext.setAttribute( "report", new ReportObject( ) ); scriptContext.setAttribute( "params", params ); //$NON-NLS-1$ scriptContext.setAttribute( "config", configs ); //$NON-NLS-1$ scriptContext.setAttribute( "currentPage", new Long( pageNumber ) ); scriptContext.setAttribute( "totalPage", new Long( totalPage ) ); scriptContext.setAttribute( "_jsContext", this ); scriptContext.setAttribute( "vars", pageVariables ); if ( runnable != null ) { registerDesign( runnable ); } if ( reportContext != null ) { scriptContext.setAttribute( "reportContext", reportContext ); } scriptContext.setAttribute( "pageNumber", new Long( pageNumber ) ); scriptContext.setAttribute( "totalPage", new Long( totalPage ) ); if ( task != null ) { IStatusHandler handler = task.getStatusHandler( ); if ( handler != null ) { handler.initialize( ); } if ( handler == null ) { handler = engine.getConfig( ).getStatusHandler( ); } if ( handler != null ) { scriptContext.setAttribute( "_statusHandle", handler ); } } if ( transientBeans != null ) { Iterator entries = transientBeans.entrySet( ).iterator( ); while ( entries.hasNext( ) ) { Map.Entry entry = (Map.Entry) entries.next( ); scriptContext.setAttribute( (String) entry.getKey( ), entry .getValue( ) ); } } if ( persistentBeans != null ) { Iterator entries = persistentBeans.entrySet( ).iterator( ); while ( entries.hasNext( ) ) { Map.Entry entry = (Map.Entry) entries.next( ); registerInRoot( (String) entry.getKey( ), entry.getValue( ) ); } } scriptContext.setApplicationClassLoader( getApplicationClassLoader( ) ); } /** * get the report engine. In that engine, we create the context. * * @return the report engine used to create the context. */ public ReportEngine getEngine( ) { return engine; } /** * Clean up the execution context before finishing using it */ public void close( ) { if ( extendedItemManager != null ) { extendedItemManager.close( ); extendedItemManager = null; } if ( engineExtensionManager != null ) { engineExtensionManager.close( ); engineExtensionManager = null; } if ( scriptContext != null ) { scriptContext.close( ); scriptContext = null; } if ( dataSource != null ) { try { dataSource.close( ); } catch ( IOException e ) { log.log( Level.SEVERE, "Failed to close the data source", e ); } dataSource = null; } if ( dataEngine != null ) { dataEngine.shutdown( ); dataEngine = null; } if ( closeClassLoader && applicationClassLoader instanceof ApplicationClassLoader ) { ( (ApplicationClassLoader) applicationClassLoader ).close( ); } IStatusHandler handler = task.getStatusHandler( ); if ( handler != null ) { handler.finish( ); } // RELEASE ALL THE MEMBERS EXPLICTLY AS THIS OBJECT MAY BE REFERENCED BY // THE SCRIPT OBJECT WHICH IS HOLDED IN THE FININALIZER QUEUE applicationClassLoader = null; engine = null; // task = null; executor = null; tocBuilder = null; // runnable = null; // originalRunnable = null; configs = null; params = null; persistentBeans = null; transientBeans = null; pageVariables = null; docWriter = null; reportIR = null; appContext = null; reportContext = null; renderOption = null; reportDoc = null; reportContent = null; design = null; content = null; rsets = null; reportHandles = null; errors.clear(); stringFormatters = null; numberFormatters = null; dateFormatters = null; pageBreakListeners = null; eventHandlerManager = null; progressMonitor = null; element = null; } /** * create a new scope, use the object to create the curren scope. * * @param object * the "this" object in the new scope */ public void newScope( Object object ) { scriptContext = getScriptContext( ).newContext( object ); } /** * exits a variable scope. */ public void exitScope( ) { if ( scriptContext == null ) { throw new IllegalStateException( ); } ScriptContext parent = scriptContext.getParent( ); if ( parent == null ) { throw new IllegalStateException( ); } scriptContext = parent; } /** * register beans in the execution context * * @param map * name value pair. */ public void registerBeans( Map map ) { if ( map != null ) { Iterator iter = map.entrySet( ).iterator( ); while ( iter.hasNext( ) ) { Map.Entry entry = (Map.Entry) iter.next( ); Object keyObj = entry.getKey( ); Object value = entry.getValue( ); if ( keyObj != null ) { String key = keyObj.toString( ); registerBean( key, value ); } } } } /** * declares a variable in the current scope. The variable is then accessible * through JavaScript. * * @param name * variable name * @param value * variable value */ public void registerBean( String name, Object value ) { transientBeans.put( name, value ); if ( scriptContext != null ) { scriptContext.setAttribute( name, value ); } } public void unregisterBean( String name ) { transientBeans.remove( name ); if ( scriptContext != null ) { scriptContext.setAttribute( name, null ); } } public Map getBeans( ) { return transientBeans; } public void registerGlobalBeans( Map map ) { if ( map != null ) { Iterator iter = map.entrySet( ).iterator( ); while ( iter.hasNext( ) ) { Map.Entry entry = (Map.Entry) iter.next( ); Object keyObj = entry.getKey( ); Object value = entry.getValue( ); if ( keyObj != null && value instanceof Serializable ) { String key = keyObj.toString( ); registerGlobalBean( key, (Serializable) value ); } } } } public void registerGlobalBean( String name, Serializable value ) { persistentBeans.put( name, value ); if ( scriptContext != null ) { registerInRoot( name, value ); } } public void unregisterGlobalBean( String name ) { persistentBeans.remove( name ); if ( scriptContext != null ) { registerInRoot( name, null ); } } public Map getGlobalBeans( ) { return persistentBeans; } private void registerInRoot( String name, Object value ) { getRootContext( ).setAttribute( name, value ); } public Object evaluate( Expression expr ) throws BirtException { if ( expr != null ) { switch ( expr.getType( ) ) { case Expression.CONSTANT : Expression.Constant cs = (Expression.Constant) expr; return cs.getValue( ); case Expression.SCRIPT : Expression.Script script = (Expression.Script) expr; ICompiledScript compiledScript = script .getScriptExpression( ); if ( compiledScript == null ) { compiledScript = compile( script.getLanguage( ), script .getFileName( ), script.getLineNumber( ), script.getScriptText( ) ); script.setCompiledScript( compiledScript ); } return evaluate( compiledScript ); case Expression.CONDITIONAL : IConditionalExpression ce = ( (Expression.Conditional) expr ) .getConditionalExpression( ); return evaluateCondExpr( ce ); } } return null; } /** * The expression may be evaluated at onPrepare stage, at that time the * reportIR is not initialized. */ protected String getScriptLanguage( ) { if ( reportIR != null ) { return reportIR.getScriptLanguage( ); } return Expression.SCRIPT_JAVASCRIPT; } public Object evaluate( String scriptText ) throws BirtException { return evaluate( getScriptLanguage( ), "<inline>", 1, scriptText ); } public Object evaluate( String fileName, String scriptText ) throws BirtException { return evaluate( getScriptLanguage( ), fileName, 1, scriptText ); } public Object evaluateInlineScript( String language, String scriptText ) throws BirtException { return evaluate( language, "<inline>", 1, scriptText ); } public Object evaluate( String language, String fileName, int lineNumber, String scriptText ) throws BirtException { if ( scriptText == null ) { return null; } ICompiledScript compiledScript = compile( language, fileName, lineNumber, scriptText ); return evaluate( compiledScript ); } private ICompiledScript compile( String language, String fileName, int lineNumber, String scriptText ) throws BirtException { ICompiledScript compiledScript = runnable.getScript( language, scriptText ); if ( compiledScript == null ) { compiledScript = getScriptContext( ).compile( language, fileName, lineNumber, scriptText ); runnable.putScript( language, scriptText, compiledScript ); } return compiledScript; } private Object evaluate( ICompiledScript compiledScript ) throws BirtException { return getScriptContext( ).evaluate( compiledScript ); } /** * evaluate conditional expression. A conditional expression can have an * operator, one LHS expression, and up to two expressions on RHS, i.e., * * testExpr operator operand1 operand2 or testExpr between 1 20 * * Now only support comparison between the same data type * * @param expr * the conditional expression to be evaluated * @return a boolean value (as an Object) */ public Object evaluateCondExpr( IConditionalExpression expr ) throws BirtException { IScriptExpression testExpr = expr.getExpression( ); ScriptContext scriptContext = getScriptContext( ); if ( testExpr == null ) return Boolean.FALSE; try { return ScriptEvalUtil.evalExpr( expr, scriptContext, ScriptExpression.defaultID, 0 ); } catch ( Throwable e ) { throw new EngineException( MessageConstants.INVALID_EXPRESSION_ERROR, testExpr .getText( ), e ); } } /** * execute the script. Simply evaluate the script, then drop the return * value * * @param script * script statement * @param fileName * file name * @param lineNo * line no */ public void execute( ICompiledScript script ) { try { scriptContext.evaluate( script ); } catch ( BirtException ex ) { addException( this.design, ex ); } } /** * @return Returns the locale. */ public Locale getLocale( ) { if ( rlocale != null ) return rlocale.toLocale( ); return ulocale.toLocale( ); } /** * @param locale * The locale to set. */ public void setLocale( ULocale ulocale ) { this.ulocale = ulocale; if ( rlocale == null ) this.getScriptContext( ).setLocale( ulocale.toLocale( ) ); } public TimeZone getTimeZone( ) { return this.timeZone; } public void setTimeZone( TimeZone timeZone ) { this.timeZone = timeZone; this.getScriptContext( ).setTimeZone( timeZone ); } public void openDataEngine( ) throws EngineException { if ( dataEngine == null ) { try { dataEngine = engine.getDataEngineFactory( ).createDataEngine( this, needOutputResultSet ); } catch ( Exception e ) { throw new EngineException( MessageConstants.CANNOT_CREATE_DATA_ENGINE, e ); } } } /** * @return Returns the dataEngine. */ public IDataEngine getDataEngine( ) throws EngineException { if ( dataEngine == null ) { openDataEngine( ); } return dataEngine; } public void closeDataEngine( ) { if ( dataEngine != null ) { dataEngine.shutdown( ); dataEngine = null; } } /** * @param name * @param value */ public void setParameterValue( String name, Object value ) { Object parameter = params.get( name ); if ( parameter instanceof ParameterAttribute ) { ( (ParameterAttribute) parameter ).setValue( value ); } else { params.put( name, new ParameterAttribute( value, null ) ); } } /** * @param name * @param value */ public void setParameter( String name, Object value, String displayText ) { params.put( name, new ParameterAttribute( value, displayText ) ); } public void clearParameters( ) { params.clear( ); } public Object getParameterValue( String name ) { Object parameter = params.get( name ); if ( parameter != null ) { return ( (ParameterAttribute) parameter ).getValue( ); } return null; } public Map getParameterValues( ) { HashMap result = new HashMap( ); Set entries = params.entrySet( ); Iterator iterator = entries.iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); ParameterAttribute parameter = (ParameterAttribute) entry .getValue( ); result.put( entry.getKey( ), parameter.getValue( ) ); } return result; } public Map getParameterDisplayTexts( ) { Map result = new HashMap( ); Set entries = params.entrySet( ); Iterator iterator = entries.iterator( ); while ( iterator.hasNext( ) ) { Map.Entry entry = (Map.Entry) iterator.next( ); String name = (String) entry.getKey( ); ParameterAttribute value = (ParameterAttribute) entry.getValue( ); result.put( name, value.getDisplayText( ) ); } return result; } public String getParameterDisplayText( String name ) { Object parameter = params.get( name ); if ( parameter != null ) { return ( (ParameterAttribute) parameter ).getDisplayText( ); } return null; } public void setParameterDisplayText( String name, String displayText ) { Object parameter = params.get( name ); if ( parameter != null ) { ( (ParameterAttribute) parameter ).setDisplayText( displayText ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.executor.IFactoryContext#getConfigs() */ public Map getConfigs( ) { return configs; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.engine.executor.IFactoryContext#getReportDesign() */ public ModuleHandle getDesign( ) { return runnable != null ? (ModuleHandle) runnable.getDesignHandle( ) : null; } public ReportDesignHandle getReportDesign( ) { ModuleHandle design = getDesign( ); if ( design instanceof ReportDesignHandle ) { return (ReportDesignHandle) design; } return null; } /** * @return Returns the report. */ public IReportContent getReportContent( ) { return reportContent; } public void setReportContent( ReportContent content ) { this.reportContent = content; content.setReportContext( reportContext ); content.setErrors( errors ); } /** * Loads scripts that are stored in an external file. Used to support * include-script. Each script file should be load only once. and the script * in the file must be encoded in UTF-8. * * @param fileName * script file name */ public void loadScript( String language, String fileName ) { ModuleHandle reportDesign = this.getDesign( ); URL url = null; if ( reportDesign != null ) { url = reportDesign.findResource( fileName, IResourceLocator.LIBRARY, appContext ); } if ( url == null ) { log.log( Level.SEVERE, "loading external script file " + fileName + " failed." ); addException( new EngineException( MessageConstants.SCRIPT_FILE_LOAD_ERROR, fileName ) ); //$NON-NLS-1$ return; } // read the script in the URL, and execution. InputStream in = null; try { in = url.openStream( ); ByteArrayOutputStream out = new ByteArrayOutputStream( ); byte[] buffer = new byte[1024]; int size = in.read( buffer ); while ( size != -1 ) { out.write( buffer, 0, size ); size = in.read( buffer ); } byte[] script = out.toByteArray( ); ICompiledScript compiledScript = getScriptContext( ).compile( language, fileName, 1, new String( script, "UTF-8" ) ); execute( compiledScript ); //$NON-NLS-1$ } catch ( IOException ex ) { log.log( Level.SEVERE, "loading external script file " + fileName + " failed.", //$NON-NLS-1$ //$NON-NLS-2$ ex ); addException( new EngineException( MessageConstants.SCRIPT_FILE_LOAD_ERROR, url.toString( ), ex ) ); //$NON-NLS-1$ // TODO This is a fatal error. Should throw an exception. } catch ( BirtException e ) { log.log( Level.SEVERE, "Failed to execute script " + fileName + ".", //$NON-NLS-1$ //$NON-NLS-2$ e ); addException( new EngineException( MessageConstants.SCRIPT_EVALUATION_ERROR, url.toString( ), e ) ); //$NON-NLS-1$ } finally { try { if ( in != null ) in.close( ); } catch ( IOException e ) { } } } public ScriptContext getScriptContext( ) { if ( scriptContext == null ) { initializeScriptContext( ); } return this.scriptContext; } /** * @return */ public IContent getContent( ) { return content; } public void setContent( IContent content ) { this.content = content; } public ReportItemDesign getItemDesign( ) { return design; } public void setItemDesign( ReportItemDesign design ) { this.design = design; } /** * @param obj */ public void pushHandle( DesignElementHandle obj ) { reportHandles.push( obj ); } /** * @return */ public DesignElementHandle popHandle( ) { return (DesignElementHandle) reportHandles.pop( ); } /** * @return */ public DesignElementHandle getHandle( ) { if ( reportHandles.empty( ) ) { return null; } return (DesignElementHandle) reportHandles.peek( ); } /** * Adds the exception * * @param ex * the Throwable instance */ public void addException( BirtException ex ) { DesignElementHandle handle = getDesign( ); if ( design != null ) { handle = design.getHandle( ); } addException( handle, ex ); } /** * A list of errors in time order, it is also shared by the report content */ private List<EngineException> errors = new ArrayList<EngineException>( ); /** * The exception list grouped by the element */ protected HashMap<DesignElementHandle, ElementExceptionInfo> elementExceptions = new HashMap<DesignElementHandle, ElementExceptionInfo>( ); public void addException( ReportElementDesign design, BirtException ex ) { DesignElementHandle handle = null; if ( null != design ) { handle = design.getHandle( ); } addException( handle, ex ); } public void addException( DesignElementHandle element, BirtException ex ) { if ( errors.size( ) >= ERROR_TOTAL_COUNT ) { if ( cancelOnError && task != null ) { task.cancel( ); } return; } EngineException engineEx = null; if ( ex instanceof EngineException ) { engineEx = (EngineException) ex; } else { engineEx = new EngineException( ex ); } if ( element != null ) { engineEx.setElementID( element.getID( ) ); } errors.add( engineEx ); ElementExceptionInfo exInfo = (ElementExceptionInfo) elementExceptions .get( element ); if ( exInfo == null ) { exInfo = new ElementExceptionInfo( element ); elementExceptions.put( element, exInfo ); } exInfo.addException( engineEx ); if ( cancelOnError && task != null ) { task.cancel( ); } } /** * report object is the script object used in the script context. * * All infos can get from this object. * * */ public class ReportObject { /** * get the report design handle * * @return report design object. */ public Object getDesign( ) { return element; } /** * get the report document. * * @return report document. */ public Object getDocument( ) { return reportDoc; } /** * @return a map of name/value pairs for all the parameters and their * values */ public Map getParams( ) { return params; } /** * @return a set of data sets */ public Object getDataSets( ) { return null; } /** * @return a set of data sources */ public Object getDataSources( ) { return null; } /** * @return a map of name/value pairs for all the configuration variables */ public Map getConfig( ) { return configs; } public Object getReportContext( ) { return reportContext; } } /** * @return Returns the runnable. */ public ReportRunnable getRunnable( ) { return runnable; } /** * @param runnable * The runnable to set. */ public void setRunnable( IReportRunnable runnable ) { this.runnable = (ReportRunnable) runnable; if ( scriptContext != null ) { registerDesign( runnable ); } } public void updateRunnable( IReportRunnable newRunnable ) { if ( originalRunnable == null ) { this.originalRunnable = this.runnable; } this.runnable = (ReportRunnable) newRunnable; if ( scriptContext != null ) { registerDesign( runnable ); } reportIR = null; } public ReportRunnable getOriginalRunnable( ) { if ( originalRunnable != null ) { return originalRunnable; } return runnable; } private void registerDesign( IReportRunnable runnable ) { DesignElementHandle design = (ModuleHandle) runnable.getDesignHandle( ); element = SimpleElementFactory.getInstance( ).getElement( design ); } /** * @return Returns the renderOption. */ public IRenderOption getRenderOption( ) { return renderOption; } /** * @param renderOption * The renderOption to set. */ public void setRenderOption( IRenderOption renderOption ) { this.renderOption = renderOption; } public String getOutputFormat( ) { String outputFormat = null; if ( renderOption != null ) { outputFormat = renderOption.getOutputFormat( ); } if ( outputFormat == null ) { if ( isFixedLayout( ) ) { outputFormat = IRenderOption.OUTPUT_FORMAT_PDF; } else { outputFormat = IRenderOption.OUTPUT_FORMAT_HTML; } } return outputFormat; } public class ElementExceptionInfo { DesignElementHandle element; ArrayList exList = new ArrayList( ); ArrayList countList = new ArrayList( ); public ElementExceptionInfo( DesignElementHandle element ) { this.element = element; } public void addException( BirtException e ) { for ( int i = 0; i < exList.size( ); i++ ) { BirtException err = (BirtException) exList.get( i ); if ( e.getErrorCode( ) != null && e.getErrorCode( ).equals( err.getErrorCode( ) ) && e.getLocalizedMessage( ) != null && e.getLocalizedMessage( ).equals( err.getLocalizedMessage( ) ) ) { countList.set( i, new Integer( ( (Integer) countList .get( i ) ).intValue( ) + 1 ) ); return; } } exList.add( e ); countList.add( new Integer( 1 ) ); } public String getType( ) { if ( element == null ) { return "report"; } return element.getDefn( ).getName( ); } public String getName( ) { if ( element == null ) { return "report"; } return element.getName( ); } public String getID( ) { if ( element == null ) return null; else return String.valueOf( element.getID( ) ); } public ArrayList getErrorList( ) { return exList; } public ArrayList getCountList( ) { return countList; } } public Map getAppContext( ) { return appContext; } public void setAppContext( Map appContext ) { this.appContext.clear( ); if ( appContext != null ) { this.appContext.putAll( appContext ); } } public IReportContext getReportContext( ) { return reportContext; } public void setReportContext( IReportContext reportContext ) { this.reportContext = reportContext; if ( scriptContext != null ) { getRootContext( ).setAttribute( "reportContext", reportContext ); } } public void setPageNumber( long pageNo ) { pageNumber = pageNo; if ( scriptContext != null ) { getRootContext( ) .setAttribute( "pageNumber", new Long( pageNumber ) ); } if ( totalPage < pageNumber ) { setTotalPage( pageNumber ); } } /** * set the total page. * * @param totalPage * total page */ public void setTotalPage( long totalPage ) { if ( totalPage > this.totalPage ) { this.totalPage = totalPage; if ( scriptContext != null ) { getRootContext( ).setAttribute( "totalPage", new Long( totalPage ) ); } if ( reportContent instanceof ReportContent ) { ( (ReportContent) reportContent ).setTotalPage( totalPage ); } } } /** * get the current page number * * @return current page number */ public long getPageNumber( ) { return pageNumber; } /** * get the total page have been created. * * @return total page */ public long getTotalPage( ) { return totalPage; } public void setFilteredPageNumber( long pageNo ) { filteredPageNumber = pageNo; } public void setFilteredTotalPage( long totalPage ) { filteredTotalPage = totalPage; } public long getFilteredPageNumber( ) { if ( filteredPageNumber <= 0 ) { return pageNumber; } return filteredPageNumber; } public long getFilteredTotalPage( ) { if ( filteredTotalPage <= 0 ) { return totalPage; } return filteredTotalPage; } /** * is in factory mode * * @return true, factory mode, false not in factory mode */ public boolean isInFactory( ) { return factoryMode; } /** * is in presentation mode. * * @return true, presentation mode, false otherwise */ public boolean isInPresentation( ) { return presentationMode; } /** * set the in factory mode * * @param mode * factory mode */ public void setFactoryMode( boolean mode ) { this.factoryMode = mode; } public boolean getFactoryMode( ) { return this.factoryMode; } /** * set in presentation mode * * @param mode * presentation mode */ public void setPresentationMode( boolean mode ) { this.presentationMode = mode; } private ULocale determineLocale( String locale ) { ULocale loc = null; if ( locale == null ) { if ( rlocale == null ) loc = ulocale; else loc = rlocale; } else { if ( USER_LOCALE.equals( locale ) ) loc = ulocale; else loc = new ULocale( locale ); } return loc; } /** * get a string formatter object * * @param value * string format * @return formatter object */ public StringFormatter getStringFormatter( String pattern ) { return getStringFormatter( pattern, null ); } public StringFormatter getStringFormatter( String pattern, String locale ) { String key = pattern + ":" + locale; StringFormatter fmt = stringFormatters.get( key ); if ( fmt == null ) { ULocale loc = determineLocale( locale ); fmt = new StringFormatter( pattern, loc ); stringFormatters.put( key, fmt ); } return fmt; } /** * get a number formatter object * * @param pattern * number format * @return formatter object */ public NumberFormatter getNumberFormatter( String pattern ) { return getNumberFormatter( pattern, null ); } public NumberFormatter getNumberFormatter( String pattern, String locale ) { String key = pattern + ":" + locale; NumberFormatter fmt = numberFormatters.get( key ); if ( fmt == null ) { ULocale loc = determineLocale( locale ); fmt = new NumberFormatter( pattern, loc ); numberFormatters.put( key, fmt ); } return fmt; } /** * get a date formatter object * * @param value * date format * @return formatter object */ public DateFormatter getDateFormatter( String pattern ) { return getDateFormatter( pattern, null ); } public DateFormatter getDateFormatter( String pattern, String locale ) { String key = pattern + ":" + locale; DateFormatter fmt = dateFormatters.get( key ); if ( fmt == null ) { ULocale loc = determineLocale( locale ); fmt = new DateFormatter( pattern, loc, timeZone ); dateFormatters.put( key, fmt ); } return fmt; } /** * set the executor used in the execution context * * @param executor */ public void setExecutor( IReportExecutor executor ) { this.executor = executor; } /** * get the executor used to execute the report * * @return report executor */ public IReportExecutor getExecutor( ) { return executor; } public TOCBuilder getTOCBuilder( ) { return tocBuilder; } public void setTOCBuilder( TOCBuilder builder ) { this.tocBuilder = builder; } /** * set the report document used in the context * * @param doc */ public void setReportDocument( IReportDocument doc ) { this.reportDoc = doc; } /** * get the report document used in the context. * * @return */ public IReportDocument getReportDocument( ) { return reportDoc; } public void setReportDocWriter( ReportDocumentWriter docWriter ) { this.docWriter = docWriter; } public ReportDocumentWriter getReportDocWriter( ) { return docWriter; } /** * @return Returns the action handler. */ public IHTMLActionHandler getActionHandler( ) { return renderOption.getActionHandler( ); } /** * @return Returns the action handler. */ public IHTMLImageHandler getImageHandler( ) { return renderOption.getImageHandler( ); } /** * return application class loader. The application class loader is used to * load the report item event handle and java classes called in the * javascript. * * @return class loader */ public ClassLoader getApplicationClassLoader( ) { if ( applicationClassLoader == null ) { closeClassLoader = true; applicationClassLoader = new ApplicationClassLoader( engine, runnable, appContext ); if ( scriptContext != null ) { scriptContext .setApplicationClassLoader( applicationClassLoader ); } } return applicationClassLoader; } public void setApplicationClassLoader( ClassLoader classLoader ) { if ( classLoader == null ) { throw new NullPointerException( "null classloader" ); } if ( closeClassLoader && applicationClassLoader instanceof ApplicationClassLoader ) { ( (ApplicationClassLoader) applicationClassLoader ).close( ); } closeClassLoader = false; this.applicationClassLoader = classLoader; if ( scriptContext != null ) { scriptContext.setApplicationClassLoader( applicationClassLoader ); } } /** * Set the cancel flag. */ public void cancel( ) { isCancelled = true; // cancel the dte's session if ( dataEngine != null ) { DataRequestSession session = dataEngine.getDTESession( ); if ( session != null ) { session.cancel( ); } } } public boolean isCanceled( ) { return isCancelled; } public void restart( ) throws EngineException { getDataEngine( ).getDTESession( ).restart( ); this.isCancelled = false; } public void setCancelOnError( boolean cancel ) { cancelOnError = cancel; } public void setDataSource( DocumentDataSource dataSource ) throws IOException { this.dataSource = dataSource; this.dataSource.open( ); } public DocumentDataSource getDataSource( ) { return dataSource; } public IBaseResultSet executeQuery( IBaseResultSet parent, IDataQueryDefinition query, Object queryOwner, boolean useCache ) throws BirtException { IDataEngine dataEngine = getDataEngine( ); return dataEngine.execute( parent, query, queryOwner, useCache ); } public IBaseResultSet getResultSet( ) { if ( rsets != null ) { return rsets[0]; } return null; } public void setResultSet( IBaseResultSet rset ) { if ( rset != null ) { if ( rsets != null && rsets.length == 1 && rsets[0] == rset ) { return; } setResultSets( new IBaseResultSet[]{rset} ); } else { setResultSets( null ); } } public IBaseResultSet[] getResultSets( ) { return rsets; } public void setResultSets( IBaseResultSet[] rsets ) { if ( this.rsets == rsets ) { return; } if ( rsets != null ) { this.rsets = rsets; if ( rsets[0] != null ) { try { DataAdapterUtil.registerDataObject( scriptContext, new ResultIteratorTree( rsets[0] ) ); } catch ( AdapterException e ) { log.log( Level.SEVERE, e.getLocalizedMessage( ), e ); } } } else { this.rsets = null; // FIXME: we should also remove the JSObject from scope // Scriptable scope = scriptContext.getRootScope( ); // DataAdapterUtil.registerJSObject( scope, // new ResultIteratorTree( rsets[0] ) ); } } private class ResultIteratorTree implements ILinkedResult { IBaseResultSet currentRset; int resultType = -1; public ResultIteratorTree( IBaseResultSet rset ) { this.currentRset = rset; if ( rset instanceof IQueryResultSet ) { resultType = ILinkedResult.TYPE_TABLE; } else if ( rset instanceof ICubeResultSet ) { resultType = ILinkedResult.TYPE_CUBE; } } public ILinkedResult getParent( ) { return new ResultIteratorTree( currentRset.getParent( ) ); } public Object getCurrentResult( ) { if ( resultType == ILinkedResult.TYPE_TABLE ) { return ( (IQueryResultSet) currentRset ).getResultIterator( ); } else if ( resultType == ILinkedResult.TYPE_CUBE ) { return ( (ICubeResultSet) currentRset ).getCubeCursor( ); } return null; } public int getCurrentResultType( ) { return resultType; } } public boolean hasErrors( ) { return !elementExceptions.isEmpty( ); } /** * Returns list or errors, the max count of the errors is * <code>MAX_ERRORS</code> * * @return error list which has max error size limited to * <code>MAX_ERRORS</code> */ public List getErrors( ) { List errors = this.getAllErrors( ); if ( errors.size( ) > MAX_ERRORS ) { errors = errors.subList( 0, MAX_ERRORS - 1 ); } return errors; } /** * Returns all errors. * * @return list of all the errors. */ public List getAllErrors( ) { return errors; } /** * @return the mAX_ERRORS */ public int getMaxErrors( ) { return MAX_ERRORS; } /** * @param max_errors * the mAX_ERRORS to set */ public void setMaxErrors( int maxErrors ) { MAX_ERRORS = maxErrors; } /** * to remember the current report item is in master page or not. */ boolean isExecutingMasterPage = false; /** * Since the data set in master page will be executed in each page and while * the data set in report body will only be executed once, we need to * remember the current report item is in master page or not. This will be * used to help store the executed resultSetID and load it to distinguish * them. */ public void setExecutingMasterPage( boolean isExecutingMasterPage ) { this.isExecutingMasterPage = isExecutingMasterPage; } public boolean isExecutingMasterPage( ) { return isExecutingMasterPage; } /** * Add a page break listener. * * @param listener * the page break listener. */ public void addPageBreakListener( IPageBreakListener listener ) { if ( pageBreakListeners == null ) { pageBreakListeners = new ArrayList( ); } pageBreakListeners.add( listener ); } /** * Notify page break listeners that page is broken. */ public void firePageBreakEvent( ) { if ( pageBreakListeners != null ) { for ( int i = 0; i < pageBreakListeners.size( ); i++ ) { ( (IPageBreakListener) pageBreakListeners.get( i ) ) .onPageBreak( ); } } } /** * Remove a page break listener. * * @param listener * the page break listener. */ public void removePageBreakListener( IPageBreakListener listener ) { if ( pageBreakListeners != null ) { pageBreakListeners.remove( listener ); } } public IEngineTask getEngineTask( ) { return task; } public Logger getLogger( ) { return log; } public void setLogger( Logger logger ) { log = logger; } protected ExecutionPolicy executionPolicy; public void optimizeExecution( ) { if ( ( task != null ) && ( task.getTaskType( ) == IEngineTask.TASK_RUN ) && !isFixedLayout ) { String[] engineExts = getEngineExtensions( ); if ( engineExts == null || engineExts.length == 0 ) { executionPolicy = new ExecutionOptimize( ) .optimize( getReport( ) ); } } } public ExecutionPolicy getExecutionPolicy( ) { return executionPolicy; } public Report getReport( ) { if ( reportIR != null ) { return reportIR; } if ( runnable != null ) { reportIR = new ReportParser( ).parse( (ReportDesignHandle) runnable .getDesignHandle( ) ); setupFromReport( ); } return reportIR; } public void setReport( Report reportIR ) { this.reportIR = reportIR; setupFromReport( ); } protected void setupFromReport( ) { if ( reportIR == null ) return; String locale = reportIR.getLocale( ); if ( locale != null ) { rlocale = new ULocale( locale ); this.getScriptContext( ).setLocale( rlocale.toLocale( ) ); } } public URL getResource( String resourceName ) { if ( getDesign( ) != null ) { return getDesign( ).findResource( resourceName, IResourceLocator.OTHERS, appContext ); } return null; } public ExtendedItemManager getExtendedItemManager( ) { return extendedItemManager; } public EngineExtensionManager getEngineExtensionManager( ) { return engineExtensionManager; } public void setMaxRowsPerQuery( int maxRows ) { if ( maxRows >= 0 ) { maxRowsPerQuery = maxRows; } } public int getMaxRowsPerQuery( ) { return maxRowsPerQuery; } private String[] engineExts; public String[] getEngineExtensions( ) { if ( engineExts != null ) { return engineExts; } engineExts = engine.getEngineExtensions( runnable ); if ( engineExts == null ) { engineExts = new String[]{}; } return engineExts; } private boolean enableProgreesiveViewing = true; public void enableProgressiveViewing( boolean enabled ) { enableProgreesiveViewing = enabled; } public boolean isProgressiveViewingEnable( ) { return enableProgreesiveViewing; } public EventHandlerManager getEventHandlerManager( ) { return eventHandlerManager; } public void setProgressMonitor( IProgressMonitor monitor ) { progressMonitor = new ProgressMonitorProxy( monitor ); } public IProgressMonitor getProgressMonitor( ) { if ( progressMonitor == null ) { progressMonitor = new ProgressMonitorProxy( null ); } return progressMonitor; } public boolean needOutputResultSet( ) { return needOutputResultSet; } public void setNeedOutputResultSet( boolean needOutputResultSet ) { this.needOutputResultSet = needOutputResultSet; } public Object getPageVariable( String name ) { if ( "totalPage".equals( name ) ) { return Long.valueOf( totalPage ); } if ( "pageNumber".equals( name ) ) { return Long.valueOf( totalPage ); } PageVariable var = pageVariables.get( name ); if ( var != null ) { return var.getValue( ); } return null; } public void setPageVariable( String name, Object value ) { PageVariable var = pageVariables.get( name ); if ( var != null ) { var.setValue( value ); } // lazy add special page variables else if ( IReportContext.PAGE_VAR_PAGE_LABEL.equals( name ) ) { addPageVariable( new PageVariable( IReportContext.PAGE_VAR_PAGE_LABEL, PageVariable.SCOPE_PAGE, value ) ); } } public void addPageVariables( Collection<PageVariable> vars ) { for ( PageVariable var : vars ) { pageVariables.put( var.getName( ), var ); } } public Collection<PageVariable> getPageVariables( ) { return pageVariables.values( ); } public void addPageVariable( PageVariable var ) { pageVariables.put( var.getName( ), var ); } public boolean isFixedLayout( ) { return isFixedLayout; } public void setFixedLayout( boolean isFixedLayout ) { this.isFixedLayout = isFixedLayout; } public int getTaskType( ) { return task.getTaskType( ); } private IScriptContext getRootContext( ) { ScriptContext result = scriptContext; while ( result.getParent( ) != null ) { result = result.getParent( ); } return result; } public boolean needRefreshData() { return this.refreshData; } public void setRefreshData(boolean refreshData) { this.refreshData = refreshData; } }
package org.ensembl.healthcheck; import org.ensembl.healthcheck.util.*; import org.ensembl.healthcheck.testcase.*; import java.io.*; import java.sql.*; import java.util.*; import java.util.logging.*; import java.util.regex.*; /** * Subclass of TestRunner intended for running tests from the command line. */ public class TextTestRunner extends TestRunner implements Reporter { private static String version = "$Id$"; private boolean forceDatabases = false; private boolean debug = false; private boolean useSchemaInfo = true; private boolean rebuildSchemaInfo = false; public Vector outputBuffer ; private String lastDatabase = ""; /** * Command-line run method. * @param args The command-line arguments. */ public static void main(String[] args) { TextTestRunner ttr = new TextTestRunner(); System.out.println(ttr.getVersion()); ttr.parseCommandLine(args); ttr.outputBuffer = new Vector(); ttr.setupLogging(); ttr.readPropertiesFile(); if (ttr.useSchemaInfo) { ttr.buildSchemaList(true); } //if (ttr.useSchemaInfo && !ttr.rebuildSchemaInfo) { // if buildSchemaList has been called, SchemaManager will already have been populated // ttr.readStoredSchemaInfo(); ReportManager.setReporter(ttr); ttr.runAllTests(ttr.findAllTests(), ttr.forceDatabases); ConnectionPool.closeAll(); } // main private void printUsage() { System.out.println("\nUsage: TextTestRunner {-d regexp} {-force} {-output none|problem|correct|summary|info|all} {group1} {group2} ...\n"); System.out.println("Options:"); System.out.println(" -d regexp Use the given regular expression to decide which databases to use."); System.out.println(" -force Run the named tests on the databases matched by -d, without "); System.out.println(" taking into account the regular expressions built into the tests themselves."); System.out.println(" -h This message."); System.out.println(" -output level Set output level; level can be one of "); System.out.println(" none nothing is printed"); System.out.println(" problem only problems are reported"); System.out.println(" correct only correct results (and problems) are reported"); System.out.println(" summary only summary info (and problems, and correct reports) are reported"); System.out.println(" info info (and problem, correct, summary) messages reported"); System.out.println(" all everything is printed"); System.out.println(" -config file Read config from file (in ensj-healthcheck dir) rather than database.properties"); System.out.println(" -debug Print debugging info (for developers only)"); System.out.println(" -repair If appropriate, carry out repair methods on test cases that support it"); System.out.println(" -showrepair Like -repair, but the repair is NOT carried out, just reported."); System.out.println(" -noschemainfo Do not cache schema info at startup. Quicker, but may cause some tests not to work. Use with caution."); System.out.println(" -refreshschemas Rebuild the stored schema info; this is rather slow as every schema must be examined, but should be used when a schema structure change has occurred."); System.out.println(" group1 Names of groups of test cases to run."); System.out.println(" Note each test case is in a group of its own with the name of the test case."); System.out.println(" This allows individual tests to be run if required."); System.out.println(""); System.out.println("If no tests or test groups are specified, and a database regular expression is given with -d, the matching databases are shown. "); System.out.println(""); System.out.println("Currently available tests:"); List tests = findAllTests(); Collections.sort(tests, new TestComparator()); Iterator it = tests.iterator(); while (it.hasNext()) { EnsTestCase test = (EnsTestCase)it.next(); System.out.print(test.getShortTestName() + " "); } System.out.println(""); } /** * Return the CVS version string for this class. * @return The version. */ public String getVersion() { // strip off first and last few chars of version since these are only used by CVS return version.substring(5, version.length() - 2); } private void parseCommandLine(String[] args) { if (args.length == 0) { printUsage(); System.exit(1); } else { for (int i = 0; i < args.length; i++) { if (args[i].equals("-h")) { printUsage(); System.exit(0); } else if (args[i].equals("-output")) { setOutputLevel(args[++i]); // System.out.println("Set output level to " + outputLevel); } else if (args[i].equals("-debug")) { debug = true; } else if (args[i].equals("-repair")) { doRepair = true; } else if (args[i].equals("-showrepair")) { showRepair = true; } else if (args[i].equals("-d")) { i++; preFilterRegexp = args[i]; // System.out.println("Will pre-filter database names on " + preFilterRegexp); } else if (args[i].equals("-force")) { forceDatabases = true; // System.out.println("Will use ONLY databases specified by -d"); } else if (args[i].equals("-noschemainfo")) { useSchemaInfo = false; // System.out.println("Will NOT read schema info at startup"); } else if (args[i].equals("-refreshschemas")) { rebuildSchemaInfo = true; // System.out.println("Will rebuild and store schema info at startup"); } else if (args[i].equals("-config")) { i++; propertiesFileName = args[i]; // System.out.println("Will read properties from " + propertiesFileName); } else { groupsToRun.add(args[i]); // System.out.println("Will run tests in group " + args[i]); } } if (forceDatabases && (preFilterRegexp == null)) { System.err.println("You have requested -force but not specified a database name regular expression with -d"); System.exit(1); } } } // parseCommandLine private void setupLogging() { logger.setUseParentHandlers(false);// stop parent logger getting the message Handler myHandler = new MyStreamHandler(System.out, new LogFormatter()); logger.addHandler(myHandler); logger.setLevel(Level.WARNING);// default - only print important messages if (debug) { logger.setLevel(Level.FINEST); } //logger.info("Set logging level to " + logger.getLevel().getName()); } // setupLogging public void message( ReportLine reportLine ) { String level = "ODD "; System.out.print( "." ); System.out.flush(); if( reportLine.getLevel() < outputLevel ) { return; } if( ! reportLine.getDatabaseName().equals( lastDatabase )) { outputBuffer.add( " " + reportLine.getDatabaseName() ); lastDatabase = reportLine.getDatabaseName(); } switch( reportLine.getLevel() ) { case( ReportLine.PROBLEM ) : level = "PROBLEM"; break; case( ReportLine.WARNING ) : level = "WARNING"; break; case( ReportLine.INFO ) : level = "INFO "; break; case( ReportLine.CORRECT ) : level = "CORRECT"; break; } outputBuffer.add( " " + level + ": " + lineBreakString( reportLine.getMessage(), 65, " " )); } public void startTestCase( EnsTestCase testCase ) { String name; name = testCase.getClass().getName(); name = name.substring( name.lastIndexOf( "." ) + 1 ); System.out.print( name + " " ); System.out.flush(); } public void finishTestCase( EnsTestCase testCase, TestResult result ) { if (result.getResult()) { System.out.println(" PASSED"); } else { System.out.println(" FAILED"); } lastDatabase = ""; Iterator it = outputBuffer.iterator(); while( it.hasNext() ) { System.out.println( (String) it.next() ); } outputBuffer.clear(); } private String lineBreakString( String mesg, int maxLen, String indent ) { if( mesg.length() <= maxLen ) { return mesg; } int lastSpace = mesg.lastIndexOf( " ", maxLen ); if( lastSpace > 15 ) { return mesg.substring(0, lastSpace) + "\n" + indent + lineBreakString(mesg.substring(lastSpace+1), maxLen, indent); } else { return mesg.substring(0, maxLen) + "\n" + indent + lineBreakString(mesg.substring(maxLen), maxLen, indent); } } } // TextTestRunner
package org.sakaiproject.entitybroker.impl.collector; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.entitybroker.collector.AutoRegister; import org.sakaiproject.entitybroker.collector.BeanCollector; import org.sakaiproject.entitybroker.collector.OrderedBean; import org.sakaiproject.entitybroker.collector.BeanMapCollector; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; /** * This will collect the autoregistered beans and place them into all the locations which requested them * * @author Aaron Zeckoski (aaron@caret.cam.ac.uk) */ public class BeanCollectorAutoRegistrar implements ApplicationListener, ApplicationContextAware, InitializingBean { private static Log log = LogFactory.getLog(BeanCollectorAutoRegistrar.class); private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void onApplicationEvent(ApplicationEvent event) { // We do not actually respond to any events, purpose is to time initialisation only. } private Set<String> autoRegistered; public void init() { String[] autobeans = applicationContext.getBeanNamesForType(AutoRegister.class, false, false); autoRegistered = new HashSet<String>(); for (int i = 0; i < autobeans.length; i++) { autoRegistered.add(autobeans[i]); } } public void afterPropertiesSet() throws Exception { log.debug("setAC: " + applicationContext.getDisplayName()); ConfigurableApplicationContext cac = (ConfigurableApplicationContext) applicationContext; ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) cac.getBeanFactory(); cbf.addBeanPostProcessor(new BeanPostProcessor() { @SuppressWarnings("unchecked") public Object postProcessBeforeInitialization(Object bean, String beanName) { if (bean instanceof BeanCollector<?>) { BeanCollector<Object> bc = (BeanCollector<Object>) bean; Class<?> c = bc.getCollectedType(); if (c == null) { throw new IllegalArgumentException("collected type cannot be null"); } List<Object> l = getAutoRegisteredBeansOfType(c); logCollectedBeanInsertion(beanName, c.getName(), l); bc.setCollectedBeans(l); } else if (bean instanceof BeanMapCollector) { BeanMapCollector bc = (BeanMapCollector) bean; Class<?>[] cArray = bc.getCollectedTypes(); if (cArray == null) { throw new IllegalArgumentException("collected types cannot be null"); } Map<Class<?>, List<?>> collectedBeans = new HashMap<Class<?>, List<?>>(); for (int i = 0; i < cArray.length; i++) { List<Object> l = getAutoRegisteredBeansOfType(cArray[i]); logCollectedBeanInsertion(beanName, cArray[i].getName(), l); collectedBeans.put(cArray[i], l); } bc.setCollectedBeansMap(collectedBeans); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; } }); } /** * Get all autoregistered beans of a specific type * @param c the class type * @return a list of the matching beans */ private List<Object> getAutoRegisteredBeansOfType(Class<?> c) { String[] autobeans = applicationContext.getBeanNamesForType(c, false, false); List<Object> l = new ArrayList<Object>(); for (String autobean : autobeans) { if (autoRegistered.contains(autobean)) { Object bean = applicationContext.getBean(autobean); l.add(bean); } } Collections.sort(l, new OrderComparator()); return l; } /** * Generate a log message about the collected insertion * @param beanName the name of the bean getting collected beans inserted into it * @param l the list of beans that were inserted */ private void logCollectedBeanInsertion(String beanName, String beanType, List<Object> l) { StringBuilder registeredBeans = new StringBuilder(); registeredBeans.append("["); for (int i = 0; i < l.size(); i++) { if (i > 0) { registeredBeans.append(","); } registeredBeans.append(l.get(i).getClass().getName()); } registeredBeans.append("]"); log.info("Set collected beans of type ("+beanType+") on bean ("+beanName+") to ("+l.size()+") " + registeredBeans.toString()); } /** * Comparator to order the collected beans based on order or use default order otherwise * * @author Aaron Zeckoski (aaron@caret.cam.ac.uk) */ private static class OrderComparator implements Comparator<Object> { public int compare(Object arg0, Object arg1) { if (arg0 instanceof OrderedBean && arg1 instanceof OrderedBean) { return ((OrderedBean)arg0).getOrder() - ((OrderedBean)arg1).getOrder(); } else if (arg0 instanceof OrderedBean) { return -1; } else if (arg1 instanceof OrderedBean) { return 1; } else { return 0; } } } }
package org.jgroups.protocols.jzookeeper; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Timer; import java.util.TimerTask; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.stack.Protocol; import org.jgroups.util.MessageBatch; public class MMZAB extends Protocol { protected final AtomicLong zxid=new AtomicLong(0); private ExecutorService executor; protected Address local_addr; protected volatile Address leader; protected volatile View view; protected volatile boolean is_leader=false; private List<Address> zabMembers = Collections.synchronizedList(new ArrayList<Address>()); private long lastZxidProposed=0, lastZxidCommitted=0; private final Set<MessageId> requestQueue =Collections.synchronizedSet(new HashSet<MessageId>()); private Map<Long, ZABHeader> queuedCommitMessage = new HashMap<Long, ZABHeader>(); private final LinkedBlockingQueue<ZABHeader> queuedMessages = new LinkedBlockingQueue<ZABHeader>(); private ConcurrentMap<Long, Proposal> outstandingProposals = new ConcurrentHashMap<Long, Proposal>(); private final Map<Long, ZABHeader> queuedProposalMessage = Collections.synchronizedMap(new HashMap<Long, ZABHeader>()); private final Map<MessageId, Message> messageStore = Collections.synchronizedMap(new HashMap<MessageId, Message>()); Calendar cal = Calendar.getInstance(); protected volatile boolean running=true; private int index=-1; //private Map<Long, Boolean> notACK = new HashMap<Long, Boolean>(); SortedSet<Long> wantCommit = new TreeSet<Long>(); private Timer _timer; private boolean startSending = false; private boolean makeAllFollowersAck = false; private long lastRequestRecieved=0; private long laslAckRecieved=0; private volatile long lastTimeQueueChecked=0; private boolean recievedFirstRequest = false; public MMZAB(){ } @ManagedAttribute public boolean isleaderinator() {return is_leader;} public Address getleaderinator() {return leader;} public Address getLocalAddress() {return local_addr;} @Override public void start() throws Exception { super.start(); log.setLevel("trace"); //if (zabMembers.contains(local_addr)){ running=true; executor = Executors.newSingleThreadExecutor(); executor.execute(new FollowerMessageHandler(this.id)); } // For sending Dummy request // class FinishTask extends TimerTask { // private short idd; // public FinishTask(short id){ // this.idd = id; // @Override // public void run() { // //this can be used to measure rate of each thread // //at this moment, it is not necessary // long currentTime = System.currentTimeMillis(); //log.info("cccccccall FinishTask diff time "+(currentTime - timeDiff)); // if (outstandingProposals.isEmpty()){ // this.cancel(); // return; // if ((currentTime - lastRequestRecieved) > 1000){ // this.cancel(); // return; // if (!outstandingProposals.isEmpty() && (currentTime - lastRequestRecieved) >500) { // this.cancel(); // log.info("Comit Alllllllllllllllllllllllllllllllllll"); // ZABHeader commitPending = new ZABHeader(ZABHeader.COMMITOUTSTANDINGREQUESTS); // for (Address address : zabMembers) { // Message commitALL = new Message(address).putHeader(this.idd, commitPending); // down_prot.down(new Event(Event.MSG, commitALL)); // makeAllFollowersAck=true; // //startSending=false; @Override public void stop() { running=false; executor.shutdown(); super.stop(); } public Object down(Event evt) { ZABHeader hdr; switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); // hdr=(ZABHeader)msg.getHeader(this.id); handleClientRequest(msg); return null; // don't pass down case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; } return down_prot.down(evt); } public Object up(Event evt) { Message msg = null; ZABHeader hdr; switch(evt.getType()) { case Event.MSG: msg=(Message)evt.getArg(); hdr=(ZABHeader)msg.getHeader(this.id); if(hdr == null){ break; // pass up } switch(hdr.getType()) { case ZABHeader.START_SENDING: // if(zabMembers.contains(local_addr)){ // //log.info("$$$$$$$$$$$$$$$$$ initiale startSending and makeAllFollowersAck = false"); // startSending=false; // makeAllFollowersAck=false; // else return up_prot.up(new Event(Event.MSG, msg)); case ZABHeader.REQUEST: forwardToLeader(msg); break; case ZABHeader.FORWARD: lastRequestRecieved=System.currentTimeMillis(); recievedFirstRequest = true; // if (!startSending){ // _timer = new Timer(); // _timer.scheduleAtFixedRate(new FinishTask(this.id), 200, 200); // startSending=true; //lastRequestRecieved = System.currentTimeMillis(); queuedMessages.add(hdr); break; case ZABHeader.PROPOSAL: if (!is_leader){ sendACK(msg); } break; case ZABHeader.ACK: processACK(msg, msg.getSrc()); break; case ZABHeader.COMMITOUTSTANDINGREQUESTS: //makeAllFollowersAck=true; commitPendingRequest(); //startSending = false; break; case ZABHeader.RESPONSE: handleOrderingResponse(hdr); } return null; case Event.VIEW_CHANGE: handleViewChange((View)evt.getArg()); break; } return up_prot.up(evt); } public void up(MessageBatch batch) { for(Message msg: batch) { if(msg.isFlagSet(Message.Flag.NO_TOTAL_ORDER) || msg.isFlagSet(Message.Flag.OOB) || msg.getHeader(id) == null) continue; batch.remove(msg); try { up(new Event(Event.MSG, msg)); } catch(Throwable t) { log.error("failed passing up message", t); } } if(!batch.isEmpty()) up_prot.up(batch); } private void handleClientRequest(Message message){ ZABHeader clientHeader = ((ZABHeader) message.getHeader(this.id)); if (clientHeader!=null && clientHeader.getType() == ZABHeader.START_SENDING){ for (Address client : view.getMembers()){ if (log.isInfoEnabled()) log.info("Address to check " + client); if (!zabMembers.contains(client)){ if (log.isInfoEnabled()) log.info("Address to check is not zab Members, will send start request to" + client+ " "+ getCurrentTimeStamp()); message.setDest(client); down_prot.down(new Event(Event.MSG, message)); } } } else if(!clientHeader.getMessageId().equals(null)){ Address destination = null; messageStore.put(clientHeader.getMessageId(), message); ZABHeader hdrReq=new ZABHeader(ZABHeader.REQUEST, clientHeader.getMessageId()); ++index; if (index>2) index=0; destination = zabMembers.get(index); Message requestMessage = new Message(destination).putHeader(this.id, hdrReq); down_prot.down(new Event(Event.MSG, requestMessage)); } } private void handleViewChange(View v) { this.view = v; List<Address> mbrs=v.getMembers(); leader=mbrs.get(0); if (leader.equals(local_addr)){ is_leader = true; } if (mbrs.size() == 3){ zabMembers.addAll(v.getMembers()); } if (mbrs.size() > 3 && zabMembers.isEmpty()){ for (int i = 0; i < 3; i++) { zabMembers.add(mbrs.get(i)); } } if(mbrs.isEmpty()) return; if(view == null || view.compareTo(v) < 0) view=v; else return; } private long getNewZxid(){ return zxid.incrementAndGet(); } private void forwardToLeader(Message msg) { ZABHeader hdrReq = (ZABHeader) msg.getHeader(this.id); requestQueue.add(hdrReq.getMessageId()); if (is_leader){ queuedMessages.add((ZABHeader)msg.getHeader(this.id)); } else{ forward(msg); } } private void forward(Message msg) { Address target=leader; ZABHeader hdrReq = (ZABHeader) msg.getHeader(this.id); if(target == null) return; try { ZABHeader hdr=new ZABHeader(ZABHeader.FORWARD, hdrReq.getMessageId()); Message forward_msg=new Message(target).putHeader(this.id,hdr); down_prot.down(new Event(Event.MSG, forward_msg)); } catch(Exception ex) { log.error("failed forwarding message to " + msg, ex); } } private void sendACK(Message msg){ Proposal p; if (msg == null ) return; ZABHeader hdr = (ZABHeader) msg.getHeader(this.id); if (hdr == null) return; // if (hdr.getZxid() != lastZxidProposed + 1){ // log.info("Got zxid 0x" // + Long.toHexString(hdr.getZxid()) // + " expected 0x" // + Long.toHexString(lastZxidProposed + 1)); //log.info("[" + local_addr + "] " + "follower, sending ack (sendAck) at "+getCurrentTimeStamp()); // if (!(outstandingProposals.containsKey(hdr.getZxid()))){ p = new Proposal(); p.AckCount++; // Ack from leader p.setZxid(hdr.getZxid()); outstandingProposals.put(hdr.getZxid(), p); lastZxidProposed = hdr.getZxid(); queuedProposalMessage.put(hdr.getZxid(), hdr); // else{ // p = outstandingProposals.get(hdr.getZxid()); // p.AckCount++; // Ack from leader // queuedProposalMessage.put(hdr.getZxid(), hdr); // lastZxidProposed = hdr.getZxid(); if (ZUtil.SendAckOrNoSend()){// || makeAllFollowersAck) { // log.info("[" // + local_addr // + "follower, sending ack if (ZUtil.SendAckOrNoSend()) (sendAck) at "+getCurrentTimeStamp()); //if(makeAllFollowersAck) ZABHeader hdrACK = new ZABHeader(ZABHeader.ACK, hdr.getZxid()); Message ackMessage = new Message().putHeader(this.id, hdrACK); log.info("Sending ACK for " + hdr.getZxid()+" "+getCurrentTimeStamp()+ " " +getCurrentTimeStamp()); //notACK.put(hdr.getZxid(), true); try{ for (Address address : zabMembers) { Message cpy = ackMessage.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } }catch(Exception ex) { log.error("failed proposing message to members"); } } else{ log.info("Not Sending ACK for " + hdr.getZxid()+" "+getCurrentTimeStamp()+ " " +getCurrentTimeStamp()); //notACK.put(hdr.getZxid(), false); } } private synchronized void processACK(Message msgACK, Address sender){ laslAckRecieved = System.currentTimeMillis(); Proposal p = null; ZABHeader hdr = (ZABHeader) msgACK.getHeader(this.id); long ackZxid = hdr.getZxid(); log.info("Reciving Ack zxid " + ackZxid + " sender " + sender+ " " +getCurrentTimeStamp()); // if (!(outstandingProposals.containsKey(hdr.getZxid())) && (lastZxidProposed < hdr.getZxid())){ // p = new Proposal(); // outstandingProposals.put(hdr.getZxid(), p); // queuedProposalMessage.put(hdr.getZxid(), hdr); // lastZxidProposed = hdr.getZxid(); //log.info("recieved ack "+ackZxid+" "+ sender + " "+getCurrentTimeStamp()); if (lastZxidCommitted >= ackZxid) { if (log.isDebugEnabled()) { log.info("proposal has already been committed, pzxid: 0x{} zxid: 0x{}", lastZxidCommitted, ackZxid); } return; } p = outstandingProposals.get(ackZxid); if (p == null) { // Long.toHexString(ackZxid), sender); return; } p.AckCount++; //if (log.isDebugEnabled()) { // log.debug("Count for zxid: " + // Long.toHexString(ackZxid)+" = "+ p.getAckCount()); if (isQuorum(p.getAckCount())) { if (ackZxid == lastZxidCommitted+1){ commit(ackZxid); outstandingProposals.remove(ackZxid); //if (isFirstZxid(ackZxid)) { //log.info(" if (isQuorum(p.getAckCount())) commiting " + ackZxid); //commit(ackZxid); //outstandingProposals.remove(ackZxid); } else { long zxidCommiting = lastZxidCommitted +1; for (long z = zxidCommiting; z < ackZxid+1; z++){ commit(z); outstandingProposals.remove(z); } } //for (Proposal proposalPending : outstandingProposals.values()) { //if (proposalPending.getZxid() < p.getZxid()) { //log.info(" inside proposalPending.getZxid() < p.getZxid() " //+ proposalPending.getZxid() + " " + p.getZxid()); //wantCommit.add(proposalPending.getZxid()); //log.info(" wantCommit size " + wantCommit.size()); //wantCommit.add(ackZxid); // log.info(" processAck Commiting allwantCommit) commiting " + wantCommit + " before "+ackZxid); // for (long zx : wantCommit) { // if (isFirstZxid(zx)) { // commit(zx); // //log.info(" for (long zx : wantCommit) commiting " + zx); // outstandingProposals.remove(zx); // } else // break; // wantCommit.clear(); } } private void commitPendingRequest(){ if (!outstandingProposals.isEmpty()){ for (Proposal proposalPending : outstandingProposals.values()){ wantCommit.add(proposalPending.getZxid()); } //log.info("Before Finished outstandingProposals "+outstandingProposals.keySet()); //log.info("Before Finished wantCommit "+wantCommit); log.info("Commiting all "+wantCommit); for (long zx:wantCommit){ log.info("Commiting "+outstandingProposals.keySet()); commit(zx); outstandingProposals.remove(zx); } // log.info("After Finished outstandingProposals "+outstandingProposals.keySet()); // log.info("After Finished wantCommit "+wantCommit); wantCommit.clear(); } } private void commit(long zxid){ //log.info("[" + local_addr + "] "+"About to commit the request (commit) for zxid="+zxid+" "+getCurrentTimeStamp()); ZABHeader hdrOrginal = null; synchronized(this){ lastZxidCommitted = zxid; } hdrOrginal = queuedProposalMessage.get(zxid); if (hdrOrginal == null){ if (log.isInfoEnabled()) log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!! Header is null (commit)"+ hdrOrginal + " for zxid "+zxid); return; } MessageId mid = hdrOrginal.getMessageId(); // if (mid == null){ // log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!! Message is null (commit)"+ mid + " for zxid "+zxid); // return; ZABHeader hdrCommit = new ZABHeader(ZABHeader.COMMIT, zxid, mid); Message commitMessage = new Message().putHeader(this.id, hdrCommit); commitMessage.src(local_addr); deliver(commitMessage); } private void deliver(Message toDeliver){ ZABHeader hdr = (ZABHeader) toDeliver.getHeader(this.id); long zxid = hdr.getZxid(); //log.info("[" + local_addr + "] "+ " delivering message (deliver) for zxid=" + hdr.getZxid()+" "+getCurrentTimeStamp()); ZABHeader hdrOrginal = queuedProposalMessage.remove(zxid); if (hdrOrginal == null) { if (log.isInfoEnabled()) log.info("$$$$$$$$$$$$$$$$$$$$$ Header is null (deliver)" + hdrOrginal + " for zxid " + hdr.getZxid()); return; } queuedCommitMessage.put(zxid, hdrOrginal); //if (log.isInfoEnabled()) log.info("queuedCommitMessage size = " + queuedCommitMessage.size() + " zxid "+zxid); if (requestQueue.contains(hdrOrginal.getMessageId())){ //log.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!I am the zab request receiver, going to send response back to " + hdrOrginal.getMessageId().getAddress()); ZABHeader hdrResponse = new ZABHeader(ZABHeader.RESPONSE, zxid, hdrOrginal.getMessageId()); Message msgResponse = new Message(hdrOrginal.getMessageId().getAddress()).putHeader(this.id, hdrResponse); down_prot.down(new Event(Event.MSG, msgResponse)); } } private void handleOrderingResponse(ZABHeader hdrResponse) { //log.info("[" + local_addr + "] "+ "recieved response message (handleOrderingResponse) for zxid=" + hdrResponse.getZxid()+" "+getCurrentTimeStamp()); Message message = messageStore.get(hdrResponse.getMessageId()); message.putHeader(this.id, hdrResponse); //log.info("[ " + local_addr + "] " + "Received zab ordered for request " + message + " its zxid = " + hdrResponse); up_prot.up(new Event(Event.MSG, message)); } private boolean isQuorum(int majority){ //log.info(" acks = " + majority + " majority "+ ((zabMembers.size()/2)+1)); return majority >= ((zabMembers.size()/2) + 1)? true : false; } private boolean isFirstZxid(long zxid){ int i =0; boolean find = true; for (long z : outstandingProposals.keySet()){ //log.info("Inside isFirstZxid loop" + z + " i =" + (++i)); if (z < zxid){ find = false; break; } } return find; } private String getCurrentTimeStamp(){ long timestamp = new Date().getTime(); cal.setTimeInMillis(timestamp); String timeString = new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime()); return timeString; } final class FollowerMessageHandler implements Runnable { private short id; public FollowerMessageHandler(short id){ this.id = id; } @Override public void run() { handleRequests(); } /** * create a proposal and send it out to all the members * * @param message */ private void handleRequests() { ZABHeader hdrReq = null; long currentTime = 0; while (running) { if (queuedMessages.peek()!=null) lastTimeQueueChecked = System.currentTimeMillis(); currentTime = System.currentTimeMillis(); if (queuedMessages.peek()==null){ log.info("lastTimeQueueChecked = " + lastTimeQueueChecked + " diff = " + (currentTime - lastTimeQueueChecked) ); log.info("laslAckRecieved = " + laslAckRecieved + " diff = " + (currentTime - laslAckRecieved) ); log.info("lastRequestRecieved = " + lastRequestRecieved + " diff = " + (currentTime - lastRequestRecieved) ); log.info("outstandingProposals size = " + outstandingProposals.size()); log.info("queuedMessages size = " + queuedMessages.size()); } if (recievedFirstRequest && (currentTime - lastTimeQueueChecked) > 20 && (currentTime -laslAckRecieved) > 20 && (currentTime - lastRequestRecieved) > 20 && !outstandingProposals.isEmpty()){ //if (log.isInfoEnabled()){ log.info("Dummy is sending ************ " + outstandingProposals.size()); ZABHeader commitPending = new ZABHeader(ZABHeader.COMMITOUTSTANDINGREQUESTS); for (Address address : zabMembers) { Message commitALL = new Message(address).putHeader(this.id, commitPending); down_prot.down(new Event(Event.MSG, commitALL)); } } try { hdrReq=queuedMessages.take(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } long new_zxid = getNewZxid(); ZABHeader hdrProposal = new ZABHeader(ZABHeader.PROPOSAL, new_zxid, hdrReq.getMessageId()); Message ProposalMessage=new Message().putHeader(this.id, hdrProposal); ProposalMessage.setSrc(local_addr); Proposal p = new Proposal(); p.setMessageId(hdrReq.getMessageId()); p.setZxid(new_zxid); p.AckCount++; lastZxidProposed=new_zxid; //log.info("Zxid count for zxid = " + new_zxid + " count = " +p.AckCount+" "+getCurrentTimeStamp()); outstandingProposals.put(new_zxid, p); queuedProposalMessage.put(new_zxid, hdrProposal); try{ //log.info("[" + local_addr + "] "+" prepar for proposal (run) for zxid="+new_zxid+" "+getCurrentTimeStamp()); //log.info("Leader is about to sent a proposal " + ProposalMessage); for (Address address : zabMembers) { if(address.equals(leader)) continue; Message cpy = ProposalMessage.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } }catch(Exception ex) { log.error("failed proposing message to members"); } } } } }
package org.eclipse.che.ide.actions; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.OperationException; import org.eclipse.che.api.promises.client.PromiseError; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.ide.CoreLocalizationConstant; import org.eclipse.che.ide.Resources; import org.eclipse.che.ide.api.action.AbstractPerspectiveAction; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.dialogs.DialogFactory; import org.eclipse.che.ide.api.dialogs.InputCallback; import org.eclipse.che.ide.api.dialogs.InputDialog; import org.eclipse.che.ide.api.dialogs.InputValidator; import org.eclipse.che.ide.api.editor.EditorAgent; import org.eclipse.che.ide.api.editor.EditorPartPresenter; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.resources.RenamingSupport; import org.eclipse.che.ide.api.resources.Resource; import org.eclipse.che.ide.resource.Path; import org.eclipse.che.ide.util.NameUtils; import javax.validation.constraints.NotNull; import java.util.List; import java.util.Set; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singletonList; import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.EMERGE_MODE; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL; import static org.eclipse.che.ide.api.resources.Resource.FILE; import static org.eclipse.che.ide.api.resources.Resource.FOLDER; import static org.eclipse.che.ide.api.resources.Resource.PROJECT; import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID; /** * Rename selected resource in the application context. * * @author Artem Zatsarynnyi * @author Vlad Zhukovskyi * @see AppContext#getResource() */ @Singleton public class RenameItemAction extends AbstractPerspectiveAction { private final CoreLocalizationConstant localization; private final Set<RenamingSupport> renamingSupport; private final EditorAgent editorAgent; private final NotificationManager notificationManager; private final DialogFactory dialogFactory; private final AppContext appContext; @Inject public RenameItemAction(Resources resources, CoreLocalizationConstant localization, Set<RenamingSupport> renamingSupport, EditorAgent editorAgent, NotificationManager notificationManager, DialogFactory dialogFactory, AppContext appContext) { super(singletonList(PROJECT_PERSPECTIVE_ID), localization.renameItemActionText(), localization.renameItemActionDescription(), null, resources.rename()); this.localization = localization; this.renamingSupport = renamingSupport; this.editorAgent = editorAgent; this.notificationManager = notificationManager; this.dialogFactory = dialogFactory; this.appContext = appContext; } /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { final Resource resource = appContext.getResource(); checkState(resource != null, "Null resource occurred"); final String resourceName = resource.getName(); final int selectionLength = resourceName.indexOf('.') >= 0 ? resourceName.lastIndexOf('.') : resourceName.length(); final InputValidator validator; final String dialogTitle; if (resource.getResourceType() == FILE) { validator = new FileNameValidator(resourceName); dialogTitle = localization.renameFileDialogTitle(resourceName); } else if (resource.getResourceType() == FOLDER) { validator = new FolderNameValidator(resourceName); dialogTitle = localization.renameFolderDialogTitle(resourceName); } else if (resource.getResourceType() == PROJECT) { validator = new ProjectNameValidator(resourceName); dialogTitle = localization.renameProjectDialogTitle(resourceName); } else { throw new IllegalStateException("Not a resource"); } final InputCallback inputCallback = new InputCallback() { @Override public void accepted(final String value) { //we shouldn't perform renaming file with the same name if (!value.trim().equals(resourceName)) { closeRelatedEditors(resource); final Path destination = resource.getLocation().parent().append(value); resource.move(destination).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError arg) throws OperationException { notificationManager.notify("", arg.getMessage(), FAIL, EMERGE_MODE); } }); } } }; InputDialog inputDialog = dialogFactory.createInputDialog(dialogTitle, localization.renameDialogNewNameLabel(), resource.getName(), 0, selectionLength, inputCallback, null); inputDialog.withValidator(validator); inputDialog.show(); } private void closeRelatedEditors(Resource resource) { if (!resource.isProject()) { return; } final List<EditorPartPresenter> openedEditors = editorAgent.getOpenedEditors(); for (EditorPartPresenter editor : openedEditors) { if (resource.getLocation().isPrefixOf(editor.getEditorInput().getFile().getLocation())) { editorAgent.closeEditor(editor); } } } /** {@inheritDoc} */ @Override public void updateInPerspective(@NotNull ActionEvent e) { final Resource[] resources = appContext.getResources(); e.getPresentation().setVisible(true); if (resources == null || resources.length != 1) { e.getPresentation().setEnabled(false); return; } for (RenamingSupport validator : renamingSupport) { if (!validator.isRenameAllowed(resources[0])) { e.getPresentation().setEnabled(false); return; } } e.getPresentation().setEnabled(true); } private abstract class AbstractNameValidator implements InputValidator { private final String selfName; public AbstractNameValidator(final String selfName) { this.selfName = selfName; } @Override public Violation validate(String value) { if (value.trim().equals(selfName)) { return new Violation() { @Override public String getMessage() { return ""; } @Override public String getCorrectedValue() { return null; } }; } return isValidName(value); } public abstract Violation isValidName(String value); } private class FileNameValidator extends AbstractNameValidator { public FileNameValidator(String selfName) { super(selfName); } @Override public Violation isValidName(String value) { if (!NameUtils.checkFileName(value)) { return new Violation() { @Override public String getMessage() { return localization.invalidName(); } @Nullable @Override public String getCorrectedValue() { return null; } }; } return null; } } private class FolderNameValidator extends AbstractNameValidator { public FolderNameValidator(String selfName) { super(selfName); } @Override public Violation isValidName(String value) { if (!NameUtils.checkFolderName(value)) { return new Violation() { @Override public String getMessage() { return localization.invalidName(); } @Nullable @Override public String getCorrectedValue() { return null; } }; } return null; } } private class ProjectNameValidator extends AbstractNameValidator { public ProjectNameValidator(String selfName) { super(selfName); } @Override public Violation isValidName(String value) { return new Violation() { @Override public String getMessage() { return localization.invalidName(); } @Nullable @Override public String getCorrectedValue() { if (NameUtils.checkProjectName(value)) { return value.contains(" ") ? value.replaceAll(" ", "-") : value; } return null; } }; } } }
package eu.hohenegger.modulebuilder.ui.wizard; import org.eclipse.emf.ecp.ui.view.ECPRendererException; import org.eclipse.emf.ecp.ui.view.swt.ECPSWTView; import org.eclipse.emf.ecp.ui.view.swt.ECPSWTViewRenderer; import org.eclipse.jface.dialogs.IDialogPage; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import modulespecification.Updatesite; /** * The "New" wizard page allows setting the container for the new file as well * as the file name. The page will only accept file name without the extension * OR with the extension that matches the expected one (mpe). */ public class NewP2UpdateSiteWizardPage extends WizardPage { private Updatesite updatesite; /** * Constructor for SampleNewWizardPage. * * @param updatesite * @param pageName */ public NewP2UpdateSiteWizardPage(Updatesite updatesite) { super("wizardPage"); this.updatesite = updatesite; setTitle("Tycho p2 layout"); setDescription("This wizard creates new projects that can be built with Tycho, producing a p2 update site."); } /** * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { Composite rootComposite = new Composite(parent, SWT.NULL); rootComposite.setLayout(GridLayoutFactory.fillDefaults().create()); scrolled(rootComposite); setControl(rootComposite); } private void scrolled(Composite rootComposite) { ScrolledComposite sc = new ScrolledComposite(rootComposite, SWT.H_SCROLL | SWT.V_SCROLL); sc.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, 400).create()); sc.setExpandHorizontal(true); sc.setExpandVertical(true); Composite containerMain = new Composite(sc, SWT.NONE); containerMain.setLayout(GridLayoutFactory.swtDefaults().numColumns(1).create()); render(containerMain); sc.setContent(containerMain); sc.setMinSize(containerMain.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } private Control render(Composite parent) { try { ECPSWTView render = ECPSWTViewRenderer.INSTANCE.render(parent, updatesite); return render.getSWTControl(); } catch (ECPRendererException e) { throw new RuntimeException(e); } } }
package org.aksw.iguana.tp.query; import java.util.Collection; import org.aksw.iguana.commons.factory.TypedFactory; import org.aksw.iguana.tp.tasks.impl.stresstest.worker.Worker; /** * Factory to create a QueryHandler based upon a class name and constructor arguments * * @author f.conrads * */ public class QueryHandlerFactory extends TypedFactory<QueryHandler> { /** * This will create a QueryHandler which first argument is a Collection of Workers. * The other arguments have to be of the String class. * * * @param className The class name of the QueryHandler * @param constructorArgs The constructor arguments as Strings * @param workers the List of all workers which queries should be generated * @return the QueryHandler */ @SuppressWarnings("unchecked") public QueryHandler createWorkerBasedQueryHandler(String className, Object[] constructorArgs, Collection<Worker> workers) { Class<String>[] stringClass = new Class[constructorArgs.length]; for(int i=0;i<stringClass.length;i++){ stringClass[i]=String.class; } return createWorkerBasedQueryHandler(className, constructorArgs, stringClass, workers); } /** * This will create a QueryHandler which first argument is a Collection of Workers. * The other arguments have to be of the specified classes * * * @param className The class name of the QueryHandler * @param constructorArgs2 The constructor arguments * @param constructorClasses2 The classes of the constructor arguments * @param workers the List of all workers which queries should be generated * @return the QueryHandler */ public QueryHandler createWorkerBasedQueryHandler(String className, Object[] constructorArgs2, Class<?>[] constructorClasses2, Collection<Worker> workers) { Object[] constructorArgs = new Object[1+constructorArgs2.length]; Class<?>[] constructorClasses = new Class<?>[1+constructorClasses2.length]; constructorArgs[0] = workers; constructorClasses[0] = workers.getClass(); for(int i=1;i<constructorArgs.length;i++) { constructorArgs[i] = constructorArgs2[i-1]; constructorClasses[i] = constructorClasses2[i-1]; } return create(className, constructorArgs, constructorClasses); } }
package io.quarkus.kafka.client.deployment; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.security.auth.spi.LoginModule; import org.apache.kafka.clients.consumer.RangeAssignor; import org.apache.kafka.clients.consumer.RoundRobinAssignor; import org.apache.kafka.clients.consumer.StickyAssignor; import org.apache.kafka.clients.consumer.internals.PartitionAssignor; import org.apache.kafka.clients.producer.Partitioner; import org.apache.kafka.clients.producer.internals.DefaultPartitioner; import org.apache.kafka.common.security.authenticator.AbstractLogin; import org.apache.kafka.common.security.authenticator.DefaultLogin; import org.apache.kafka.common.security.authenticator.SaslClientCallbackHandler; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.ByteBufferDeserializer; import org.apache.kafka.common.serialization.ByteBufferSerializer; import org.apache.kafka.common.serialization.BytesDeserializer; import org.apache.kafka.common.serialization.BytesSerializer; import org.apache.kafka.common.serialization.Deserializer; import org.apache.kafka.common.serialization.DoubleDeserializer; import org.apache.kafka.common.serialization.DoubleSerializer; import org.apache.kafka.common.serialization.FloatDeserializer; import org.apache.kafka.common.serialization.FloatSerializer; import org.apache.kafka.common.serialization.IntegerDeserializer; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.LongSerializer; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.serialization.ShortDeserializer; import org.apache.kafka.common.serialization.ShortSerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Type; import org.jboss.jandex.Type.Kind; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.AdditionalIndexedClassesBuildItem; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.IndexDependencyBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem; import io.quarkus.kafka.client.runtime.KafkaRuntimeConfigProducer; import io.quarkus.kafka.client.serialization.JsonbDeserializer; import io.quarkus.kafka.client.serialization.JsonbSerializer; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; import io.quarkus.kafka.client.serialization.ObjectMapperSerializer; import io.quarkus.smallrye.health.deployment.spi.HealthBuildItem; public class KafkaProcessor { static final Class[] BUILT_INS = { //serializers ShortSerializer.class, DoubleSerializer.class, LongSerializer.class, BytesSerializer.class, ByteArraySerializer.class, IntegerSerializer.class, ByteBufferSerializer.class, StringSerializer.class, FloatSerializer.class, //deserializers ShortDeserializer.class, DoubleDeserializer.class, LongDeserializer.class, BytesDeserializer.class, ByteArrayDeserializer.class, IntegerDeserializer.class, ByteBufferDeserializer.class, StringDeserializer.class, FloatDeserializer.class }; @BuildStep void contributeClassesToIndex(BuildProducer<AdditionalIndexedClassesBuildItem> additionalIndexedClasses, BuildProducer<IndexDependencyBuildItem> indexDependency) { // This is needed for SASL authentication additionalIndexedClasses.produce(new AdditionalIndexedClassesBuildItem( LoginModule.class.getName(), javax.security.auth.Subject.class.getName(), javax.security.auth.login.AppConfigurationEntry.class.getName(), javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag.class.getName())); indexDependency.produce(new IndexDependencyBuildItem("org.apache.kafka", "kafka-clients")); } @BuildStep public void build(CombinedIndexBuildItem indexBuildItem, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, Capabilities capabilities) { final Set<DotName> toRegister = new HashSet<>(); collectImplementors(toRegister, indexBuildItem, Serializer.class); collectImplementors(toRegister, indexBuildItem, Deserializer.class); collectImplementors(toRegister, indexBuildItem, Partitioner.class); collectImplementors(toRegister, indexBuildItem, PartitionAssignor.class); for (Class i : BUILT_INS) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, i.getName())); collectSubclasses(toRegister, indexBuildItem, i); } if (capabilities.isPresent(Capability.JSONB)) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, JsonbSerializer.class, JsonbDeserializer.class)); collectSubclasses(toRegister, indexBuildItem, JsonbSerializer.class); collectSubclasses(toRegister, indexBuildItem, JsonbDeserializer.class); } if (capabilities.isPresent(Capability.JACKSON)) { reflectiveClass.produce( new ReflectiveClassBuildItem(false, false, ObjectMapperSerializer.class, ObjectMapperDeserializer.class)); collectSubclasses(toRegister, indexBuildItem, ObjectMapperSerializer.class); collectSubclasses(toRegister, indexBuildItem, ObjectMapperDeserializer.class); } for (DotName s : toRegister) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, s.toString())); } // built in partitioner and partition assignors reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DefaultPartitioner.class.getName())); reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, RangeAssignor.class.getName())); reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, RoundRobinAssignor.class.getName())); reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, StickyAssignor.class.getName())); // classes needed to perform reflection on DirectByteBuffer - only really needed for Java 8 reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, "java.nio.DirectByteBuffer")); reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, "sun.misc.Cleaner")); } @BuildStep public AdditionalBeanBuildItem runtimeConfig() { return AdditionalBeanBuildItem.builder() .addBeanClass(KafkaRuntimeConfigProducer.class) .setUnremovable() .build(); } @BuildStep public void withSasl(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, AbstractLogin.DefaultLoginCallbackHandler.class)); reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, SaslClientCallbackHandler.class)); reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, DefaultLogin.class)); final Type loginModuleType = Type .create(DotName.createSimple(LoginModule.class.getName()), Kind.CLASS); reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(loginModuleType)); } private static void collectImplementors(Set<DotName> set, CombinedIndexBuildItem indexBuildItem, Class<?> cls) { collectClassNames(set, indexBuildItem.getIndex().getAllKnownImplementors(DotName.createSimple(cls.getName()))); } private static void collectSubclasses(Set<DotName> set, CombinedIndexBuildItem indexBuildItem, Class<?> cls) { collectClassNames(set, indexBuildItem.getIndex().getAllKnownSubclasses(DotName.createSimple(cls.getName()))); } private static void collectClassNames(Set<DotName> set, Collection<ClassInfo> classInfos) { classInfos.forEach(c -> { set.add(c.name()); }); } @BuildStep HealthBuildItem addHealthCheck(KafkaBuildTimeConfig buildTimeConfig) { return new HealthBuildItem("io.quarkus.kafka.client.health.KafkaHealthCheck", buildTimeConfig.healthEnabled, "kafka"); } }
package org.fusesource.fabric.service.jclouds; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.inject.Module; import org.fusesource.fabric.api.AgentProvider; import org.fusesource.fabric.api.CreateAgentArguments; import org.fusesource.fabric.api.CreateJCloudsAgentArguments; import org.fusesource.fabric.api.FabricException; import org.fusesource.fabric.api.JCloudsInstanceType; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.RunNodesException; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.domain.Credentials; import org.jclouds.rest.RestContextFactory; import static org.fusesource.fabric.internal.AgentProviderUtils.DEFAULT_SSH_PORT; import static org.fusesource.fabric.internal.AgentProviderUtils.buildStartupScript; /** * A concrete {@link AgentProvider} that creates {@link org.fusesource.fabric.api.Agent}s via jclouds {@link ComputeService}. */ public class JcloudsAgentProvider implements AgentProvider { private static final String IMAGE_ID = "imageId"; private static final String LOCATION_ID = "locationId"; private static final String HARDWARE_ID = "hardwareId"; private static final String USER = "user"; private static final String GROUP = "group"; private static final String INSTANCE_TYPE = "instanceType"; private final ConcurrentMap<String, ComputeService> computeServiceMap = new ConcurrentHashMap<String, ComputeService>(); public void bind(ComputeService computeService) { if(computeService != null) { String providerName = computeService.getContext().getProviderSpecificContext().getId(); if(providerName != null) { computeServiceMap.put(providerName,computeService); } } } public void unbind(ComputeService computeService) { if(computeService != null) { String providerName = computeService.getContext().getProviderSpecificContext().getId(); if(providerName != null) { computeServiceMap.remove(providerName); } } } public ConcurrentMap<String, ComputeService> getComputeServiceMap() { return computeServiceMap; } /** * Creates an {@link org.fusesource.fabric.api.Agent} with the given name pointing to the specified zooKeeperUrl. * @param proxyUri The uri of the maven proxy to use. * @param agentUri The uri that contains required information to build the Agent. * @param name The name of the Agent. * @param zooKeeperUrl The url of Zoo Keeper. * @param server Marks if the agent will have the role of the cluster server. * @param debugAgent */ public void create(URI proxyUri, URI agentUri, String name, String zooKeeperUrl, boolean server, boolean debugAgent) { create(proxyUri, agentUri,name,zooKeeperUrl,server,debugAgent,1); } /** * Creates an {@link org.fusesource.fabric.api.Agent} with the given name pointing to the specified zooKeeperUrl. * @param proxyUri The uri of the maven proxy to use. * @param agentUri The uri that contains required information to build the Agent. * @param name The name of the Agent. * @param zooKeeperUrl The url of Zoo Keeper. * @param isClusterServer Marks if the agent will have the role of the cluster server. * @param debugAgent Flag used to enable debugging on the new Agent. * @param number The number of Agents to create. */ @Override public void create(URI proxyUri, URI agentUri, String name, String zooKeeperUrl, boolean isClusterServer, boolean debugAgent, int number) { String imageId = null; String hardwareId = null; String locationId = null; String group = null; String user = null; JCloudsInstanceType instanceType = JCloudsInstanceType.Smallest; String identity = null; String credential = null; String owner = null; try { String providerName = agentUri.getHost(); if (agentUri.getQuery() != null) { Map<String, String> parameters = parseQuery(agentUri.getQuery()); if (parameters != null) { imageId = parameters.get(IMAGE_ID); group = parameters.get(GROUP); locationId = parameters.get(LOCATION_ID); hardwareId = parameters.get(HARDWARE_ID); user = parameters.get(USER); if (parameters.get(INSTANCE_TYPE) != null) { instanceType = JCloudsInstanceType.get(parameters.get(INSTANCE_TYPE), instanceType); } } } doCreateAgent(proxyUri, name, number, zooKeeperUrl, isClusterServer, debugAgent, imageId, hardwareId, locationId, group, user, instanceType, providerName, identity, credential, owner, DEFAULT_SSH_PORT); } catch (FabricException e) { throw e; } catch (Exception e) { throw new FabricException(e); } } /** * Creates an {@link org.fusesource.fabric.api.Agent} with the given name pointing to the specified zooKeeperUrl. * @param proxyUri The uri of the maven proxy to use. * @param agentUri The uri that contains required information to build the Agent. * @param name The name of the Agent. * @param zooKeeperUrl The url of Zoo Keeper. */ public void create(URI proxyUri, URI agentUri, String name, String zooKeeperUrl) { create(proxyUri,agentUri, name, zooKeeperUrl); } @Override public boolean create(CreateAgentArguments createArgs, String name, String zooKeeperUrl) throws Exception { if (createArgs instanceof CreateJCloudsAgentArguments) { CreateJCloudsAgentArguments args = (CreateJCloudsAgentArguments) createArgs; return doCreateAgent(args, name, zooKeeperUrl, DEFAULT_SSH_PORT) != null; } return false; } protected String doCreateAgent(CreateJCloudsAgentArguments args, String name, String zooKeeperUrl, int returnPort) throws MalformedURLException, RunNodesException, URISyntaxException { boolean isClusterServer = args.isClusterServer(); boolean debugAgent = args.isDebugAgent(); int number = args.getNumber(); String imageId = args.getImageId(); String hardwareId = args.getHardwareId(); String locationId = args.getLocationId(); String group = args.getGroup(); String user = args.getUser(); JCloudsInstanceType instanceType = args.getInstanceType(); String providerName = args.getProviderName(); String identity = args.getIdentity(); String credential = args.getCredential(); String owner = args.getOwner(); URI proxyURI = args.getProxyUri(); return doCreateAgent(proxyURI, name, number, zooKeeperUrl, isClusterServer, debugAgent, imageId, hardwareId, locationId, group, user, instanceType, providerName, identity, credential, owner, returnPort); } /** * Creates a new fabric on a remote JClouds machine, returning the new ZK connection URL */ public String createClusterServer(CreateJCloudsAgentArguments createArgs, String name) throws Exception { // TODO how can we get this value from the tarball I wonder, in case it ever changes? int zkPort = 2181; createArgs.setClusterServer(true); return doCreateAgent(createArgs, name, null, zkPort); } protected String doCreateAgent(URI proxyUri, String name, int number, String zooKeeperUrl, boolean isClusterServer, boolean debugAgent, String imageId, String hardwareId, String locationId, String group, String user, JCloudsInstanceType instanceType, String providerName, String identity, String credential, String owner, int returnPort) throws MalformedURLException, RunNodesException, URISyntaxException { ComputeService computeService = computeServiceMap.get(providerName); if (computeService == null) { //Iterable<? extends Module> modules = ImmutableSet.of(new Log4JLoggingModule(), new JschSshClientModule()); Iterable<? extends Module> modules = ImmutableSet.of(); Properties props = new Properties(); props.put("provider", providerName); props.put("identity", identity); props.put("credential", credential); if (!Strings.isNullOrEmpty(owner)) { props.put("jclouds.ec2.ami-owners", owner); } RestContextFactory restFactory = new RestContextFactory(); ComputeServiceContext context = new ComputeServiceContextFactory(restFactory).createContext(providerName, identity, credential, modules, props); computeService = context.getComputeService(); } TemplateBuilder builder = computeService.templateBuilder(); builder.any(); switch (instanceType) { case Smallest: builder.smallest(); break; case Biggest: builder.biggest(); break; case Fastest: builder.fastest(); } if (locationId != null) { builder.locationId(locationId); } if (imageId != null) { builder.imageId(imageId); } if (hardwareId != null) { builder.hardwareId(hardwareId); } Set<? extends NodeMetadata> metadatas = null; Credentials credentials = null; if (user != null && credentials == null) { credentials = new Credentials(user, null); } metadatas = computeService.createNodesInGroup(group, number, builder.build()); int suffix = 1; StringBuilder buffer = new StringBuilder(); boolean first = true; if (metadatas != null) { for (NodeMetadata nodeMetadata : metadatas) { String id = nodeMetadata.getId(); Set<String> publicAddresses = nodeMetadata.getPublicAddresses(); for (String pa: publicAddresses) { if (first) { first = false; } else { buffer.append(","); } buffer.append(pa + ":" + returnPort); } String agentName = name; if(number > 1) { agentName+=suffix++; } String script = buildStartupScript(proxyUri, agentName, "~/", zooKeeperUrl, DEFAULT_SSH_PORT,isClusterServer, debugAgent); if (credentials != null) { computeService.runScriptOnNode(id, script, RunScriptOptions.Builder.overrideCredentialsWith(credentials).runAsRoot(false)); } else { computeService.runScriptOnNode(id, script); } } } return buffer.toString(); } public Map<String, String> parseQuery(String uri) throws URISyntaxException { //TODO: This is copied form URISupport. We should move URISupport to core so that we don't have to copy stuff arround. try { Map<String, String> rc = new HashMap<String, String>(); if (uri != null) { String[] parameters = uri.split("&"); for (int i = 0; i < parameters.length; i++) { int p = parameters[i].indexOf("="); if (p >= 0) { String name = URLDecoder.decode(parameters[i].substring(0, p), "UTF-8"); String value = URLDecoder.decode(parameters[i].substring(p + 1), "UTF-8"); rc.put(name, value); } else { rc.put(parameters[i], null); } } } return rc; } catch (UnsupportedEncodingException e) { throw (URISyntaxException) new URISyntaxException(e.toString(), "Invalid encoding").initCause(e); } } }
package nu.nerd.beastmaster.mobs; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Set; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Ageable; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; import nu.nerd.beastmaster.BeastMaster; import nu.nerd.beastmaster.Drop; import nu.nerd.beastmaster.DropSet; import nu.nerd.beastmaster.DropType; import nu.nerd.beastmaster.Item; import nu.nerd.entitymeta.EntityMeta; /** * Represents a custom mob type. * * TODO: implement potions. */ public class MobType { /** * Return the set of property names that are immutable for predefined Mob * Types. * * @return the set of property names that are immutable for predefined Mob * Types. */ public static Set<String> getImmutablePredefinedPropertyNames() { return IMMUTABLE_PREDEFINED_PROPERTIES; } /** * Constructor for loading. */ public MobType() { this(null, null, false); } /** * Constructor for custom mob types. * * @param id the programmatic ID of this mob type. * @param id the programmatic ID of the parent mob type. */ public MobType(String id, String parentTypeId) { this(id, null, false); setParentTypeId(parentTypeId); } /** * General purpose constructor. * * @param id the programmatic ID of this mob type. * @param entityType the EntityType of the underlying vanilla mob. * @param predefined true if this mob type can be changed. */ public MobType(String id, EntityType entityType, boolean predefined) { _id = id; _predefined = predefined; addProperties(); getProperty("entity-type").setValue(entityType); } /** * Return the programmatic ID of this mob type. * * @return the programmatic ID of this mob type. */ public String getId() { return _id; } /** * Return true if this mob type is predefined. * * Predefined mob types correspond to the vanilla mob types. They cannot * haver their "entity-type" or "parent-type" property changed. * * @return true if this mob type is predefined. */ public boolean isPredefined() { return _predefined; } /** * Set the parent mob type ID. * * @param parentTypeId the parent type ID. */ public void setParentTypeId(String parentTypeId) { getProperty("parent-type").setValue(parentTypeId); } /** * Return the parent mob type ID, or null if unset. * * @return the parent mob type ID, or null if unset. */ public String getParentTypeId() { return (String) getProperty("parent-type").getValue(); } /** * Return the parent mob type, or null if unset or invalid. * * @return the parent mob type, or null if unset or invalid. */ public MobType getParentType() { return BeastMaster.MOBS.getMobType(getParentTypeId()); } /** * Set the drops loot table ID. * * @param dropsId the drops loot table ID. */ public void setDropsId(String dropsId) { getProperty("drops").setValue(dropsId); } /** * Return the ID of the DropSet consulted when this mob dies. * * @return the ID of the DropSet consulted when this mob dies. */ public String getDropsId() { return (String) getProperty("drops").getValue(); } /** * Return the DropSet consulted when this mob dies. * * @return the DropSet consulted when this mob dies. */ public DropSet getDrops() { String dropsId = getDropsId(); return dropsId != null ? BeastMaster.LOOTS.getDropSet(dropsId) : null; } /** * Return a collection of all properties that this mob type can override. * * @return a collection of all properties that this mob type can override. */ public Collection<MobProperty> getAllProperties() { return _properties.values(); } /** * Return the set of all property IDs. * * @return the set of all property IDs. */ public static Set<String> getAllPropertyIds() { // All mobs have the same properties. Choose zombie, arbitarily. return BeastMaster.MOBS.getMobType("zombie")._properties.keySet(); } /** * Return the property of this mob type with the specified ID. * * Note that this method does not consider property values inherited from * the parent type. * * @param id the property ID. * @return the property. */ public MobProperty getProperty(String id) { return _properties.get(id); } /** * Return the property with the specified ID derived by considering * inherited property values as well as the properties overridden by this * mob type. * * Properties that have a null value ({@link MobProperty#getValue()}) do not * override whatever was inherited from the ancestor mob types. * * @param id the property ID. * @return the {@link MobProperty} instance that has a non-null value * belonging to the most-derived mob type in the hierarchy, or the * root ancestor of the hierarchy if no mob type overrides that * property. Return null if there is no property with the specified * ID. The return value will always be non-null if the property ID * is valid. */ public MobProperty getDerivedProperty(String id) { MobProperty property = getProperty(id); if (property == null) { return null; } for (;;) { if (property.getValue() != null) { // Overridden property belonging to most-derived mob type. return property; } MobType owner = property.getMobType(); MobType parent = owner.getParentType(); if (parent == null) { // Root ancestor when not overridden. return property; } else { property = parent.getProperty(id); // Invariant: all mob types have the same property IDs. } } } /** * Load this mob type from the specified section. * * @param section the configuration file section. * @return true if successful. */ public boolean load(ConfigurationSection section, Logger logger) { _id = section.getName(); ConfigurationSection propertiesSection = section.getConfigurationSection("properties"); if (propertiesSection != null) { for (MobProperty property : getAllProperties()) { property.load(propertiesSection, logger); } } else { logger.warning("Mob type " + _id + " overrides no properties."); } // TODO: check properties on load, e.g. verify drops table existence. return true; } /** * Save this mob type as a child of the specified parent configuration * section. * * @param parentSection the parent configuration section. * @param logger the logger. */ public void save(ConfigurationSection parentSection, Logger logger) { ConfigurationSection section = parentSection.createSection(getId()); ConfigurationSection propertiesSection = section.createSection("properties"); for (MobProperty property : getAllProperties()) { property.save(propertiesSection, logger); } } /** * Configure a mob according to this mob type. * * @param mob the mob. */ public void configureMob(LivingEntity mob) { EntityMeta.api().set(mob, BeastMaster.PLUGIN, "mob-type", getId()); for (String propertyId : getAllPropertyIds()) { getDerivedProperty(propertyId).configureMob(mob, null); } } /** * Return a short string description of this type. * * This is a short (single line) description with just the basic details. * Immutable (built-in) mob types have their ID shown in green. * * @return a short string description of this type. */ public String getShortDescription() { StringBuilder desc = new StringBuilder(); if (!isPredefined()) { desc.append(ChatColor.WHITE).append("id: "); desc.append(ChatColor.YELLOW).append(getId()); desc.append(ChatColor.WHITE).append(", parent-type: "); desc.append(getParentType() != null ? ChatColor.GREEN : ChatColor.RED); desc.append(getParentTypeId()); } else { desc.append(ChatColor.YELLOW).append(getId()); } // TODO: Add properties. return desc.toString(); } /** * This method is called to check that the mob type is mutable before an * attempt is made to change its properties. * * @throws AssertionException if the mob type is not mutable. */ protected void checkMutable() { if (!isPredefined()) { throw new AssertionError("This mob type is not mutable."); } } /** * Add the specified property. * * @param property the property. */ protected void addProperty(MobProperty property) { _properties.put(property.getId(), property); property.setMobType(this); } /** * Add standard properties of this mob type. */ protected void addProperties() { // TODO: Many of these need get/set/range implementations. addProperty(new MobProperty("parent-type", DataType.STRING, null)); addProperty(new MobProperty("entity-type", DataType.ENTITY_TYPE, null)); addProperty(new MobProperty("drops", DataType.STRING, null)); // Note: configureMob() lambdas only called if property value non-null. addProperty(new MobProperty("health", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_MAX_HEALTH); attribute.setBaseValue((Double) getDerivedProperty("health").getValue()); mob.setHealth(attribute.getBaseValue()); })); addProperty(new MobProperty("experience", DataType.INTEGER, null)); addProperty(new MobProperty("follow-range", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_FOLLOW_RANGE); attribute.setBaseValue((Double) getDerivedProperty("follow-range").getValue()); })); addProperty(new MobProperty("attack-damage", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE); attribute.setBaseValue((Double) getDerivedProperty("attack-damage").getValue()); })); addProperty(new MobProperty("attack-speed", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_ATTACK_SPEED); attribute.setBaseValue((Double) getDerivedProperty("attack-speed").getValue()); })); addProperty(new MobProperty("speed", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED); attribute.setBaseValue((Double) getDerivedProperty("speed").getValue()); })); addProperty(new MobProperty("flying-speed", DataType.DOUBLE, (mob, logger) -> { AttributeInstance attribute = mob.getAttribute(Attribute.GENERIC_FLYING_SPEED); if (attribute != null) { attribute.setBaseValue((Double) getDerivedProperty("flying-speed").getValue()); } })); addProperty(new MobProperty("pick-up-percent", DataType.DOUBLE, (mob, logger) -> { mob.setCanPickupItems(Math.random() * 100 < (Double) getDerivedProperty("pick-up-percent").getValue()); })); addProperty(new MobProperty("baby-percent", DataType.DOUBLE, (mob, logger) -> { if (mob instanceof Ageable) { boolean isBaby = (Math.random() * 100 < (Double) getDerivedProperty("baby-percent").getValue()); if (isBaby) { ((Ageable) mob).setBaby(); } else { ((Ageable) mob).setAdult(); } } })); addProperty(new MobProperty("glowing", DataType.BOOLEAN, (mob, logger) -> { mob.setGlowing((Boolean) getDerivedProperty("glowing").getValue()); })); addProperty(new MobProperty("name", DataType.STRING, (mob, logger) -> { mob.setCustomName(ChatColor.translateAlternateColorCodes('&', (String) getDerivedProperty("name").getValue())); })); addProperty(new MobProperty("show-name-plate", DataType.BOOLEAN, (mob, logger) -> { mob.setCustomNameVisible((Boolean) getDerivedProperty("show-name-plate").getValue()); })); addProperty(new MobProperty("breath-seconds", DataType.INTEGER, (mob, logger) -> { int ticks = 20 * (Integer) getDerivedProperty("breath-seconds").getValue(); mob.setMaximumAir(ticks); mob.setRemainingAir(ticks); })); addProperty(new MobProperty("helmet", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("helmet").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setHelmet(itemStack); } })); addProperty(new MobProperty("helmet-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("helmet-drop-percent").getValue(); mob.getEquipment().setHelmetDropChance((float) percent / 100); })); addProperty(new MobProperty("chest-plate", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("chest-plate").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setChestplate(itemStack); } })); addProperty(new MobProperty("chest-plate-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("chest-plate-drop-percent").getValue(); mob.getEquipment().setChestplateDropChance((float) percent / 100); })); addProperty(new MobProperty("leggings", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("leggings").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setLeggings(itemStack); } })); addProperty(new MobProperty("leggings-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("leggings-drop-percent").getValue(); mob.getEquipment().setLeggingsDropChance((float) percent / 100); })); addProperty(new MobProperty("boots", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("boots").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setBoots(itemStack); } })); addProperty(new MobProperty("boots-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("boots-drop-percent").getValue(); mob.getEquipment().setBootsDropChance((float) percent / 100); })); addProperty(new MobProperty("main-hand", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("main-hand").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setItemInMainHand(itemStack); } })); addProperty(new MobProperty("main-hand-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("main-hand-drop-percent").getValue(); mob.getEquipment().setItemInMainHandDropChance((float) percent / 100); })); addProperty(new MobProperty("off-hand", DataType.STRING, (mob, logger) -> { String id = (String) getDerivedProperty("off-hand").getValue(); ItemStack itemStack = getEquipmentItem(id); if (itemStack != null) { mob.getEquipment().setItemInOffHand(itemStack); } })); addProperty(new MobProperty("off-hand-drop-percent", DataType.DOUBLE, (mob, logger) -> { double percent = (Double) getDerivedProperty("off-hand-drop-percent").getValue(); mob.getEquipment().setItemInOffHandDropChance((float) percent / 100); })); // Added after custom name => will clear PersistenceRequired NBT. addProperty(new MobProperty("can-despawn", DataType.BOOLEAN, (mob, logger) -> { boolean canDespawn = (Boolean) getDerivedProperty("can-despawn").getValue(); mob.setRemoveWhenFarAway(canDespawn); })); // TODO: use AIR to signify clearing the default armour/weapon. // TODO: Disguise property. // TODO: contact potion effects. // TODO: particle effect tracking mob. } /** * Return an equipment ItemStack to apply to a mob in * {@link #configureMob(LivingEntity)}. * * Mob properties corresponding to equipment items (helmet, chest-plate, * leggings, boots, main-hand, off-hand) are Strings that are interpreted as * either the ID of a {@link DropSet} or the ID of an {@link Item}. This * method attempts to look up the DropSet first, and if one with the * specified ID doesn't exist, the ID is interpreted as that of an Item. * * @param id the ID of the DropSet or Item to generate. * @return the equipment as an ItemStack, or null if the equipment should * not change (be default). */ protected ItemStack getEquipmentItem(String id) { DropSet drops = BeastMaster.LOOTS.getDropSet(id); if (drops != null) { Drop drop = drops.chooseOneDrop(); if (drop != null) { if (drop.getDropType() == DropType.NOTHING) { return new ItemStack(Material.AIR); } else if (drop.getDropType() == DropType.ITEM) { return drop.randomItemStack(); } } return null; } else { Item item = BeastMaster.ITEMS.getItem(id); return (item != null) ? item.getItemStack().clone() : null; } } /** * The set of property names that are immutable for predefined Mob Types. */ protected static HashSet<String> IMMUTABLE_PREDEFINED_PROPERTIES = new HashSet<>(); static { IMMUTABLE_PREDEFINED_PROPERTIES.addAll(Arrays.asList("parent-type", "entity-type")); } /** * The ID of this mob type. */ protected String _id; /** * True if this mob type is predefined (corresponds to a vanilla mob). */ protected boolean _predefined; /** * Map from property ID to {@link MobProperty} instance. * * Properties are enumerated in the order they were added by * {@link #addProperties()}. */ protected LinkedHashMap<String, MobProperty> _properties = new LinkedHashMap<>(); } // class MobType
package org.biojava.spice.das; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; //import org.biojava.spice.das.DAS_Sequence_Handler; import org.biojava.spice.manypanel.eventmodel.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.XMLReader; import java.util.*; /** a thread that gets the sequence from a DAS server * * @author Andreas Prlic * */ public class SequenceThread extends Thread { SpiceDasSource[] sequenceServers; String sp_accession; List seqListeners; static Logger logger = Logger.getLogger("org.biojava.spice"); public SequenceThread(String sp_accession,SpiceDasSource ds ) { super(); SpiceDasSource[] dss =new SpiceDasSource[1]; dss[0] = ds; this.sp_accession = sp_accession; this.sequenceServers =dss ; clearSequenceListeners(); } public SequenceThread(String sp_accession,SpiceDasSource[] ds ) { super(); this.sp_accession = sp_accession; this.sequenceServers =ds ; clearSequenceListeners(); } public void clearSequenceListeners(){ seqListeners = new ArrayList(); } public void addSequenceListener(SequenceListener lis){ seqListeners.add(lis); } public void run() { getSequence(); } public void getSequence( ){ boolean gotSequence = false ; for ( int i = 0 ; i< sequenceServers.length; i++){ if ( gotSequence ) break ; SpiceDasSource ds = sequenceServers[i]; String url = ds.getUrl() ; char lastChar = url.charAt(url.length()-1); if ( ! (lastChar == '/') ) url +="/" ; String dascmd = url + "sequence?segment="; String connstr = dascmd + sp_accession ; try { String sequence = retrieveSequence(connstr); // bug in aristotle das source? sequence.replaceAll(" ",""); gotSequence = true ; // set the sequence ... Iterator iter = seqListeners.iterator(); while (iter.hasNext()){ SequenceListener li = (SequenceListener)iter.next(); //SequenceEvent event = new SequenceEvent(sequence); SequenceEvent event = new SequenceEvent(sp_accession,sequence); li.newSequence(event); } return; } catch (Exception ex) { ex.printStackTrace(); logger.warning(ex.getMessage()); } } logger.log(Level.WARNING,"could not retreive UniProt sequence from any available DAS sequence server"); } public String retrieveSequence( String connstr) throws Exception { //logger.finest("trying: " + connstr) ; URL dasUrl = new URL(connstr); //DAS_httpConnector dhtp = new DAS_httpConnector() ; logger.info("requesting sequence from " + connstr); InputStream dasInStream =open(dasUrl); SAXParserFactory spfactory = SAXParserFactory.newInstance(); String vali = System.getProperty("XMLVALIDATION"); boolean validate = false ; if ((vali != null) && ( vali.equals("true")) ) validate = true ; spfactory.setValidating(validate); SAXParser saxParser = null ; try{ saxParser = spfactory.newSAXParser(); } catch (ParserConfigurationException e) { //e.printStackTrace(); logger.log(Level.FINER,"Uncaught exception", e); } XMLReader xmlreader = saxParser.getXMLReader(); try { xmlreader.setFeature("http://xml.org/sax/features/validation", validate); } catch (SAXException e) { logger.finer("Cannot set validation to " + validate); logger.log(Level.FINER,"Uncaught exception", e); } try { xmlreader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",validate); } catch (SAXNotRecognizedException e){ //e.printStackTrace(); logger.finer("Cannot set load-external-dtd to" + validate); logger.log(Level.FINER,"Uncaught exception", e); //System.err.println("Cannot set load-external-dtd to" + validate); } //DAS_DNA_Handler cont_handle = new DAS_DNA_Handler() ; DAS_Sequence_Handler cont_handle = new DAS_Sequence_Handler() ; xmlreader.setContentHandler(cont_handle); xmlreader.setErrorHandler(new org.xml.sax.helpers.DefaultHandler()); InputSource insource = new InputSource() ; insource.setByteStream(dasInStream); xmlreader.parse(insource); String sequence = cont_handle.get_sequence(); //logger.finest("Got sequence from DAS: " +sequence); logger.exiting(this.getClass().getName(), "retreiveSequence", sequence); return sequence ; } private InputStream open(URL url) { { InputStream inStream = null; try{ /// PROXY!!!! //String proxy = "wwwcache.sanger.ac.uk"; //String port = "3128" ; //Properties systemProperties = System.getProperties(); //systemProperties.setProperty("proxySet", "true" ); // systemProperties.setProperty("http.proxyHost",proxy); // systemProperties.setProperty("http.proxyPort",port); HttpURLConnection huc = null; //huc = (HttpURLConnection) dasUrl.openConnection(); //huc = proxyUrl.openConnection(); //logger.finer("opening "+url); huc = org.biojava.spice.SpiceApplication.openHttpURLConnection(url); logger.finest(huc.getResponseMessage()); //String contentEncoding = huc.getContentEncoding(); //logger.finest("encoding: " + contentEncoding); //logger.finest("code:" + huc.getResponseCode()); //logger.finest("message:" + huc.getResponseMessage()); inStream = huc.getInputStream(); //logger.finest(inStream); //in = new BufferedReader(new InputStreamReader(inStream)); //String inputLine ; //while (null != (inputLine = in.readLine()) ) { //logger.finest(inputLine); } catch ( Exception ex){ ex.printStackTrace(); logger.log(Level.WARNING,"Uncaught exception", ex); } return inStream; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.frc1675.commands; import edu.wpi.first.wpilibj.command.CommandGroup; import org.frc1675.commands.drive.mecanum.MecanumDrivePolarForTime; import org.frc1675.commands.shooter.GoToIdleSpeed; import org.frc1675.commands.shooter.GoToShootingSpeed; /** * Drive forward at 75% speed for 3 seconds. * @author josh */ public class BackCornerAuton extends CommandGroup { private static final double INITIAL_WIND_UP = 6.0; private static final double AFTER_FIRST_SHOT = 3.0; private static final double AFTER_SECOND_SHOT = 3.0; private static final double DRIVE_DURATION = 1.0; public BackCornerAuton() { addSequential(new GoToShootingSpeed()); addSequential(new Wait(INITIAL_WIND_UP)); addSequential(new Index()); addSequential(new Wait(AFTER_FIRST_SHOT)); addSequential(new Index()); addSequential(new Wait(AFTER_SECOND_SHOT)); addSequential(new Index()); addSequential(new MecanumDrivePolarForTime(0.5, 0.0, 0.0, DRIVE_DURATION)); } }
package org.gamefolk.roomfullofcats; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Random; import org.gamefolk.roomfullofcats.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.view.MotionEvent; import android.webkit.WebSettings; import android.webkit.WebView; import com.arcadeoftheabsurd.absurdengine.DeviceUtility; import com.arcadeoftheabsurd.absurdengine.GameView; //import com.arcadeoftheabsurd.absurdengine.MobFoxNativeRequest; import com.arcadeoftheabsurd.absurdengine.Sprite; import com.arcadeoftheabsurd.absurdengine.Timer; import com.arcadeoftheabsurd.absurdengine.WebUtils; import com.arcadeoftheabsurd.j_utils.Delegate; import com.arcadeoftheabsurd.j_utils.Pair; import com.arcadeoftheabsurd.j_utils.Vector2d; import com.mobfox.adsdk.nativeads.NativeAd; import com.mobfox.adsdk.nativeads.NativeAd.ImageAsset; import com.mobfox.adsdk.nativeads.NativeAdListener; import com.mobfox.adsdk.nativeads.NativeAdManager; public class CatsGame extends GameView implements NativeAdListener { private final Vector2d mapLoc = new Vector2d(50, 50); // in pixels, the top left corner of the top left column of things on the screen private final Vector2d mapSize = new Vector2d(6, 10); // in columns, rows private final int bucketSpace = 60; // vertical pixels between the bottom of the columns and the buckets private final int incSize = 10; // the amount by which to increase the size of things as they collect private final Thing[][] map = new Thing[mapSize.x][mapSize.y]; private Vector2d thingSize; // in pixels, set according to the size of the screen in onSizeChanged() private final int fallTime = 1; // interval after which things fall, in seconds private final int thingsLimit = 3; // the target number of things of the same type to collect private int score = 0; private Timer fallTimer; private final Random rGen = new Random(); private NativeAdManager adManager = new NativeAdManager(getContext(), "http://my.mobfox.com/request.php", "80187188f458cfde788d961b6882fd53", this, null); @Override public void adLoaded(NativeAd ad) { // TODO Auto-generated method stub System.out.println("got ad: " + ad.getClickUrl()); downloaded1 = makeSprite(loadBitmapHolder(((ImageAsset)ad.getImageAsset("icon")).bitmapHolder), 50, 50); } @Override public void adFailedToLoad() { // TODO Auto-generated method stub System.out.println("ad failed"); } @Override public void impression() { // TODO Auto-generated method stub } @Override public void adClicked() { // TODO Auto-generated method stub } public CatsGame(Context context, GameLoadListener loadListener) { super(context, loadListener); fallTimer = new Timer(fallTime, this, new Delegate() { public void function(Object... args) { // move bottommost row into buckets for (int x = 0; x < mapSize.x; x++) { Thing candidate = map[x][mapSize.y-2]; if (candidate != null) { Thing current = map[x][mapSize.y-1]; if (current != null) { if (candidate.type == current.type) { current.sprite.resize(current.sprite.getWidth() + incSize, current.sprite.getHeight() + incSize); current.things++; if (current.things == thingsLimit) { score++; map[x][mapSize.y-1] = null; } } else { current = null; candidate.sprite.translate(0, thingSize.y + bucketSpace); map[x][mapSize.y-1] = candidate; } } else { candidate.sprite.translate(0, thingSize.y + bucketSpace); map[x][mapSize.y-1] = candidate; } } } // descend things in all other rows for (int y = mapSize.y-2; y > 0; y for (int x = 0; x < mapSize.x; x++) { if (map[x][y-1] != null) { map[x][y-1].sprite.translate(0, thingSize.y); } map[x][y] = map[x][y-1]; } } // fill the top row with new things for (int x = 0; x < mapSize.x; x++) { ThingType type = ThingType.values()[rGen.nextInt(4)]; map[x][0] = new Thing(type, makeSprite(type.bitmapId, mapLoc.x + (x * thingSize.x), mapLoc.y)); } } }); } @Override public boolean onTouchEvent(MotionEvent event) { for (int x = 0; x < mapSize.x; x++) { for (int y = 0; y < mapSize.y-1; y++) { if (map[x][y] != null) { if (map[x][y].sprite.getBounds().contains((int)event.getX(), (int)event.getY())) { map[x][y] = null; } } } } return true; } @Override public void onDraw(Canvas canvas) { for (int x = 0; x < mapSize.x; x++) { for (int y = 0; y < mapSize.y; y++) { if (map[x][y] != null) { drawSprite(canvas, map[x][y].sprite); } } } if (downloaded1 != null) { drawSprite(canvas, downloaded1); //drawSprite(canvas, downloaded2); } } @Override protected void setupGame(int width, int height) { thingSize = new Vector2d((width / mapSize.x) - 20, (height / mapSize.y) - 20); ThingType.GEAR.setBitmap (loadBitmapResource(ThingType.GEAR.resourceId, thingSize)); ThingType.SHROOM.setBitmap (loadBitmapResource(ThingType.SHROOM.resourceId, thingSize)); ThingType.CRYSTAL.setBitmap(loadBitmapResource(ThingType.CRYSTAL.resourceId, thingSize)); ThingType.ROCK.setBitmap (loadBitmapResource(ThingType.ROCK.resourceId, thingSize)); } @Override protected void startGame() { fallTimer.start(); adManager.requestAd(); } boolean test = false; Sprite downloaded1; Sprite downloaded2; @Override protected void updateGame() { if (!test) { test = true; try { /* * IMAGE TEST */ /* * FIRST AD TEST */ /*System.out.println("getting ip..."); String ip = DeviceUtility.getLocalIp(); System.out.println(ip); System.out.println("getting ad id..."); String adId = DeviceUtility.getAdId(); System.out.println(adId); MobFoxNativeRequest adRequest = new MobFoxNativeRequest(); adRequest.publisherId = "80187188f458cfde788d961b6882fd53"; // test id adRequest.userAgent = URLEncoder.encode(DeviceUtility.getUserAgent(), "UTF-8"); adRequest.ipAddress = ip; adRequest.adId = adId; adRequest.imageTypes = new String[]{"icon"}; adRequest.textTypes = new String[]{"headline"}; System.out.println("compiling request..."); String request = adRequest.compileRequest(); System.out.println(request); System.out.println("sending request..."); String result = WebUtils.restRequest(request); System.out.println(result);*/ /* * InetAddress test */ /*System.out.println("by name:"); InetAddress addr = InetAddress.getByName("arcadeoftheabsurd.com"); System.out.println("Printing IP:"); for(byte b : addr.getAddress()){ System.out.println(b + "."); } System.out.println("hostname: " + addr.getHostName()); System.out.println("canonical name: " + addr.getCanonicalHostName()); System.out.println(); System.out.println("by address:"); InetAddress addr2 = InetAddress.getByAddress(new byte[]{(byte)72,(byte)167,(byte)3,(byte)128}); System.out.println("Printing IP:"); for(byte b : addr2.getAddress()){ System.out.println(b + "."); } System.out.println("hostname: " + addr2.getHostName()); System.out.println("canonical name: " + addr2.getCanonicalHostName()); System.out.println();*/ /* * Socket test */ /*InetAddress addr = InetAddress.getByName("arcadeoftheabsurd.com"); String address = addr.getHostAddress(); String host = addr.getHostName(); System.out.println("address: " + address); System.out.println("host: " + host); Socket s = new Socket(address, 80); System.out.println("connected?: " + s.isConnected()); PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("GET / HTTP/1.1"); pw.println("Host: arcadeoftheabsurd.com"); pw.println(""); pw.flush(); System.out.println("connected?: " + s.isConnected()); InputStreamReader ir = new InputStreamReader(s.getInputStream()); char[] chars = new char[32]; while(ir.read(chars) != -1) { System.out.println("connected?: " + s.isConnected()); System.out.println(String.valueOf(chars)); chars = new char[32]; } ir.close();*/ /* * URL TEST */ } catch (Exception e) {} } } private class Thing { public int things = 0; public ThingType type; public Sprite sprite; public Thing (ThingType type, Sprite sprite) { this.type = type; this.sprite = sprite; } } private enum ThingType { GEAR(R.drawable.gear), SHROOM(R.drawable.shroom), CRYSTAL(R.drawable.crystal), ROCK(R.drawable.rock); private int resourceId; private int bitmapId = -1; private ThingType(int resourceId) { this.resourceId = resourceId; } public void setBitmap(int bitmapId) { this.bitmapId = bitmapId; } } }
package org.jdcp.job; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import org.jdcp.concurrent.BackgroundThreadFactory; import org.selfip.bkimmel.jobs.Job; import org.selfip.bkimmel.progress.ProgressMonitor; /** * A <code>Job</code> that runs a <code>ParallelizableJob</code> using multiple * threads. * @author bkimmel */ public final class ParallelizableJobRunner implements Job { /** * Creates a new <code>ParallelizableJobRunner</code>. * @param job The <code>ParallelizableJob</code> to run. * @param executor The <code>Executor</code> to use to run worker threads. * @param maxConcurrentWorkers The maximum number of concurrent tasks to * process. */ public ParallelizableJobRunner(ParallelizableJob job, Executor executor, int maxConcurrentWorkers) { this.job = job; this.worker = job.worker(); this.executor = executor; this.workerSlot = new Semaphore(maxConcurrentWorkers); this.maxConcurrentWorkers = maxConcurrentWorkers; } /** * Creates a new <code>ParallelizableJobRunner</code>. * @param job The <code>ParallelizableJob</code> to run. * @param maxConcurrentWorkers The maximum number of concurrent tasks to * process. */ public ParallelizableJobRunner(ParallelizableJob job, int maxConcurrentWorkers) { this(job, Executors.newFixedThreadPool(maxConcurrentWorkers, new BackgroundThreadFactory()), maxConcurrentWorkers); } /* (non-Javadoc) * @see org.jmist.framework.Job#go(org.jmist.framework.reporting.ProgressMonitor) */ public synchronized boolean go(final ProgressMonitor monitor) { int taskNumber = 0; boolean complete = false; this.monitor = monitor; /* Task loop. */ while (!this.monitor.isCancelPending()) { try { /* Get the next task to run. If there are no further tasks, * then wait for the remaining tasks to finish. */ Object task = this.job.getNextTask(); if (task == null) { this.workerSlot.acquire(this.maxConcurrentWorkers); complete = true; break; } /* Create a worker and process the task. */ String workerTitle = String.format("Worker (%d)", taskNumber); Worker worker = new Worker(task, monitor.createChildProgressMonitor(workerTitle)); /* Acquire one of the slots for processing a task -- this * limits the processing to the specified number of concurrent * tasks. */ this.workerSlot.acquire(); notifyStatusChanged(String.format("Starting worker %d", ++taskNumber)); this.executor.execute(worker); } catch (InterruptedException e) { e.printStackTrace(); } } this.monitor = null; if (!complete) { monitor.notifyCancelled(); } else { monitor.notifyComplete(); } return true; } /** * Notifies the progress monitor that the status has changed. * @param status A <code>String</code> describing the status. */ private void notifyStatusChanged(String status) { synchronized (monitor) { this.monitor.notifyStatusChanged(status); } } /** * Submits results for a task. * @param task An <code>Object</code> describing the task for which results * are being submitted. * @param results An <code>Object</code> describing the results. */ private void submitResults(Object task, Object results) { synchronized (monitor) { this.job.submitTaskResults(task, results, monitor); } } /** * Processes tasks for a <code>ParallelizableJob</code>. * @author bkimmel */ private class Worker implements Runnable { /** * Creates a new <code>Worker</code>. * @param task An <code>Object</code> describing the task to be * processed by the worker. * @param monitor The <code>ProgressMonitor</code> to report progress * to. */ public Worker(Object task, ProgressMonitor monitor) { this.task = task; this.monitor = monitor; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { submitResults(task, worker.performTask(task, monitor)); } catch (Exception e) { e.printStackTrace(); } finally { workerSlot.release(); } } /** The <code>ProgressMonitor</code> to report progress to. */ private final ProgressMonitor monitor; /** An <code>Object</code> describing the task to be processed. */ private final Object task; } /** The <code>ProgressMonitor</code> to report progress to. */ private ProgressMonitor monitor = null; /** The <code>ParallelizableJob</code> to be run. */ private final ParallelizableJob job; /** The <code>TaskWorker</code> to use to process tasks. */ private final TaskWorker worker; /** * The <code>Semaphore</code> to use to limit the number of concurrent * threads. */ private final Semaphore workerSlot; /** The <code>Executor</code> to use to run worker threads. */ private final Executor executor; /** The maximum number of concurrent tasks to process. */ private final int maxConcurrentWorkers; }
package org.jgroups.protocols.pbcast; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.logging.Log; import org.jgroups.util.Digest; import org.jgroups.util.MergeId; import java.util.Collection; import java.util.Map; public abstract class GmsImpl { protected final GMS gms; protected final Merger merger; protected final Log log; volatile boolean leaving=false; protected GmsImpl(GMS gms) { this.gms=gms; merger=gms.merger; log=gms.getLog(); } public abstract void join(Address mbr, boolean useFlushIfPresent); public abstract void joinWithStateTransfer(Address local_addr,boolean useFlushIfPresent); public abstract void leave(Address mbr); public void handleJoinResponse(JoinRsp join_rsp) {} public void handleLeaveResponse() {} public void suspect(Address mbr) {} public void unsuspect(Address mbr) {} public void merge(Map<Address,View> views) {} // only processed by coord public void handleMergeRequest(Address sender, MergeId merge_id, Collection<? extends Address> mbrs) {} // only processed by coords public void handleMergeResponse(MergeData data, MergeId merge_id) {} // only processed by coords public void handleMergeView(MergeData data, MergeId merge_id) {} // only processed by coords public void handleMergeCancelled(MergeId merge_id) {} // only processed by coords public void handleDigestResponse(Address sender, Digest digest) {} // only processed by coords public void handleMembershipChange(Collection<Request> requests) {} public void handleViewChange(View new_view, Digest digest) {} public void init() throws Exception {leaving=false;} public void start() throws Exception {leaving=false;} public void stop() {leaving=true;} protected void sendMergeRejectedResponse(Address sender, MergeId merge_id) { Message msg=new Message(sender, null, null); msg.setFlag(Message.OOB); GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP); hdr.merge_rejected=true; hdr.merge_id=merge_id; msg.putHeader(gms.getId(), hdr); if(log.isDebugEnabled()) log.debug("merge response=" + hdr); gms.getDownProtocol().down(new Event(Event.MSG, msg)); } protected void wrongMethod(String method_name) { if(log.isWarnEnabled()) log.warn(method_name + "() should not be invoked on an instance of " + getClass().getName()); } public static class Request { static final int JOIN = 1; static final int LEAVE = 2; static final int SUSPECT = 3; static final int MERGE = 4; static final int JOIN_WITH_STATE_TRANSFER = 6; int type=-1; Address mbr; boolean suspected; Map<Address,View> views; // different view on MERGE boolean useFlushIfPresent; Request(int type, Address mbr, boolean suspected) { this.type=type; this.mbr=mbr; this.suspected=suspected; } Request(int type, Address mbr, boolean suspected, Map<Address,View> views, boolean useFlushPresent) { this(type, mbr, suspected); this.views=views; this.useFlushIfPresent=useFlushPresent; } Request(int type, Address mbr, boolean suspected, Map<Address,View> views) { this(type, mbr, suspected, views, true); } public int getType() { return type; } public String toString() { switch(type) { case JOIN: return "JOIN(" + mbr + ")"; case JOIN_WITH_STATE_TRANSFER: return "JOIN_WITH_STATE_TRANSFER(" + mbr + ")"; case LEAVE: return "LEAVE(" + mbr + ", " + suspected + ")"; case SUSPECT: return "SUSPECT(" + mbr + ")"; case MERGE: return "MERGE(" + views.size() + " views)"; } return "<invalid (type=" + type + ")"; } /** * Specifies whether this request can be processed with other request simultaneously */ public boolean canBeProcessedTogether(Request other) { if(other == null) return false; int other_type=other.type; return (type == JOIN || type == LEAVE || type == SUSPECT) && (other_type == JOIN || other_type == LEAVE || other_type == SUSPECT); } } }
package org.jgroups.protocols.pbcast; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.annotations.*; import org.jgroups.protocols.TP; import org.jgroups.stack.DiagnosticsHandler; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import java.util.*; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically * increasing sequence number (seqno). Receivers deliver messages ordered * according to seqno and request retransmission of missing messages.<br/> * Retransmit requests are usually sent to the original sender of a message, but * this can be changed by xmit_from_random_member (send to random member) or * use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone * instead of the requester by setting use_mcast_xmit to true. * * @author Bela Ban */ @MBean(description="Reliable transmission multipoint FIFO protocol") public class NAKACK2 extends Protocol implements DiagnosticsHandler.ProbeHandler { protected static final int NUM_REBROADCAST_MSGS=3; @Property(description="Max number of messages to be removed from a RingBuffer. This property might " + "get removed anytime, so don't use it !") protected int max_msg_batch_size=100; /** * Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers * lost a message, the sender only retransmits once */ @Property(description="Retransmit retransmit responses (messages) using multicast rather than unicast") protected boolean use_mcast_xmit=true; /** * Use a multicast to request retransmission of missing messages. This may * be costly as every member in the cluster will send a response */ @Property(description="Use a multicast to request retransmission of missing messages") protected boolean use_mcast_xmit_req=false; /** * Ask a random member for retransmission of a missing message. If set to * true, discard_delivered_msgs will be set to false */ @Property(description="Ask a random member for retransmission of a missing message. Default is false") protected boolean xmit_from_random_member=false; /** * Messages that have been received in order are sent up the stack (= delivered to the application). * Delivered messages are removed from the retransmission buffer, so they can get GC'ed by the JVM. When this * property is true, everyone (except the sender of a message) removes the message from their retransission * buffers as soon as it has been delivered to the application */ @Property(description="Should messages delivered to application be discarded") protected boolean discard_delivered_msgs=true; @Property(description="Timeout to rebroadcast messages. Default is 2000 msec") protected long max_rebroadcast_timeout=2000; /** * When not finding a message on an XMIT request, include the last N * stability messages in the error message */ @Property(description="Should stability history be printed if we fail in retransmission. Default is false") protected boolean print_stability_history_on_failed_xmit=false; /** If true, logs messages discarded because received from other members */ @Property(description="discards warnings about promiscuous traffic") protected boolean log_discard_msgs=true; @Property(description="If true, trashes warnings about retransmission messages not found in the xmit_table (used for testing)") protected boolean log_not_found_msgs=true; @Property(description="Interval (in milliseconds) at which missing messages (from all retransmit buffers) " + "are retransmitted") protected long xmit_interval=1000; @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) int xmit_table_num_rows=50; @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) int xmit_table_msgs_per_row=10000; @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) double xmit_table_resize_factor=1.2; @Property(description="Number of milliseconds after which the matrix in the retransmission table " + "is compacted (only for experts)",writable=false) long xmit_table_max_compaction_time=10000; @ManagedAttribute(description="Number of retransmit requests received") protected final AtomicLong xmit_reqs_received=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit requests sent") protected final AtomicLong xmit_reqs_sent=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit responses received") protected final AtomicLong xmit_rsps_received=new AtomicLong(0); @ManagedAttribute(description="Number of retransmit responses sent") protected final AtomicLong xmit_rsps_sent=new AtomicLong(0); @ManagedAttribute(description="Is the retransmit task running") public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();} protected boolean is_server=false; protected Address local_addr=null; protected final List<Address> members=new CopyOnWriteArrayList<Address>(); protected View view; private final AtomicLong seqno=new AtomicLong(0); // current message sequence number (starts with 1) /** Map to store sent and received messages (keyed by sender) */ protected final ConcurrentMap<Address,Table<Message>> xmit_table=Util.createConcurrentMap(); /** RetransmitTask running every xmit_interval ms */ protected Future<?> xmit_task; protected volatile boolean leaving=false; protected volatile boolean running=false; protected TimeScheduler timer=null; protected final Lock rebroadcast_lock=new ReentrantLock(); protected final Condition rebroadcast_done=rebroadcast_lock.newCondition(); // set during processing of a rebroadcast event protected volatile boolean rebroadcasting=false; protected final Lock rebroadcast_digest_lock=new ReentrantLock(); @GuardedBy("rebroadcast_digest_lock") protected Digest rebroadcast_digest=null; /** BoundedList<Digest>, keeps the last 10 stability messages */ protected final BoundedList<Digest> stability_msgs=new BoundedList<Digest>(10); /** Keeps a bounded list of the last N digest sets */ protected final BoundedList<String> digest_history=new BoundedList<String>(10); public long getXmitRequestsReceived() {return xmit_reqs_received.get();} public long getXmitRequestsSent() {return xmit_reqs_sent.get();} public long getXmitResponsesReceived() {return xmit_rsps_received.get();} public long getXmitResponsesSent() {return xmit_rsps_sent.get();} public boolean isUseMcastXmit() {return use_mcast_xmit;} public boolean isXmitFromRandomMember() {return xmit_from_random_member;} public boolean isDiscardDeliveredMsgs() {return discard_delivered_msgs;} public boolean getLogDiscardMessages() {return log_discard_msgs;} public void setUseMcastXmit(boolean use_mcast_xmit) {this.use_mcast_xmit=use_mcast_xmit;} public void setLogDiscardMessages(boolean flag) {log_discard_msgs=flag;} public void setXmitFromRandomMember(boolean xmit_from_random_member) { this.xmit_from_random_member=xmit_from_random_member; } public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { this.discard_delivered_msgs=discard_delivered_msgs; } /** Returns the receive window for sender; only used for testing. Do not use ! */ public Table<Message> getWindow(Address sender) { return xmit_table.get(sender); } /** Only used for unit tests, don't use ! */ public void setTimer(TimeScheduler timer) {this.timer=timer;} @ManagedAttribute(description="Total number of undelivered messages in all retransmit buffers") public int getXmitTableUndeliveredMsgs() { int num=0; for(Table<Message> buf: xmit_table.values()) num+=buf.size(); return num; } @ManagedAttribute(description="Total number of missing (= not received) messages in all retransmit buffers") public int getXmitTableMissingMessages() { int num=0; for(Table<Message> buf: xmit_table.values()) num+=buf.getNumMissing(); return num; } @ManagedAttribute(description="Capacity of the retransmit buffer. Computed as xmit_table_num_rows * xmit_table_msgs_per_row") public long getXmitTableCapacity() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.capacity() : 0; } @ManagedAttribute(description="Prints the number of rows currently allocated in the matrix. This value will not " + "be lower than xmit_table_now_rows") public int getXmitTableNumCurrentRows() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.getNumRows() : 0; } @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + "To compute the size, Message.getLength() is used") public long getSizeOfAllMessages() { long retval=0; for(Table<Message> buf: xmit_table.values()) retval+=sizeOfAllMessages(buf,false); return retval; } @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + "To compute the size, Message.size() is used") public long getSizeOfAllMessagesInclHeaders() { long retval=0; for(Table<Message> buf: xmit_table.values()) retval+=sizeOfAllMessages(buf, true); return retval; } @ManagedAttribute(description="Number of retransmit table compactions") public int getXmitTableNumCompactions() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.getNumCompactions() : 0; } @ManagedAttribute(description="Number of retransmit table moves") public int getXmitTableNumMoves() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.getNumMoves() : 0; } @ManagedAttribute(description="Number of retransmit table resizes") public int getXmitTableNumResizes() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.getNumResizes(): 0; } @ManagedAttribute(description="Number of retransmit table purges") public int getXmitTableNumPurges() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; return table != null? table.getNumPurges(): 0; } @ManagedOperation(description="Prints the contents of the receiver windows for all members") public String printMessages() { StringBuilder ret=new StringBuilder(local_addr + ":\n"); for(Map.Entry<Address,Table<Message>> entry: xmit_table.entrySet()) { Address addr=entry.getKey(); Table<Message> buf=entry.getValue(); ret.append(addr).append(": ").append(buf.toString()).append('\n'); } return ret.toString(); } @ManagedAttribute public long getCurrentSeqno() {return seqno.get();} @ManagedOperation(description="Prints the stability messages received") public String printStabilityMessages() { StringBuilder sb=new StringBuilder(); sb.append(Util.printListWithDelimiter(stability_msgs, "\n")); return sb.toString(); } @ManagedOperation(description="Keeps information about the last N times a digest was set or merged") public String printDigestHistory() { StringBuilder sb=new StringBuilder(local_addr + ":\n"); for(String tmp: digest_history) sb.append(tmp).append("\n"); return sb.toString(); } @ManagedOperation(description="Compacts the retransmit buffer") public void compact() { Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; if(table != null) table.compact(); } @ManagedOperation(description="Prints the number of rows currently allocated in the matrix for all members. " + "This value will not be lower than xmit_table_now_rows") public String dumpXmitTablesNumCurrentRows() { StringBuilder sb=new StringBuilder(); for(Map.Entry<Address,Table<Message>> entry: xmit_table.entrySet()) { sb.append(entry.getKey()).append(": ").append(entry.getValue().getNumRows()).append("\n"); } return sb.toString(); } @ManagedOperation(description="Resets all statistics") public void resetStats() { xmit_reqs_received.set(0); xmit_reqs_sent.set(0); xmit_rsps_received.set(0); xmit_rsps_sent.set(0); stability_msgs.clear(); digest_history.clear(); Table<Message> table=local_addr != null? xmit_table.get(local_addr) : null; if(table != null) table.resetStats(); } public void init() throws Exception { if(xmit_from_random_member) { if(discard_delivered_msgs) { discard_delivered_msgs=false; log.debug("xmit_from_random_member set to true: changed discard_delivered_msgs to false"); } } TP transport=getTransport(); if(transport != null) { transport.registerProbeHandler(this); if(!transport.supportsMulticasting()) { if(use_mcast_xmit) { log.warn("use_mcast_xmit should not be used because the transport (" + transport.getName() + ") does not support IP multicasting; setting use_mcast_xmit to false"); use_mcast_xmit=false; } if(use_mcast_xmit_req) { log.warn("use_mcast_xmit_req should not be used because the transport (" + transport.getName() + ") does not support IP multicasting; setting use_mcast_xmit_req to false"); use_mcast_xmit_req=false; } } } } public Map<String,Object> dumpStats() { Map<String,Object> retval=super.dumpStats(); retval.put("msgs", printMessages()); return retval; } public String printStats() { StringBuilder sb=new StringBuilder(); sb.append("\nStability messages received\n"); sb.append(printStabilityMessages()).append("\n"); return sb.toString(); } public String printStabilityHistory() { StringBuilder sb=new StringBuilder(); int i=1; for(Digest digest: stability_msgs) { sb.append(i++).append(": ").append(digest).append("\n"); } return sb.toString(); } public List<Integer> providedUpServices() { return Arrays.asList(Event.GET_DIGEST,Event.SET_DIGEST,Event.OVERWRITE_DIGEST,Event.MERGE_DIGEST); } public void start() throws Exception { timer=getTransport().getTimer(); if(timer == null) throw new Exception("timer is null"); running=true; leaving=false; startRetransmitTask(); } public void stop() { running=false; stopRetransmitTask(); reset(); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>down_prot.down()</code> in this * method as the event is passed down by default by the superclass after this method returns !</b> */ public Object down(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); Address dest=msg.getDest(); if(dest != null || msg.isFlagSet(Message.NO_RELIABILITY)) break; // unicast address: not null and not mcast, pass down unchanged send(evt, msg); return null; // don't pass down the stack case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass down further (Bela Aug 7 2001) case Event.GET_DIGEST: return getDigest((Address)evt.getArg()); case Event.SET_DIGEST: setDigest((Digest)evt.getArg()); return null; case Event.OVERWRITE_DIGEST: overwriteDigest((Digest)evt.getArg()); return null; case Event.MERGE_DIGEST: mergeDigest((Digest)evt.getArg()); return null; case Event.TMP_VIEW: View tmp_view=(View)evt.getArg(); List<Address> mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); break; case Event.VIEW_CHANGE: tmp_view=(View)evt.getArg(); mbrs=tmp_view.getMembers(); members.clear(); members.addAll(mbrs); view=tmp_view; adjustReceivers(members); is_server=true; // check vids from now on Set<Address> tmp=new LinkedHashSet<Address>(members); tmp.add(null); // for null destination (= mcast) break; case Event.BECOME_SERVER: is_server=true; break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.DISCONNECT: leaving=true; reset(); break; case Event.REBROADCAST: rebroadcasting=true; rebroadcast_digest=(Digest)evt.getArg(); try { rebroadcastMessages(); } finally { rebroadcasting=false; rebroadcast_digest_lock.lock(); try { rebroadcast_digest=null; } finally { rebroadcast_digest_lock.unlock(); } } return null; case Event.ADD_TO_XMIT_TABLE: msg=(Message)evt.getArg(); dest=msg.getDest(); if(dest != null || msg.isFlagSet(Message.NO_RELIABILITY)) return null; // unicast address: not null and not mcast, pass down unchanged send(evt, msg, false); // add to retransmit window, but don't send (we want to avoid the unneeded traffic) return null; // don't pass down the stack } return down_prot.down(evt); } /** * <b>Callback</b>. Called by superclass when event may be handled.<p> <b>Do not use <code>PassUp</code> in this * method as the event is passed up by default by the superclass after this method returns !</b> */ public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); if(msg.isFlagSet(Message.NO_RELIABILITY)) break; NakAckHeader2 hdr=(NakAckHeader2)msg.getHeader(this.id); if(hdr == null) break; // pass up (e.g. unicast msg) if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) if(log.isTraceEnabled()) log.trace(local_addr + ": message " + msg.getSrc() + "::" + hdr.seqno + " was discarded (not yet server)"); return null; } // Changed by bela Jan 29 2003: we must not remove the header, otherwise further xmit requests will fail ! //hdr=(NakAckHeader2)msg.removeHeader(getName()); switch(hdr.type) { case NakAckHeader2.MSG: handleMessage(msg, hdr); return null; // transmitter passes message up for us ! case NakAckHeader2.XMIT_REQ: SeqnoList missing=(SeqnoList)msg.getObject(); if(missing == null) { if(log.isErrorEnabled()) log.error("XMIT_REQ: no missing seqnos; discarding request from " + msg.getSrc()); return null; } handleXmitReq(msg.getSrc(), missing, hdr.sender); return null; case NakAckHeader2.XMIT_RSP: handleXmitRsp(msg, hdr); return null; default: if(log.isErrorEnabled()) { log.error("NakAck header type " + hdr.type + " not known !"); } return null; } case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg stable((Digest)evt.getArg()); return null; // do not pass up further (Bela Aug 7 2001) case Event.SUSPECT: // release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new // flush round anyway if(rebroadcasting) { cancelRebroadcasting(); } break; } return up_prot.up(evt); } // ProbeHandler interface public Map<String, String> handleProbe(String... keys) { Map<String,String> retval=new HashMap<String,String>(); for(String key: keys) { if(key.equals("digest-history")) retval.put(key, printDigestHistory()); if(key.equals("dump-digest")) retval.put(key, "\n" + printMessages()); } return retval; } // ProbeHandler interface public String[] supportedKeys() { return new String[]{"digest-history", "dump-digest"}; } protected void send(Event evt, Message msg, boolean pass_down) { if(msg == null) throw new NullPointerException("msg is null; event is " + evt); if(!running) { if(log.isTraceEnabled()) log.trace(local_addr + ": discarded message as we're not in the 'running' state, message: " + msg); return; } long msg_id; Table<Message> buf=xmit_table.get(local_addr); if(buf == null) { // discard message if there is no entry for local_addr if(log.isWarnEnabled() && log_discard_msgs) log.warn(local_addr + ": discarded message to " + local_addr + " with no window, my view is " + view); return; } if(msg.getSrc() == null) msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr msg_id=seqno.incrementAndGet(); long sleep=10; while(running) { try { msg.putHeader(this.id, NakAckHeader2.createMessageHeader(msg_id)); buf.add(msg_id, msg); break; } catch(Throwable t) { if(!running) break; if(log.isWarnEnabled()) log.warn("failed sending message", t); Util.sleep(sleep); sleep=Math.min(5000, sleep*2); } } if(!pass_down) return; try { if(log.isTraceEnabled()) log.trace("sending " + local_addr + "#" + msg_id); down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted } catch(Throwable t) { // eat the exception, don't pass it up the stack if(log.isWarnEnabled()) { log.warn("failure passing message down", t); } } } protected void send(Event evt, Message msg) { send(evt,msg,true); } /** * Finds the corresponding retransmit buffer and adds the message to it (according to seqno). Then removes as many * messages as possible and passes them up the stack. Discards messages from non-members. */ protected void handleMessage(Message msg, NakAckHeader2 hdr) { Address sender=msg.getSrc(); if(sender == null) { if(log.isErrorEnabled()) log.error("sender of message is null"); return; } Table<Message> buf=xmit_table.get(sender); if(buf == null) { // discard message if there is no entry for sender if(leaving) return; if(log.isWarnEnabled() && log_discard_msgs) log.warn(local_addr + ": dropped message " + hdr.seqno + " from " + sender + " (sender not in table " + xmit_table.keySet() +"), view=" + view); return; } boolean loopback=local_addr.equals(sender); boolean added=loopback || buf.add(hdr.seqno, msg); if(added && log.isTraceEnabled()) log.trace(new StringBuilder().append(local_addr).append(": received ").append(sender).append('#').append(hdr.seqno)); if(added && msg.isFlagSet(Message.OOB)) { if(loopback) msg=buf.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win ! if(msg != null && msg.isFlagSet(Message.OOB)) { if(msg.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) up_prot.up(new Event(Event.MSG, msg)); } } // Efficient way of checking whether another thread is already processing messages from 'sender'. // If that's the case, we return immediately and let the existing thread process our message // can be returned to the thread pool final AtomicBoolean processing=buf.getProcessing(); if(!processing.compareAndSet(false, true)) { return; } boolean remove_msgs=discard_delivered_msgs && !loopback; boolean released_processing=false; try { while(true) { // we're removing a msg and set processing to false (if null) *atomically* (wrt to add()) List<Message> msgs=buf.removeMany(processing, remove_msgs, max_msg_batch_size); if(msgs == null || msgs.isEmpty()) { released_processing=true; if(rebroadcasting) checkForRebroadcasts(); return; } for(final Message msg_to_deliver: msgs) { if(msg_to_deliver.isFlagSet(Message.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) continue; //msg_to_deliver.removeHeader(getName()); // Changed by bela Jan 29 2003: not needed (see above) try { up_prot.up(new Event(Event.MSG, msg_to_deliver)); } catch(Throwable t) { log.error("couldn't deliver message " + msg_to_deliver, t); } } } } finally { // processing is always set in win.remove(processing) above and never here ! This code is just a // 2nd line of defense should there be an exception before win.remove(processing) sets processing if(!released_processing) processing.set(false); } } /** * Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester, * called when XMIT_REQ is received. * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address * @param missing_msgs A list of seqnos that have to be retransmitted * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null */ protected void handleXmitReq(Address xmit_requester, SeqnoList missing_msgs, Address original_sender) { if(log.isTraceEnabled()) { StringBuilder sb=new StringBuilder(); sb.append(local_addr).append(": received xmit request from ").append(xmit_requester).append(" for "); sb.append(original_sender).append(missing_msgs); log.trace(sb); } if(stats) xmit_reqs_received.addAndGet(missing_msgs.size()); Table<Message> buf=xmit_table.get(original_sender); if(buf == null) { if(log.isErrorEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") ").append(original_sender).append(" not found in retransmission table"); // don't print the table unless we are in trace mode because it can be LARGE if (log.isTraceEnabled()) { sb.append(":\n").append(printMessages()); } if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.error(sb.toString()); } return; } for(long i: missing_msgs) { Message msg=buf.get(i); if(msg == null) { if(log.isWarnEnabled() && log_not_found_msgs && !local_addr.equals(xmit_requester)) { StringBuilder sb=new StringBuilder(); sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); sb.append(") message ").append(original_sender).append("::").append(i); sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(buf); if(print_stability_history_on_failed_xmit) { sb.append(" (stability history:\n").append(printStabilityHistory()); } log.warn(sb.toString()); } continue; } if(log.isTraceEnabled()) log.trace(local_addr + ": resending " + original_sender + "::" + i); sendXmitRsp(xmit_requester, msg); } } protected void cancelRebroadcasting() { rebroadcast_lock.lock(); try { rebroadcasting=false; rebroadcast_done.signalAll(); } finally { rebroadcast_lock.unlock(); } } /** * Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need * to preserve the original message's properties, such as src, headers etc. * @param dest * @param msg */ protected void sendXmitRsp(Address dest, Message msg) { if(msg == null) { if(log.isErrorEnabled()) log.error("message is null, cannot send retransmission"); return; } if(stats) xmit_rsps_sent.incrementAndGet(); if(msg.getSrc() == null) msg.setSrc(local_addr); if(use_mcast_xmit) { // we simply send the original multicast message down_prot.down(new Event(Event.MSG, msg)); return; } Message xmit_msg=msg.copy(true, true); // copy payload and headers xmit_msg.setDest(dest); NakAckHeader2 hdr=(NakAckHeader2)xmit_msg.getHeader(id); hdr.type=NakAckHeader2.XMIT_RSP; // change the type in the copy from MSG --> XMIT_RSP down_prot.down(new Event(Event.MSG,xmit_msg)); } protected void handleXmitRsp(Message msg, NakAckHeader2 hdr) { if(msg == null) return; try { if(stats) xmit_rsps_received.incrementAndGet(); msg.setDest(null); hdr.type=NakAckHeader2.MSG; // change the type back from XMIT_RSP --> MSG up(new Event(Event.MSG, msg)); if(rebroadcasting) checkForRebroadcasts(); } catch(Exception ex) { if(log.isErrorEnabled()) { log.error("failed reading retransmitted message",ex); } } } /** * Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages, * then send retransmit messages for the missing messages. Return when all missing messages have been received. If * we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set. */ protected void rebroadcastMessages() { Digest their_digest; long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS; long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis(); while(wait_time > 0) { rebroadcast_digest_lock.lock(); try { if(rebroadcast_digest == null) break; their_digest=rebroadcast_digest.copy(); } finally { rebroadcast_digest_lock.unlock(); } Digest my_digest=getDigest(); boolean xmitted=false; for(Digest.DigestEntry entry: their_digest) { Address member=entry.getMember(); long[] my_entry=my_digest.get(member); if(my_entry == null) continue; long their_high=entry.getHighest(); // Cannot ask for 0 to be retransmitted because the first seqno in NAKACK2 and UNICAST(2) is always 1 ! // Also, we need to ask for retransmission of my_high+1, because we already *have* my_high, and don't // need it, so the retransmission range is [my_high+1 .. their_high]: *exclude* my_high, but *include* // their_high long my_high=Math.max(1, Math.max(my_entry[0], my_entry[1]) +1); if(their_high > my_high) { if(log.isTraceEnabled()) log.trace("[" + local_addr + "] fetching " + my_high + "-" + their_high + " from " + member); retransmit(my_high, their_high, member, true); // use multicast to send retransmit request xmitted=true; } } if(!xmitted) return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest rebroadcast_lock.lock(); try { try { my_digest=getDigest(); rebroadcast_digest_lock.lock(); try { if(!rebroadcasting || my_digest.isGreaterThanOrEqual(rebroadcast_digest)) return; } finally { rebroadcast_digest_lock.unlock(); } rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS); wait_time-=(System.currentTimeMillis() - start); } catch(InterruptedException e) { } } finally { rebroadcast_lock.unlock(); } } } protected void checkForRebroadcasts() { Digest tmp=getDigest(); boolean cancel_rebroadcasting; rebroadcast_digest_lock.lock(); try { cancel_rebroadcasting=tmp.isGreaterThanOrEqual(rebroadcast_digest); } finally { rebroadcast_digest_lock.unlock(); } if(cancel_rebroadcasting) { cancelRebroadcasting(); } } /** * Remove old members from the retransmission buffers. Essentially removes all members that are not * in <code>members</code>. This method is not called concurrently multiple times */ protected void adjustReceivers(List<Address> new_members) { for(Address member: xmit_table.keySet()) { if(!new_members.contains(member)) { if(local_addr != null && local_addr.equals(member)) continue; Table<Message> buf=xmit_table.remove(member); if(buf != null) { if(log.isDebugEnabled()) log.debug("removed " + member + " from xmit_table (not member anymore)"); } } } } /** * Returns a message digest: for each member P the highest delivered and received seqno is added */ protected Digest getDigest() { final Map<Address,long[]> map=new HashMap<Address,long[]>(); for(Map.Entry<Address,Table<Message>> entry: xmit_table.entrySet()) { Address sender=entry.getKey(); // guaranteed to be non-null (CCHM) Table<Message> buf=entry.getValue(); // guaranteed to be non-null (CCHM) long[] seqnos=buf.getDigest(); map.put(sender, seqnos); } return new Digest(map); } protected Digest getDigest(Address mbr) { if(mbr == null) return getDigest(); Table<Message> buf=xmit_table.get(mbr); if(buf == null) return null; long[] seqnos=buf.getDigest(); return new Digest(mbr, seqnos[0], seqnos[1]); } /** * Creates a retransmit buffer for each sender in the digest according to the sender's seqno. * If a buffer already exists, it resets it. */ protected void setDigest(Digest digest) { setDigest(digest,false); } protected void mergeDigest(Digest digest) { setDigest(digest,true); } /** * Overwrites existing entries, but does NOT remove entries not found in the digest * @param digest */ protected void overwriteDigest(Digest digest) { if(digest == null) return; StringBuilder sb=new StringBuilder("\n[overwriteDigest()]\n"); sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); Table<Message> buf=xmit_table.get(member); if(buf != null) { if(local_addr.equals(member)) { buf.setHighestDelivered(highest_delivered_seqno); continue; // don't destroy my own window } xmit_table.remove(member); } buf=createTable(highest_delivered_seqno); xmit_table.put(member, buf); } sb.append("\n").append("resulting digest: " + getDigest()); digest_history.add(sb.toString()); if(log.isDebugEnabled()) log.debug(sb.toString()); } /** * Sets or merges the digest. If there is no entry for a given member in xmit_table, create a new buffer. * Else skip the existing entry, unless it is a merge. In this case, skip the existing entry if its seqno is * greater than or equal to the one in the digest, or reset the window and create a new one if not. * @param digest The digest * @param merge Whether to merge the new digest with our own, or not */ protected void setDigest(Digest digest, boolean merge) { if(digest == null) return; StringBuilder sb=new StringBuilder(merge? "\n[" + local_addr + " mergeDigest()]\n" : "\n["+local_addr + " setDigest()]\n"); sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); boolean set_own_seqno=false; for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); Table<Message> buf=xmit_table.get(member); if(buf != null) { // We only reset the window if its seqno is lower than the seqno shipped with the digest. Also, we if(!merge || (local_addr != null && local_addr.equals(member)) // never overwrite our own entry || buf.getHighestDelivered() >= highest_delivered_seqno) // my seqno is >= digest's seqno for sender continue; xmit_table.remove(member); // to get here, merge must be false ! if(member.equals(local_addr)) { seqno.set(highest_delivered_seqno); set_own_seqno=true; } } buf=createTable(highest_delivered_seqno); xmit_table.put(member, buf); } sb.append("\n").append("resulting digest: " + getDigest()); if(set_own_seqno) sb.append("\nnew seqno for " + local_addr + ": " + seqno); digest_history.add(sb.toString()); if(log.isDebugEnabled()) log.debug(sb.toString()); } protected Table<Message> createTable(long initial_seqno) { return new Table<Message>(xmit_table_num_rows, xmit_table_msgs_per_row, initial_seqno, xmit_table_resize_factor, xmit_table_max_compaction_time); } /** * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table: * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the * retransmit buffer corresponding to P which are <= seqno at digest[P]. */ protected void stable(Digest digest) { long my_highest_rcvd; // highest seqno received in my digest for a sender P long stability_highest_rcvd; // highest seqno received in the stability vector for a sender P if(members == null || local_addr == null || digest == null) { if(log.isWarnEnabled()) log.warn("members, local_addr or digest are null !"); return; } if(log.isTraceEnabled()) { log.trace("received stable digest " + digest); } stability_msgs.add(digest); for(Digest.DigestEntry entry: digest) { Address member=entry.getMember(); if(member == null) continue; long hd=entry.getHighestDeliveredSeqno(); long hr=entry.getHighestReceivedSeqno(); // check whether the last seqno received for a sender P in the stability vector is > last seqno // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic // in DESIGN) Table<Message> buf=xmit_table.get(member); if(buf != null) { my_highest_rcvd=buf.getHighestReceived(); stability_highest_rcvd=hr; if(stability_highest_rcvd >= 0 && stability_highest_rcvd > my_highest_rcvd) { if(log.isTraceEnabled()) { log.trace("my_highest_rcvd (" + my_highest_rcvd + ") < stability_highest_rcvd (" + stability_highest_rcvd + "): requesting retransmission of " + member + '#' + stability_highest_rcvd); } retransmit(stability_highest_rcvd, stability_highest_rcvd, member); } } if(hd < 0) continue; if(log.isTraceEnabled()) log.trace("deleting msgs <= " + hd + " from " + member); // delete *delivered* msgs that are stable if(buf != null) buf.purge(hd); // delete all messages with seqnos <= seqno } } protected void retransmit(long first_seqno, long last_seqno, Address sender) { if(first_seqno <= last_seqno) retransmit(first_seqno,last_seqno,sender,false); } protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) { retransmit(new SeqnoList(first_seqno,last_seqno),sender,multicast_xmit_request); } protected void retransmit(SeqnoList missing_msgs, final Address sender, boolean multicast_xmit_request) { Address dest=sender; // to whom do we send the XMIT request ? if(multicast_xmit_request || this.use_mcast_xmit_req) { dest=null; } else { if(xmit_from_random_member && !local_addr.equals(sender)) { Address random_member=(Address)Util.pickRandomElement(members); if(random_member != null && !local_addr.equals(random_member)) { dest=random_member; if(log.isTraceEnabled()) log.trace("picked random member " + dest + " to send XMIT request to"); } } } NakAckHeader2 hdr=NakAckHeader2.createXmitRequestHeader(sender); Message retransmit_msg=new Message(dest, null, missing_msgs); retransmit_msg.setFlag(Message.OOB); if(log.isTraceEnabled()) log.trace(local_addr + ": sending XMIT_REQ (" + missing_msgs + ") to " + dest); retransmit_msg.putHeader(this.id, hdr); down_prot.down(new Event(Event.MSG,retransmit_msg)); if(stats) xmit_reqs_sent.addAndGet(missing_msgs.size()); } protected void reset() { seqno.set(0); xmit_table.clear(); } protected static long sizeOfAllMessages(Table<Message> buf, boolean include_headers) { Counter counter=new Counter(include_headers); buf.forEach(buf.getHighestDelivered()+1, buf.getHighestReceived(), counter); return counter.getResult(); } protected void startRetransmitTask() { if(xmit_task == null || xmit_task.isDone()) xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS); } protected void stopRetransmitTask() { if(xmit_task != null) { xmit_task.cancel(true); xmit_task=null; } } /** * Retransmitter task which periodically (every xmit_interval ms) looks at all the retransmit tables and * sends retransmit request to all members from which we have missing messages */ protected class RetransmitTask implements Runnable { public void run() { for(Map.Entry<Address,Table<Message>> entry: xmit_table.entrySet()) { Address target=entry.getKey(); // target to send retransmit requests to Table<Message> buf=entry.getValue(); if(buf.getNumMissing() > 0) { SeqnoList missing=buf.getMissing(); if(missing != null) retransmit(missing, target, false); } } } } protected static class Counter implements Table.Visitor<Message> { protected final boolean count_size; // use size() or length() protected long result=0; public Counter(boolean count_size) { this.count_size=count_size; } public long getResult() {return result;} public boolean visit(long seqno, Message element, int row, int column) { if(element != null) result+=count_size? element.size() : element.getLength(); return true; } } }
//Modul Login /*Steven Sen 064001600022 Dimas Adi Pratama 064001600003 La Ode Muhammad Nurabdulrahma 064001600013 Febriana Tindaon 064001600017 Soefhwan 065001600002 */ import java.util.Scanner; public class Login { public static void main(String[] args) { Scanner input = new Scanner (System.in); String namauser,kode,password,username; String[] Login; Login = new String [10]; Login[0]="Anung"; Login[1]="12345"; Login[2]="Imam"; Login[3]="45678"; for(;;) { System.out.println (""); System.out.print ("Masukkan username = "); namauser = input.nextLine(); System.out.print ("Masukkan password = "); kode = input.nextLine(); if (Login[0].equals(namauser) && Login[1].equals(kode)) { System.out.println ("Login sukses ! "); System.out.println ("Hello Mr.Anung"); System.out.println (""); break; } if (Login[2].equals(namauser) && Login[3].equals(kode)) { System.out.println ("Login sukses ! "); System.out.println ("Hello Mr.Imam"); System.out.println (""); break; } else { System.out.println("Maaf, Login Anda gagal"); } } } }
/* * $Id: BlockingStreamComm.java,v 1.33 2008-02-19 01:35:27 dshr Exp $ */ package org.lockss.protocol; import java.io.*; import java.net.*; import java.security.*; import java.security.cert.*; import javax.net.ssl.*; import java.util.*; import EDU.oswego.cs.dl.util.concurrent.*; import org.lockss.util.*; import org.lockss.util.Queue; import org.lockss.config.*; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.app.*; import org.lockss.poller.*; /** * BlockingStreamComm implements the streaming mesaage protocol using * blocking sockets. */ public class BlockingStreamComm extends BaseLockssDaemonManager implements ConfigurableManager, LcapStreamComm, PeerMessage.Factory { static Logger log = Logger.getLogger("SComm"); public static final String SERVER_NAME = "StreamComm"; /** Use V3 over SSL **/ public static final String PARAM_USE_V3_OVER_SSL = PREFIX + "v3OverSsl"; public static final boolean DEFAULT_USE_V3_OVER_SSL = false; /** Use client authentication for SSL **/ public static final String PARAM_USE_SSL_CLIENT_AUTH = PREFIX + "SslClientAuth"; public static final boolean DEFAULT_USE_SSL_CLIENT_AUTH = true; /** Use temporary SSL keystore**/ public static final String PARAM_SSL_TEMP_KEYSTORE = PREFIX + "SslTempKeystore"; public static final boolean DEFAULT_SSL_TEMP_KEYSTORE = true; /** File name for SSL key store **/ public static final String PARAM_SSL_KEYSTORE = PREFIX + "SslKeyStore"; public static final String DEFAULT_SSL_KEYSTORE = ".keystore"; /** File name for SSL key store password **/ public static final String PARAM_SSL_PRIVATE_KEY_PASSWORD_FILE = PREFIX + "SslPrivateKeyPasswordFile"; public static final String DEFAULT_SSL_PRIVATE_KEY_PASSWORD_FILE = ".password"; /** SSL protocol to use **/ public static final String PARAM_SSL_PROTOCOL = PREFIX + "SslProtocol"; public static final String DEFAULT_SSL_PROTOCOL = "TLSv1"; /** Max peer channels. Only affects outgoing messages; incoming * connections are always accepted. */ public static final String PARAM_MAX_CHANNELS = PREFIX + "maxChannels"; public static final int DEFAULT_MAX_CHANNELS = 50; /** Min threads in channel thread pool */ public static final String PARAM_CHANNEL_THREAD_POOL_MIN = PREFIX + "threadPool.min"; public static final int DEFAULT_CHANNEL_THREAD_POOL_MIN = 3; /** Max threads in channel thread pool */ public static final String PARAM_CHANNEL_THREAD_POOL_MAX = PREFIX + "threadPool.max"; public static final int DEFAULT_CHANNEL_THREAD_POOL_MAX = 3 * DEFAULT_MAX_CHANNELS; /** Duration after which idle threads will be terminated.. -1 = never */ public static final String PARAM_CHANNEL_THREAD_POOL_KEEPALIVE = PREFIX + "threadPool.keepAlive"; public static final long DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE = 10 * Constants.MINUTE; /** Connect timeout */ public static final String PARAM_CONNECT_TIMEOUT = PREFIX + "timeout.connect"; public static final long DEFAULT_CONNECT_TIMEOUT = 2 * Constants.MINUTE; /** Data timeout (SO_TIMEOUT), channel is aborted if read times out. * This should be disabled (zero) because the read side of a channel may * legitimately be idle for a long time (if the channel is sending), and * interrupted reads apparently cannot reliably be resumed. If the * channel is truly idle, the send side should close it. */ public static final String PARAM_DATA_TIMEOUT = PREFIX + "timeout.data"; public static final long DEFAULT_DATA_TIMEOUT = 0; /** Time after which idle channel will be closed */ public static final String PARAM_CHANNEL_IDLE_TIME = PREFIX + "channelIdleTime"; public static final long DEFAULT_CHANNEL_IDLE_TIME = 2 * Constants.MINUTE; /** Time channel remains in DRAIN_INPUT state before closing */ public static final String PARAM_DRAIN_INPUT_TIME = PREFIX + "drainInputTime"; public static final long DEFAULT_DRAIN_INPUT_TIME = 10 * Constants.SECOND; /** Interval at which send thread checks idle timer */ public static final String PARAM_SEND_WAKEUP_TIME = PREFIX + "sendWakeupTime"; public static final long DEFAULT_SEND_WAKEUP_TIME = 1 * Constants.MINUTE; /** FilePeerMessage will be used for messages larger than this, else * MemoryPeerMessage */ public static final String PARAM_MIN_FILE_MESSAGE_SIZE = PREFIX + "minFileMessageSize"; public static final int DEFAULT_MIN_FILE_MESSAGE_SIZE = 1024; /** FilePeerMessage will be used for messages larger than this, else * MemoryPeerMessage */ public static final String PARAM_MAX_MESSAGE_SIZE = PREFIX + "maxMessageSize"; public static final int DEFAULT_MAX_MESSAGE_SIZE = 1024 * 1024; /** Dir for PeerMessage data storage */ public static final String PARAM_DATA_DIR = PREFIX + "messageDataDir"; /** Default is PlatformInfo.getSystemTempDir() */ public static final String DEFAULT_DATA_DIR = "Platform tmp dir"; /** Wrap Socket OutputStream in BufferedOutputStream? */ public static final String PARAM_IS_BUFFERED_SEND = PREFIX + "bufferedSend"; public static final boolean DEFAULT_IS_BUFFERED_SEND = true; /** TCP_NODELAY */ public static final String PARAM_TCP_NODELAY = PREFIX + "tcpNodelay"; public static final boolean DEFAULT_TCP_NODELAY = true; /** Amount of time BlockingStreamComm.stopService() should wait for * worker threads to exit. Zero disables wait. */ public static final String PARAM_WAIT_EXIT = PREFIX + "waitExit"; public static final long DEFAULT_WAIT_EXIT = 2 * Constants.SECOND; static final String WDOG_PARAM_SCOMM = "SComm"; static final long WDOG_DEFAULT_SCOMM = 1 * Constants.HOUR; static final String PRIORITY_PARAM_SCOMM = "SComm"; static final int PRIORITY_DEFAULT_SCOMM = -1; static final String PRIORITY_PARAM_SLISTEN = "SListen"; static final int PRIORITY_DEFAULT_SLISTEN = -1; static final String WDOG_PARAM_CHANNEL = "Channel"; static final long WDOG_DEFAULT_CHANNEL = 30 * Constants.MINUTE; static final String PRIORITY_PARAM_CHANNEL = "Channel"; static final int PRIORITY_DEFAULT_CHANNEL = -1; private boolean paramUseV3OverSsl = DEFAULT_USE_V3_OVER_SSL; private boolean paramSslClientAuth = DEFAULT_USE_SSL_CLIENT_AUTH; private boolean paramSslTempKeystore = DEFAULT_SSL_TEMP_KEYSTORE; private String paramSslKeyStore = DEFAULT_SSL_KEYSTORE; private String paramSslPrivateKeyPasswordFile = DEFAULT_SSL_PRIVATE_KEY_PASSWORD_FILE; private String paramSslProtocol = DEFAULT_SSL_PROTOCOL; private int paramMinFileMessageSize = DEFAULT_MIN_FILE_MESSAGE_SIZE; private int paramMaxMessageSize = DEFAULT_MAX_MESSAGE_SIZE; private File dataDir = null; private int paramBacklog = DEFAULT_LISTEN_BACKLOG; private int paramMaxChannels = DEFAULT_MAX_CHANNELS; private int paramMinPoolSize = DEFAULT_CHANNEL_THREAD_POOL_MIN; private int paramMaxPoolSize = DEFAULT_CHANNEL_THREAD_POOL_MAX; private long paramPoolKeepaliveTime = DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE; private long paramConnectTimeout = DEFAULT_CONNECT_TIMEOUT; private long paramSoTimeout = DEFAULT_DATA_TIMEOUT; private long paramSendWakeupTime = DEFAULT_SEND_WAKEUP_TIME; protected long paramChannelIdleTime = DEFAULT_CHANNEL_IDLE_TIME; private long paramDrainInputTime = DEFAULT_DRAIN_INPUT_TIME; private boolean paramIsBufferedSend = DEFAULT_IS_BUFFERED_SEND; private boolean paramIsTcpNodelay = DEFAULT_TCP_NODELAY; private long paramWaitExit = DEFAULT_WAIT_EXIT; private long lastHungCheckTime = 0; private PooledExecutor pool; protected SSLSocketFactory sslSocketFactory = null; protected SSLServerSocketFactory sslServerSocketFactory = null; private String paramSslKeyStorePassword = null; private boolean enabled = DEFAULT_ENABLED; private boolean running = false; private SocketFactory sockFact; private ServerSocket listenSock; private PeerIdentity myPeerId; private PeerAddress.Tcp myPeerAddr; private IdentityManager idMgr; private OneShot configShot = new OneShot(); private FifoQueue rcvQueue; // PeerMessages received from channels private ReceiveThread rcvThread; private ListenThread listenThread; // Synchronization lock for rcv thread, listen thread manipulations private Object threadLock = new Object(); // Maps PeerIdentity to primary PeerChannel (and used as lock for both maps) MaxSizeRecordingMap channels = new MaxSizeRecordingMap(); // Maps PeerIdentity to secondary PeerChannel MaxSizeRecordingMap rcvChannels = new MaxSizeRecordingMap(); Set<BlockingPeerChannel> drainingChannels = new HashSet(); int maxDrainingChannels = 0; ChannelStats globalStats = new ChannelStats(); private Vector messageHandlers = new Vector(); // Vector is synchronized public BlockingStreamComm() { sockFact = null; } /** * start the stream comm manager. */ public void startService() { super.startService(); LockssDaemon daemon = getDaemon(); idMgr = daemon.getIdentityManager(); resetConfig(); try { myPeerId = getLocalPeerIdentity(); } catch (Exception e) { log.critical("No V3 identity, not starting stream comm", e); enabled = false; return; } log.debug("Local V3 peer: " + myPeerId); try { PeerAddress pad = myPeerId.getPeerAddress(); if (pad instanceof PeerAddress.Tcp) { myPeerAddr = (PeerAddress.Tcp)pad; } else { log.error("Disabling stream comm; no local TCP peer address: " + pad); enabled = false; } } catch (IdentityManager.MalformedIdentityKeyException e) { log.error("Disabling stream comm; local address malformed", e); enabled = false; } if (enabled) { start(); daemon.getStatusService(). registerStatusAccessor(getStatusAccessorName("SCommChans"), new ChannelStatus()); } } protected String getStatusAccessorName(String base) { return base; } /** * stop the stream comm manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { getDaemon().getStatusService(). unregisterStatusAccessor(getStatusAccessorName("SCommChans")); if (running) { stop(); } super.stopService(); } /** * Set communication parameters from configuration, once only. * This service currently cannot be reconfigured. * @param config the Configuration */ public void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { if (getDaemon().isDaemonInited()) { // one-time only init if (configShot.once()) { configure(config, prevConfig, changedKeys); } // these params can be changed on the fly paramMinFileMessageSize = config.getInt(PARAM_MIN_FILE_MESSAGE_SIZE, DEFAULT_MIN_FILE_MESSAGE_SIZE); paramMaxMessageSize = config.getInt(PARAM_MAX_MESSAGE_SIZE, DEFAULT_MAX_MESSAGE_SIZE); paramIsBufferedSend = config.getBoolean(PARAM_IS_BUFFERED_SEND, DEFAULT_IS_BUFFERED_SEND); paramIsTcpNodelay = config.getBoolean(PARAM_TCP_NODELAY, DEFAULT_TCP_NODELAY); paramWaitExit = config.getTimeInterval(PARAM_WAIT_EXIT, DEFAULT_WAIT_EXIT); if (changedKeys.contains(PARAM_DATA_DIR)) { String paramDataDir = config.get(PARAM_DATA_DIR, PlatformUtil.getSystemTempDir()); File dir = new File(paramDataDir); if (FileUtil.ensureDirExists(dir)) { dataDir = dir; log.debug2("Message data dir: " + dataDir); } else { log.warning("No message data dir: " + dir); dataDir = null; } } paramMaxChannels = config.getInt(PARAM_MAX_CHANNELS, DEFAULT_MAX_CHANNELS); paramConnectTimeout = config.getTimeInterval(PARAM_CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT); paramSoTimeout = config.getTimeInterval(PARAM_DATA_TIMEOUT, DEFAULT_DATA_TIMEOUT); paramSendWakeupTime = config.getTimeInterval(PARAM_SEND_WAKEUP_TIME, DEFAULT_SEND_WAKEUP_TIME); paramChannelIdleTime = config.getTimeInterval(PARAM_CHANNEL_IDLE_TIME, DEFAULT_CHANNEL_IDLE_TIME); paramDrainInputTime = config.getTimeInterval(PARAM_DRAIN_INPUT_TIME, DEFAULT_DRAIN_INPUT_TIME); } } /** Internal config, so can invoke from test constructor */ void configure(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) { enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED); if (!enabled) { return; } paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN, DEFAULT_CHANNEL_THREAD_POOL_MIN); paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX, DEFAULT_CHANNEL_THREAD_POOL_MAX); paramPoolKeepaliveTime = config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE, DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE); if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) { paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL, DEFAULT_USE_V3_OVER_SSL); sockFact = null; // XXX shut down old listen socket, do exponential backoff // XXX on bind() to bring up new listen socket // XXX then move this to the "change on the fly" above } if (!paramUseV3OverSsl) return; // We're trying to use SSL if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) { paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH, DEFAULT_USE_SSL_CLIENT_AUTH); sockFact = null; } if (changedKeys.contains(PARAM_SSL_TEMP_KEYSTORE)) { paramSslTempKeystore = config.getBoolean(PARAM_SSL_TEMP_KEYSTORE, DEFAULT_SSL_TEMP_KEYSTORE); sockFact = null; } if (sslServerSocketFactory != null && sslSocketFactory != null) { // already initialized return; } if (paramSslTempKeystore) { // We're using the temporary keystore paramSslKeyStore = System.getProperty("javax.net.ssl.keyStore", null); paramSslKeyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword", null); log.debug("Using temporary keystore from " + paramSslKeyStore); // Now create the SSL socket factories from the context sslServerSocketFactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); return; } // We're using the real keystore if (changedKeys.contains(PARAM_SSL_KEYSTORE)) { paramSslKeyStore = config.get(PARAM_SSL_KEYSTORE, DEFAULT_SSL_KEYSTORE); // The password for the keystore is the machine's FQDN. paramSslKeyStorePassword = config.get("org.lockss.platform.fqdn", ""); log.debug("Using permanent keystore from " + paramSslKeyStore); sockFact = null; } byte[] sslPrivateKeyPassword = null; if (changedKeys.contains(PARAM_SSL_PRIVATE_KEY_PASSWORD_FILE)) { paramSslPrivateKeyPasswordFile = config.get(PARAM_SSL_PRIVATE_KEY_PASSWORD_FILE, DEFAULT_SSL_PRIVATE_KEY_PASSWORD_FILE); sockFact = null; } if (changedKeys.contains(PARAM_SSL_PROTOCOL)) { paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL); sockFact = null; } try { File keyStorePasswordFile = new File(paramSslPrivateKeyPasswordFile); if (keyStorePasswordFile.exists()) { FileInputStream fis = new FileInputStream(keyStorePasswordFile); sslPrivateKeyPassword = new byte[(int)keyStorePasswordFile.length()]; if (fis.read(sslPrivateKeyPassword) != sslPrivateKeyPassword.length) { throw new IOException("short read"); } fis.close(); FileOutputStream fos = new FileOutputStream(keyStorePasswordFile); byte[] junk = new byte[(int)keyStorePasswordFile.length()]; for (int i = 0; i < junk.length; i++) junk[i] = 0; fos.write(junk); fos.close(); keyStorePasswordFile.delete(); } else { log.debug("SSL password file " + paramSslPrivateKeyPasswordFile + " missing"); return; } } catch (IOException ex) { log.error(paramSslPrivateKeyPasswordFile + " threw " + ex); return; } // We now have a password to decrypt the private key in the // SSL keystore. Next create the keystore from the file. KeyStore keyStore = null; InputStream fis = null; try { keyStore = KeyStore.getInstance("JCEKS"); fis = new FileInputStream(paramSslKeyStore); keyStore.load(fis, paramSslKeyStorePassword.toCharArray()); } catch (KeyStoreException ex) { log.error("loading SSL key store threw " + ex); return; } catch (IOException ex) { log.error("loading SSL key store threw " + ex); return; } catch (NoSuchAlgorithmException ex) { log.error("loading SSL key store threw " + ex); return; } catch (CertificateException ex) { log.error("loading SSL key store threw " + ex); return; } finally { IOUtil.safeClose(fis); } { String temp = new String(sslPrivateKeyPassword); logKeyStore(keyStore, temp.toCharArray()); } // Now create a KeyManager from the keystore using the password. KeyManager[] kma = null; try { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, new String(sslPrivateKeyPassword).toCharArray()); kma = kmf.getKeyManagers(); } catch (NoSuchAlgorithmException ex) { log.error("creating SSL key manager threw " + ex); return; } catch (KeyStoreException ex) { log.error("creating SSL key manager threw " + ex); return; } catch (UnrecoverableKeyException ex) { log.error("creating SSL key manager threw " + ex); return; } // Now create a TrustManager from the keystore using the password TrustManager[] tma = null; try { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); tma = tmf.getTrustManagers(); } catch (NoSuchAlgorithmException ex) { log.error("creating SSL trust manager threw " + ex); return; } catch (KeyStoreException ex) { log.error("creating SSL trust manager threw " + ex); return; } finally { // Now forget the password for (int i = 0; i < sslPrivateKeyPassword.length; i++) { sslPrivateKeyPassword[i] = 0; } sslPrivateKeyPassword = null; } // Now create an SSLContext from the KeyManager SSLContext sslContext = null; try { sslContext = SSLContext.getInstance(paramSslProtocol); sslContext.init(kma, tma, null); // Now create the SSL socket factories from the context sslServerSocketFactory = sslContext.getServerSocketFactory(); sslSocketFactory = sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException ex) { log.error("Creating SSL context threw " + ex); sslContext = null; } catch (KeyManagementException ex) { log.error("Creating SSL context threw " + ex); sslContext = null; } } // private debug output of keystore private void logKeyStore(KeyStore ks, char[] privateKeyPassWord) { log.debug3("start of key store"); try { for (Enumeration en = ks.aliases(); en.hasMoreElements(); ) { String alias = (String) en.nextElement(); log.debug3("Next alias " + alias); if (ks.isCertificateEntry(alias)) { log.debug3("About to Certificate"); java.security.cert.Certificate cert = ks.getCertificate(alias); if (cert == null) { log.debug3(alias + " null cert chain"); } else { log.debug3("Cert for " + alias + " is " + cert.toString()); } } else if (ks.isKeyEntry(alias)) { log.debug3("About to getKey"); Key privateKey = ks.getKey(alias, privateKeyPassWord); log.debug3(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat()); } else { log.debug3(alias + " neither key nor cert"); } } log.debug3("end of key store"); } catch (Exception ex) { log.error("logKeyStore() threw " + ex); } } // overridable for testing protected PeerIdentity getLocalPeerIdentity() { return idMgr.getLocalPeerIdentity(Poll.V3_PROTOCOL); } PeerIdentity findPeerIdentity(String idkey) { return idMgr.findPeerIdentity(idkey); } PeerIdentity getMyPeerId() { return myPeerId; } Queue getReceiveQueue() { return rcvQueue; } SocketFactory getSocketFactory() { if (sockFact == null) if (paramUseV3OverSsl) { sockFact = new SslSocketFactory(); } else { sockFact = new NormalSocketFactory(); } return sockFact; } long getConnectTimeout() { return paramConnectTimeout; } long getSoTimeout() { return paramSoTimeout; } long getSendWakeupTime() { return paramSendWakeupTime; } long getChannelIdleTime() { return paramChannelIdleTime; } long getDrainInputTime() { return paramDrainInputTime; } long getChannelHungTime() { return paramChannelIdleTime + 1000; } int getMaxMessageSize() { return paramMaxMessageSize; } boolean isBufferedSend() { return paramIsBufferedSend; } boolean isTcpNodelay() { return paramIsTcpNodelay; } /** * Called by channel when it learns its peer's identity */ void associateChannelWithPeer(BlockingPeerChannel chan, PeerIdentity peer) { synchronized (channels) { BlockingPeerChannel currentChan = (BlockingPeerChannel)channels.get(peer); if (currentChan == null) { channels.put(peer, chan); // normal association log.debug2("Associated " + chan); } else if (currentChan == chan) { log.warning("Redundant peer-channel association (" + chan + ")"); } else { BlockingPeerChannel rcvChan = (BlockingPeerChannel)rcvChannels.get(peer); if (rcvChan == null) { rcvChannels.put(peer, chan); // normal secondary association log.debug2("Associated secondary " + chan); } else if (rcvChan == chan) { log.debug2("Redundant secondary peer-channel association(" + chan +")"); } else { // maybe should replace if new working and old not. but old will // eventually timeout and close anyway log.warning("Conflicting peer-channel association(" + chan + "), was " + peer); } } } } /** * Called by channel when closing */ void dissociateChannelFromPeer(BlockingPeerChannel chan, PeerIdentity peer) { synchronized (channels) { BlockingPeerChannel currentChan = (BlockingPeerChannel)channels.get(peer); if (currentChan == chan) { globalStats.add(chan.getStats()); channels.remove(peer); log.debug2("Removed: " + chan); } BlockingPeerChannel rcvChan = (BlockingPeerChannel)rcvChannels.get(peer); if (rcvChan == chan) { globalStats.add(chan.getStats()); rcvChannels.remove(peer); log.debug2("Removed secondary: " + chan); } drainingChannels.remove(chan); } } /** * Called by channel when draining channel is dissociated, so it can be * included in stats */ void addDrainingChannel(BlockingPeerChannel chan) { drainingChannels.add(chan); if (drainingChannels.size() > maxDrainingChannels) { maxDrainingChannels = drainingChannels.size(); } } /** * Return an existing channel for the peer or create and start one */ BlockingPeerChannel findOrMakeChannel(PeerIdentity pid) throws IOException { synchronized (channels) { BlockingPeerChannel chan = (BlockingPeerChannel)channels.get(pid); if (chan != null) { return chan; } chan = (BlockingPeerChannel)rcvChannels.get(pid); if (chan != null) { // found secondary, no primary. promote secondary to primary channels.put(pid, chan); rcvChannels.remove(pid); log.debug2("Promoted " + chan); return chan; } // new primary channel, if we have room if (channels.size() >= paramMaxChannels) { // need to maintain queue of messages waiting for active channel? throw new IOException("Too many open channels"); } chan = getSocketFactory().newPeerChannel(this, pid); channels.put(pid, chan); log.debug2("Added " + chan); try { chan.startOriginate(); return chan; } catch (IOException e) { log.warning("Can't make channel", e); channels.remove(pid); log.debug2("Removed " + chan); throw e; } } } /** Send a message to a peer. * @param msg the message to send * @param id the identity of the peer to which to send the message * @throws IOException if message couldn't be queued */ public void sendTo(PeerMessage msg, PeerIdentity id, RateLimiter limiter) throws IOException { if (!running) throw new IllegalStateException("SComm not running"); if (msg == null) throw new NullPointerException("Null message"); if (id == null) throw new NullPointerException("Null peer"); if (log.isDebug3()) log.debug3("sending "+ msg +" to "+ id); if (limiter == null || limiter.isEventOk()) { sendToChannel(msg, id); if (limiter != null) limiter.event(); } else { log.debug2("Pkt rate limited"); } } private void sendToChannel(PeerMessage msg, PeerIdentity id) throws IOException { // closing channel might refuse the message (return false), in which // case it will have removed itself so try again with a new channel BlockingPeerChannel last = null; for (int rpt = 0; rpt < 3; rpt++) { BlockingPeerChannel chan = findOrMakeChannel(id); if (last == chan) throw new IllegalStateException("Got same channel as last time: " + chan); if (chan.send(msg)) { return; } if (!chan.wasOpen()) { log.warning("Couldn't start channel"); return; } last = chan; } log.error("Couldn't enqueue msg after 3 tries: " + msg); } void start() { pool = new PooledExecutor(paramMaxPoolSize); pool.setMinimumPoolSize(paramMinPoolSize); pool.setKeepAliveTime(paramPoolKeepaliveTime); log.debug2("Channel thread pool min, max: " + pool.getMinimumPoolSize() + ", " + pool.getMaximumPoolSize()); pool.abortWhenBlocked(); rcvQueue = new FifoQueue(); try { int port = myPeerAddr.getPort(); if (!getDaemon().getResourceManager().reserveTcpPort(port, SERVER_NAME)) { throw new IOException("TCP port " + port + " unavailable"); } log.debug("Listening on port " + port); listenSock = getSocketFactory().newServerSocket(port, paramBacklog); } catch (IOException e) { log.critical("Can't create listen socket", e); return; } ensureQRunner(); ensureListener(); running = true; } void ensureQRunner() { synchronized (threadLock) { if (rcvThread == null) { log.info("Starting receive thread"); rcvThread = new ReceiveThread("SCommRcv: " + myPeerId.getIdString()); rcvThread.start(); rcvThread.waitRunning(); } } } void ensureListener() { synchronized (threadLock) { if (listenThread == null) { log.info("Starting listen thread"); listenThread = new ListenThread("SCommListen: " + myPeerId.getIdString()); listenThread.start(); listenThread.waitRunning(); } } } // stop all threads and channels void stop() { running = false; Deadline timeout = null; synchronized (threadLock) { if (paramWaitExit > 0) { timeout = Deadline.in(paramWaitExit); } ListenThread lth = listenThread; if (lth != null) { log.info("Stopping listen thread"); lth.stopListenThread(); if (timeout != null) { lth.waitExited(timeout); } listenThread = null; } ReceiveThread rth = rcvThread; if (rth != null) { log.info("Stopping receive thread"); rth.stopRcvThread(); if (timeout != null) { rth.waitExited(timeout); } rcvThread = null; } } stopChannels(channels, timeout); stopChannels(rcvChannels, timeout); log.debug2("shutting down pool"); if (pool != null) { pool.shutdownNow(); } log.debug2("pool shut down "); } // stop all channels in channel map void stopChannels(Map map, Deadline timeout) { List lst; synchronized (channels) { // make copy while map is locked lst = new ArrayList(map.values()); } for (Iterator iter = lst.iterator(); iter.hasNext(); ) { BlockingPeerChannel chan = (BlockingPeerChannel)iter.next(); chan.abortChannel(); } // Wait until the threads have exited before proceeding. Useful in // testing to keep debug output straight. // Any channels that had already dissociated themselves are not waited // for. It would take extra bookkeeping to handle those and they don't // seem to cause nearly as much trouble. if (timeout != null) { for (Iterator iter = lst.iterator(); iter.hasNext(); ) { BlockingPeerChannel chan = (BlockingPeerChannel)iter.next(); chan.waitThreadsExited(timeout); } } } // poke channels that might have hung sender void checkHungChannels() { log.debug3("Doing hung check"); List lst; synchronized (channels) { // make copy while map is locked lst = new ArrayList(channels.values()); } for (Iterator iter = lst.iterator(); iter.hasNext(); ) { BlockingPeerChannel chan = (BlockingPeerChannel)iter.next(); chan.checkHung(); } } /** * Execute the runnable in a pool thread * @param run the Runnable to be run * @throws RuntimeException if no pool thread is available */ void execute(Runnable run) throws InterruptedException { if (run == null) log.warning("Executing null", new Throwable()); pool.execute(run); } void XXXexecute(Runnable run) { try { if (run == null) log.warning("Executing null", new Throwable()); pool.execute(run); } catch (InterruptedException e) { // Shouldn't happen in abortWhenBlocked mode log.warning("Shouldn't happen", e); throw new RuntimeException("InterruptedException in pool.excute(): " + e.toString()); } } // process a socket returned by accept() // overridable for testing void processIncomingConnection(Socket sock) throws IOException { if (sock.isClosed()) { throw new SocketException("socket closed during handshake"); } log.debug2("Accepted connection from " + new IPAddr(sock.getInetAddress())); BlockingPeerChannel chan = getSocketFactory().newPeerChannel(this, sock); chan.startIncoming(); } private void processReceivedPacket(PeerMessage msg) { log.debug2("Received " + msg); try { runHandlers(msg); } catch (ProtocolException e) { log.warning("Cannot process incoming packet", e); } } protected void runHandler(MessageHandler handler, PeerMessage msg) { try { handler.handleMessage(msg); } catch (Exception e) { log.error("callback threw", e); } } private void runHandlers(PeerMessage msg) throws ProtocolException { try { int proto = msg.getProtocol(); MessageHandler handler; if (proto >= 0 && proto < messageHandlers.size() && (handler = (MessageHandler)messageHandlers.get(proto)) != null) { runHandler(handler, msg); } else { log.warning("Received message with unregistered protocol: " + proto); } } catch (RuntimeException e) { log.warning("Unexpected error in runHandlers", e); throw new ProtocolException(e.toString()); } } /** * Register a {@link LcapStreamComm.MessageHandler}, which will be called * whenever a message is received. * @param protocol an int representing the protocol * @param handler MessageHandler to add */ public void registerMessageHandler(int protocol, MessageHandler handler) { synchronized (messageHandlers) { if (protocol >= messageHandlers.size()) { messageHandlers.setSize(protocol + 1); } if (messageHandlers.get(protocol) != null) { throw new RuntimeException("Protocol " + protocol + " already registered"); } messageHandlers.set(protocol, handler); } } /** * Unregister a {@link LcapStreamComm.MessageHandler}. * @param protocol an int representing the protocol */ public void unregisterMessageHandler(int protocol) { if (protocol < messageHandlers.size()) { messageHandlers.set(protocol, null); } } // PeerMessage.Factory implementation public PeerMessage newPeerMessage() { return new MemoryPeerMessage(); } public PeerMessage newPeerMessage(int estSize) { if (estSize < 0) { return newPeerMessage(); } else if (estSize > 0 && dataDir != null && estSize >= paramMinFileMessageSize) { return new FilePeerMessage(dataDir); } else { return new MemoryPeerMessage(); } } protected void handShake(SSLSocket s) { SSLSession session = s.getSession(); try { java.security.cert.Certificate[] certs = session.getPeerCertificates(); log.debug(session.getPeerHost() + " via " + session.getProtocol() + " verified"); } catch (SSLPeerUnverifiedException ex) { log.error(s.getInetAddress() + " not verified"); try { s.close(); } catch (IOException ex2) { log.error("Socket close threw " + ex2); } } } // Receive thread private class ReceiveThread extends LockssThread { private volatile boolean goOn = true; private Deadline timeout = Deadline.in(getChannelHungTime()); ReceiveThread(String name) { super(name); } public void lockssRun() { setPriority(PRIORITY_PARAM_SCOMM, PRIORITY_DEFAULT_SCOMM); triggerWDogOnExit(true); startWDog(WDOG_PARAM_SCOMM, WDOG_DEFAULT_SCOMM); nowRunning(); while (goOn) { pokeWDog(); try { synchronized (timeout) { if (goOn) { timeout.expireIn(getChannelHungTime()); } } if (log.isDebug3()) log.debug3("rcvQueue.get(" + timeout + ")"); Object qObj = rcvQueue.get(timeout); if (qObj != null) { if (qObj instanceof PeerMessage) { if (log.isDebug3()) log.debug3("Rcvd " + qObj); processReceivedPacket((PeerMessage)qObj); } else { log.warning("Non-PeerMessage on rcv queue" + qObj); } } if (TimeBase.msSince(lastHungCheckTime) > getChannelHungTime()) { checkHungChannels(); lastHungCheckTime = TimeBase.nowMs(); } } catch (InterruptedException e) { // just wake up and check for exit } finally { } } rcvThread = null; } private void stopRcvThread() { synchronized (timeout) { stopWDog(); triggerWDogOnExit(false); goOn = false; timeout.expire(); } } } // Listen thread private class ListenThread extends LockssThread { private volatile boolean goOn = true; private ListenThread(String name) { super(name); } public void lockssRun() { setPriority(PRIORITY_PARAM_SLISTEN, PRIORITY_DEFAULT_SLISTEN); triggerWDogOnExit(true); // startWDog(WDOG_PARAM_SLISTEN, WDOG_DEFAULT_SLISTEN); nowRunning(); while (goOn) { // pokeWDog(); log.debug3("accept()"); try { Socket sock = listenSock.accept(); if (sock instanceof SSLSocket && paramSslClientAuth) { // Ensure handshake is complete before doing anything else handShake((SSLSocket)sock); } processIncomingConnection(sock); } catch (SocketException e) { if (goOn) { log.warning("Listener", e); } } catch (Exception e) { if (listenSock instanceof SSLServerSocket) { log.debug("SSL Listener ", e); } else { log.warning("Listener", e); } } } listenThread = null; } private void stopListenThread() { stopWDog(); triggerWDogOnExit(false); goOn = false; IOUtil.safeClose(listenSock); this.interrupt(); } } /** SocketFactory interface allows test code to use instrumented or mock sockets and peer channels */ interface SocketFactory { ServerSocket newServerSocket(int port, int backlog) throws IOException; Socket newSocket(IPAddr addr, int port) throws IOException; BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, Socket sock) throws IOException; BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, PeerIdentity peer) throws IOException; } /** Normal socket factory creates real TCP Sockets */ class NormalSocketFactory implements SocketFactory { public ServerSocket newServerSocket(int port, int backlog) throws IOException { return new ServerSocket(port, backlog); } public Socket newSocket(IPAddr addr, int port) throws IOException { return new Socket(addr.getInetAddr(), port); } public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, Socket sock) throws IOException { return new BlockingPeerChannel(comm, sock); } public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, PeerIdentity peer) throws IOException { return new BlockingPeerChannel(comm, peer); } } /** SSL socket factory */ class SslSocketFactory implements SocketFactory { public ServerSocket newServerSocket(int port, int backlog) throws IOException { if (sslServerSocketFactory == null) { throw new IOException("no SSL server socket factory"); } SSLServerSocket s = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port, backlog); s.setNeedClientAuth(paramSslClientAuth); log.debug("New SSL server socket: " + port + " backlog " + backlog + " clientAuth " + paramSslClientAuth); String cs[] = s.getEnabledCipherSuites(); for (int i = 0; i < cs.length; i++) { log.debug2(cs[i] + " enabled cipher suite"); } cs = s.getSupportedCipherSuites(); for (int i = 0; i < cs.length; i++) { log.debug2(cs[i] + " supported cipher suite"); } cs = s.getEnabledProtocols(); for (int i = 0; i < cs.length; i++) { log.debug2(cs[i] + " enabled protocol"); } cs = s.getSupportedProtocols(); for (int i = 0; i < cs.length; i++) { log.debug2(cs[i] + " supported protocol"); } log.debug2("enable session creation " + s.getEnableSessionCreation()); return s; } public Socket newSocket(IPAddr addr, int port) throws IOException { if (sslSocketFactory == null) { throw new IOException("no SSL client socket factory"); } SSLSocket s = (SSLSocket) sslSocketFactory.createSocket(addr.getInetAddr(), port); log.debug2("New SSL client socket: " + port + "@" + addr.toString()); if (paramSslClientAuth) { handShake(s); } return s; } public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, Socket sock) throws IOException { return new BlockingPeerChannel(comm, sock); } public BlockingPeerChannel newPeerChannel(BlockingStreamComm comm, PeerIdentity peer) throws IOException { return new BlockingPeerChannel(comm, peer); } } private static final List statusColDescs = ListUtil.list( new ColumnDescriptor("Peer", "Peer", ColumnDescriptor.TYPE_STRING) ); private class Status implements StatusAccessor, StatusAccessor.DebugOnly { // port, proto, u/m, direction, compressed, pkts, bytes long start; public String getDisplayName() { return "Comm Statistics"; } public boolean requiresKey() { return false; } public void populateTable(StatusTable table) { // table.setResortable(false); // table.setDefaultSortRules(statusSortRules); String key = table.getKey(); table.setColumnDescriptors(statusColDescs); table.setRows(getRows(key)); table.setSummaryInfo(getSummaryInfo(key)); } private List getSummaryInfo(String key) { List res = new ArrayList(); res.add(new StatusTable.SummaryInfo("Max channels", ColumnDescriptor.TYPE_INT, channels.getMaxSize())); res.add(new StatusTable.SummaryInfo("Max rcvChannels", ColumnDescriptor.TYPE_INT, rcvChannels.getMaxSize())); return res; } private List getRows(String key) { List table = new ArrayList(); synchronized (channels) { for (Iterator iter = channels.entrySet().iterator(); iter.hasNext();) { Map.Entry ent = (Map.Entry)iter.next(); PeerIdentity pid = (PeerIdentity)ent.getKey(); BlockingPeerChannel chan = (BlockingPeerChannel)ent.getValue(); table.add(makeRow(pid, chan)); } } return table; } private Map makeRow(PeerIdentity pid, BlockingPeerChannel chan) { Map row = new HashMap(); row.put("Peer", pid.getIdString()); return row; } } private static final List chanStatusColDescs = ListUtil.list( new ColumnDescriptor("Peer", "Peer", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("State", "State", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("Flags", "Flags", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("SendQ", "SendQ", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("Sent", "Msgs Sent", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("Rcvd", "Msgs Rcvd", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("SentBytes", "Bytes Sent", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("RcvdBytes", "Bytes Rcvd", ColumnDescriptor.TYPE_INT), new ColumnDescriptor("LastSend", "LastSend", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("LastRcv", "LastRcv", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("PrevState", "PrevState", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("PrevStateChange", "Change", ColumnDescriptor.TYPE_STRING) ); private class ChannelStatus implements StatusAccessor { long start; public String getDisplayName() { return "Comm Channels"; } public boolean requiresKey() { return false; } public void populateTable(StatusTable table) { // table.setResortable(false); // table.setDefaultSortRules(statusSortRules); String key = table.getKey(); ChannelStats cumulative = new ChannelStats(); table.setColumnDescriptors(chanStatusColDescs); table.setRows(getRows(key, cumulative)); cumulative.add(globalStats); table.setSummaryInfo(getSummaryInfo(key, cumulative)); } private List getSummaryInfo(String key, ChannelStats stats) { List res = new ArrayList(); res.add(new StatusTable.SummaryInfo("Channels", ColumnDescriptor.TYPE_STRING, channels.size() + "/" + paramMaxChannels + ", " + channels.getMaxSize() + " max")); res.add(new StatusTable.SummaryInfo("RcvChannels", ColumnDescriptor.TYPE_STRING, rcvChannels.size() + ", " + rcvChannels.getMaxSize() +" max")); res.add(new StatusTable.SummaryInfo("Draining", ColumnDescriptor.TYPE_STRING, drainingChannels.size() + ", " + maxDrainingChannels + " max")); ChannelStats.Count count = stats.getInCount(); res.add(new StatusTable.SummaryInfo("Msgs Sent", ColumnDescriptor.TYPE_INT, count.getMsgs())); res.add(new StatusTable.SummaryInfo("Bytes Sent", ColumnDescriptor.TYPE_INT, count.getBytes())); count = stats.getOutCount(); res.add(new StatusTable.SummaryInfo("Msgs Rcvd", ColumnDescriptor.TYPE_INT, count.getMsgs())); res.add(new StatusTable.SummaryInfo("Bytes Rcvd", ColumnDescriptor.TYPE_INT, count.getBytes())); return res; } private List getRows(String key, ChannelStats cumulative) { List table = new ArrayList(); synchronized (channels) { for (Iterator iter = channels.entrySet().iterator(); iter.hasNext();) { Map.Entry ent = (Map.Entry)iter.next(); PeerIdentity pid = (PeerIdentity)ent.getKey(); BlockingPeerChannel chan = (BlockingPeerChannel)ent.getValue(); table.add(makeRow(pid, chan, "", cumulative)); } for (Iterator iter = rcvChannels.entrySet().iterator(); iter.hasNext();) { Map.Entry ent = (Map.Entry)iter.next(); PeerIdentity pid = (PeerIdentity)ent.getKey(); BlockingPeerChannel chan = (BlockingPeerChannel)ent.getValue(); table.add(makeRow(pid, chan, "2", cumulative)); } for (BlockingPeerChannel chan : drainingChannels) { table.add(makeRow(chan.getPeer(), chan, "D", cumulative)); } } return table; } private Map makeRow(PeerIdentity pid, BlockingPeerChannel chan, String flags, ChannelStats cumulative) { Map row = new HashMap(); row.put("Peer", pid.getIdString()); row.put("State", chan.getState()); row.put("SendQ", chan.getSendQueueSize()); ChannelStats stats = chan.getStats(); cumulative.add(stats); ChannelStats.Count count = stats.getInCount(); row.put("Sent", count.getMsgs()); row.put("SentBytes", count.getBytes()); count = stats.getOutCount(); row.put("Rcvd", count.getMsgs()); row.put("RcvdBytes", count.getBytes()); StringBuilder sb = new StringBuilder(flags); if (chan.isOriginate()) sb.append("O"); if (chan.hasConnecter()) sb.append("C"); if (chan.hasReader()) sb.append("R"); if (chan.hasWriter()) sb.append("W"); row.put("Flags", sb.toString()); row.put("LastSend", lastTime(chan.getLastSendTime())); row.put("LastRcv", lastTime(chan.getLastRcvTime())); if (chan.getPrevState() != BlockingPeerChannel.ChannelState.NONE) { row.put("PrevState", chan.getPrevState()); row.put("PrevStateChange", lastTime(chan.getLastStateChange())); } return row; } String lastTime(long time) { if (time <= 0) return ""; return StringUtil.timeIntervalToString(TimeBase.msSince(time)); } } }
package de.kimminich.kata.tcg.strategy; import de.kimminich.kata.tcg.Card; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.TextFromStandardInputStream; import java.util.Optional; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream; public class ConsoleInputStrategyTest { Strategy strategy; @Rule public TextFromStandardInputStream consoleInput = emptyStandardInputStream(); @Test public void manualInputStrategyShouldPlayCardsSelectedOnSystemConsole() { strategy = new ConsoleInputStrategy(); consoleInput.provideText("2\n"); assertThat(strategy.nextCard(10, Card.list(0, 2, 3)), is(card(2))); } @Test public void willRejectTooExpensiveCardsUntilAffordableCardIsChosen() { strategy = new ConsoleInputStrategy(); consoleInput.provideText("8\n7\n6\n"); assertThat(strategy.nextCard(6, Card.list(6, 7, 8)), is(card(6))); } @Test public void willRejectInvalidInputUntilValidCardIsChosen() { strategy = new ConsoleInputStrategy(); consoleInput.provideText("-1\n9\n666\n5\n"); assertThat(strategy.nextCard(10, Card.list(5)), is(card(5))); } private Optional<Card> card(int card) { return Optional.of(new Card(card)); } private Optional<Card> noCard() { return Optional.empty(); } }
//$Id: MarcFactoryImpl.java,v 1.2 2006/07/28 16:28:29 bpeters Exp $ package org.marc4j.marc.impl; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.Leader; import org.marc4j.marc.MarcFactory; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; /** * Factory for creating MARC record objects. * * @author Bas Peters * @version $Revision: 1.2 $ */ public class MarcFactoryImpl extends MarcFactory { /** * Default constructor. * */ public MarcFactoryImpl() { } /** * Returns a new control field instance. * * @return ControlField */ public ControlField newControlField() { return new ControlFieldImpl(); } /** * Creates a new control field with the given tag and returns the instance. * * @return ControlField */ public ControlField newControlField(String tag) { return new ControlFieldImpl(tag); } /** * Creates a new control field with the given tag and data and returns the * instance. * * @return ControlField */ public ControlField newControlField(String tag, String data) { return new ControlFieldImpl(tag, data); } /** * Returns a new data field instance. * * @return DataField */ public DataField newDataField() { return new DataFieldImpl(); } /** * Creates a new data field with the given tag and indicators and returns * the instance. * * @return DataField */ public DataField newDataField(String tag, char ind1, char ind2) { return new DataFieldImpl(tag, ind1, ind2); } /** * Returns a new leader instance. * * @return Leader */ public Leader newLeader() { return new LeaderImpl(); } /** * Creates a new leader with the given <code>String</code> object. * * @return Leader */ public Leader newLeader(String ldr) { return new LeaderImpl(ldr); } /** * Returns a new record instance. * * @return Record */ public Record newRecord() { return new RecordImpl(); } /** * Returns a new subfield instance. * * @return Leader */ public Subfield newSubfield() { return new SubfieldImpl(); } /** * Creates a new subfield with the given identifier. * * @return Subfield */ public Subfield newSubfield(char code) { return new SubfieldImpl(code); } /** * Creates a new subfield with the given identifier and data. * * @return Subfield */ public Subfield newSubfield(char code, String data) { return new SubfieldImpl(code, data); } public Record newRecord(Leader leader) { Record record = new RecordImpl(); record.setLeader(leader); return record; } public Record newRecord(String leader) { return newRecord(new LeaderImpl(leader)); } }
/* * $Id: HistoryRepositoryImpl.java,v 1.37 2003-07-17 00:20:48 tlipkis Exp $ */ package org.lockss.state; import java.io.*; import java.net.MalformedURLException; import java.util.*; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.mapping.Mapping; import org.lockss.util.*; import org.lockss.repository.*; import org.lockss.daemon.Configuration; import org.lockss.app.*; import org.lockss.plugin.*; import java.net.URL; import org.xml.sax.InputSource; /** * HistoryRepository is an inner layer of the NodeManager which handles the actual * storage of NodeStates. */ public class HistoryRepositoryImpl extends BaseLockssManager implements HistoryRepository { /** * Configuration parameter name for Lockss history location. */ public static final String PARAM_HISTORY_LOCATION = Configuration.PREFIX + "history.location"; /** * Name of top directory in which the histories are stored. */ public static final String HISTORY_ROOT_NAME = "cache"; static final String MAPPING_FILE_NAME = "pollmapping.xml"; static final String HISTORY_FILE_NAME = "history.xml"; static final String NODE_FILE_NAME = "nodestate.xml"; static final String AU_FILE_NAME = "au_state.xml"; static final String DAMAGED_NODES_FILE_NAME = "damaged_nodes.xml"; // this contains a '#' so that it's not defeatable by strings which // match the prefix in a url (like '../tmp/') private static final String TEST_PREFIX = "/#tmp"; private String rootDir; Mapping mapping = null; private static Logger logger = Logger.getLogger("HistoryRepository"); HistoryRepositoryImpl(String repository_location) { rootDir = repository_location; } public HistoryRepositoryImpl() { } /** * start the plugin manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); if (rootDir==null) { String msg = PARAM_HISTORY_LOCATION + " not configured"; logger.error(msg); throw new LockssDaemonException(msg); } loadMapping(); } /** * stop the plugin manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { // we want to checkpoint here mapping = null; super.stopService(); } protected void setConfig(Configuration config, Configuration oldConfig, Set changedKeys) { // don't reset this once it's set if (rootDir==null) { rootDir = config.getParam(PARAM_HISTORY_LOCATION); } } public void storeNodeState(NodeState nodeState) { try { File nodeDir = new File(getNodeLocation(nodeState.getCachedUrlSet())); if (!nodeDir.exists()) { nodeDir.mkdirs(); } logger.debug3("Storing state for CUS '" + nodeState.getCachedUrlSet().getUrl() + "'"); File nodeFile = new File(nodeDir, NODE_FILE_NAME); FileWriter writer = new FileWriter(nodeFile); Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(getMapping()); marshaller.marshal(new NodeStateBean(nodeState)); writer.close(); } catch (Exception e) { logger.error("Couldn't store node state: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't store node state."); } } public NodeState loadNodeState(CachedUrlSet cus) { try { File nodeFile = new File(getNodeLocation(cus) + File.separator + NODE_FILE_NAME); if (!nodeFile.exists()) { return new NodeStateImpl(cus, -1, new CrawlState(-1, CrawlState.FINISHED, 0), new ArrayList(), this); } logger.debug3("Loading state for CUS '" + cus.getUrl() + "'"); FileReader reader = new FileReader(nodeFile); Unmarshaller unmarshaller = new Unmarshaller(NodeStateBean.class); unmarshaller.setMapping(getMapping()); NodeStateBean nsb = (NodeStateBean)unmarshaller.unmarshal(reader); reader.close(); return new NodeStateImpl(cus, nsb, this); } catch (org.exolab.castor.xml.MarshalException me) { logger.error("Marshalling exception on nodestate for '" + cus.getUrl() + "' ", me); // continue return new NodeStateImpl(cus, -1, new CrawlState(-1, CrawlState.FINISHED, 0), new ArrayList(), this); } catch (Exception e) { logger.error("Couldn't load node state: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't load node state."); } } public void storePollHistories(NodeState nodeState) { CachedUrlSet cus = nodeState.getCachedUrlSet(); try { File nodeDir = new File(getNodeLocation(cus)); if (!nodeDir.exists()) { nodeDir.mkdirs(); } logger.debug3("Storing histories for CUS '"+cus.getUrl()+"'"); File nodeFile = new File(nodeDir, HISTORY_FILE_NAME); FileWriter writer = new FileWriter(nodeFile); NodeHistoryBean nhb = new NodeHistoryBean(); nhb.historyBeans = ((NodeStateImpl)nodeState).getPollHistoryBeanList(); Marshaller marshaller = new Marshaller(new FileWriter(nodeFile)); marshaller.setMapping(getMapping()); marshaller.marshal(nhb); writer.close(); } catch (Exception e) { logger.error("Couldn't store poll history: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't store history."); } } public void loadPollHistories(NodeState nodeState) { CachedUrlSet cus = nodeState.getCachedUrlSet(); File nodeFile = null; try { nodeFile = new File(getNodeLocation(cus) + File.separator + HISTORY_FILE_NAME); if (!nodeFile.exists()) { ((NodeStateImpl)nodeState).setPollHistoryBeanList(new ArrayList()); logger.debug3("No history file found."); return; } logger.debug3("Loading histories for CUS '"+cus.getUrl()+"'"); FileReader reader = new FileReader(nodeFile); Unmarshaller unmarshaller = new Unmarshaller(NodeHistoryBean.class); unmarshaller.setMapping(getMapping()); NodeHistoryBean nhb = (NodeHistoryBean)unmarshaller.unmarshal(reader); if (nhb.historyBeans==null) { logger.debug3("Empty history list loaded."); nhb.historyBeans = new ArrayList(); } ((NodeStateImpl)nodeState).setPollHistoryBeanList( new ArrayList(nhb.historyBeans)); reader.close(); } catch (org.exolab.castor.xml.MarshalException me) { logger.error("Parsing exception. Moving file to '.old'"); nodeFile.renameTo(new File(nodeFile.getAbsolutePath()+".old")); ((NodeStateImpl)nodeState).setPollHistoryBeanList(new ArrayList()); } catch (Exception e) { logger.error("Couldn't load poll history: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't load history."); } } public void storeAuState(AuState auState) { try { File nodeDir = new File(getAuLocation(auState.getArchivalUnit())); if (!nodeDir.exists()) { nodeDir.mkdirs(); } logger.debug3("Storing state for AU '" + auState.getArchivalUnit().getName() + "'"); File auFile = new File(nodeDir, AU_FILE_NAME); FileWriter writer = new FileWriter(auFile); Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(getMapping()); marshaller.marshal(new AuStateBean(auState)); writer.close(); } catch (Exception e) { logger.error("Couldn't store au state: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't store au state."); } } public AuState loadAuState(ArchivalUnit au) { try { File auFile = new File(getAuLocation(au) + File.separator + AU_FILE_NAME); if (!auFile.exists()) { logger.debug3("No au file found."); return new AuState(au, -1, -1, -1, this); } logger.debug3("Loading state for AU '" + au.getName() + "'"); FileReader reader = new FileReader(auFile); Unmarshaller unmarshaller = new Unmarshaller(AuStateBean.class); unmarshaller.setMapping(getMapping()); AuStateBean asb = (AuStateBean) unmarshaller.unmarshal(reader); // does not load in an old treewalk time, so that one will be run // immediately reader.close(); return new AuState(au, asb.getLastCrawlTime(), asb.getLastTopLevelPollTime(), -1, this); } catch (org.exolab.castor.xml.MarshalException me) { logger.error("Marshalling exception for austate '"+au.getName()+"': "+me); // continue return new AuState(au, -1, -1, -1, this); } catch (Exception e) { logger.error("Couldn't load au state: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't load au state."); } } public void storeDamagedNodeSet(DamagedNodeSet nodeSet) { try { File nodeDir = new File(getAuLocation(nodeSet.theAu)); if (!nodeDir.exists()) { nodeDir.mkdirs(); } logger.debug3("Storing damaged nodes for AU '" + nodeSet.theAu.getName() + "'"); File damFile = new File(nodeDir, DAMAGED_NODES_FILE_NAME); FileWriter writer = new FileWriter(damFile); Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(getMapping()); marshaller.marshal(nodeSet); writer.close(); } catch (Exception e) { logger.error("Couldn't store damaged nodes: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't store damaged nodes."); } } public DamagedNodeSet loadDamagedNodeSet(ArchivalUnit au) { try { File damFile = new File(getAuLocation(au) + File.separator + DAMAGED_NODES_FILE_NAME); if (!damFile.exists()) { logger.debug3("No au file found."); return new DamagedNodeSet(au, this); } logger.debug3("Loading state for AU '" + au.getName() + "'"); FileReader reader = new FileReader(damFile); Unmarshaller unmarshaller = new Unmarshaller(DamagedNodeSet.class); unmarshaller.setMapping(getMapping()); DamagedNodeSet damNodes = (DamagedNodeSet) unmarshaller.unmarshal(reader); reader.close(); damNodes.theAu = au; damNodes.repository = this; return damNodes; } catch (org.exolab.castor.xml.MarshalException me) { logger.error("Marshalling exception for damaged nodes for '"+ au.getName()+"': "+me); // continue return new DamagedNodeSet(au, this); } catch (Exception e) { logger.error("Couldn't load damaged nodes: ", e); throw new LockssRepository.RepositoryStateException( "Couldn't load damaged nodes."); } } protected String getNodeLocation(CachedUrlSet cus) throws MalformedURLException { StringBuffer buffer = new StringBuffer(rootDir); if (!rootDir.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(HISTORY_ROOT_NAME); buffer.append(File.separator); String auLoc = LockssRepositoryImpl.mapAuToFileLocation( buffer.toString(), cus.getArchivalUnit()); String urlStr = (String)cus.getUrl(); if (AuUrl.isAuUrl(urlStr)) { return auLoc; } else { try { URL testUrl = new URL(urlStr); String path = testUrl.getPath(); if (path.indexOf("/.")>=0) { // filtering to remove urls including '..' and such path = TEST_PREFIX + path; File testFile = new File(path); String canonPath = testFile.getCanonicalPath(); if (canonPath.startsWith(TEST_PREFIX)) { urlStr = testUrl.getProtocol() + ": testUrl.getHost().toLowerCase() + canonPath.substring(TEST_PREFIX.length()); } else { logger.error("Illegal URL detected: " + urlStr); throw new MalformedURLException("Illegal URL detected."); } } } catch (IOException ie) { logger.error("Error testing URL: "+ie); throw new MalformedURLException ("Error testing URL."); } return LockssRepositoryImpl.mapUrlToFileLocation(auLoc, urlStr); } } protected String getAuLocation(ArchivalUnit au) { StringBuffer buffer = new StringBuffer(rootDir); if (!rootDir.endsWith(File.separator)) { buffer.append(File.separator); } buffer.append(HISTORY_ROOT_NAME); buffer.append(File.separator); return LockssRepositoryImpl.mapAuToFileLocation(buffer.toString(), au); } private void loadMapping() { if (mapping==null) { URL mappingLoc = getClass().getResource(MAPPING_FILE_NAME); if (mappingLoc==null) { logger.error("Couldn't find resource '"+MAPPING_FILE_NAME+"'"); throw new LockssDaemonException("Couldn't find mapping file."); } mapping = new Mapping(); try { mapping.loadMapping(mappingLoc); } catch (Exception e) { logger.error("Couldn't load mapping file '"+mappingLoc+"'", e); throw new LockssDaemonException("Couldn't load mapping file."); } } } Mapping getMapping() { if (mapping==null) { logger.error("Mapping file not loaded."); throw new LockssDaemonException("Mapping file not loaded."); } else if (mapping.getRoot().getClassMappingCount()==0) { logger.error("Mapping file is empty."); throw new LockssDaemonException("Mapping file is empty."); } else { return mapping; } } }
package org.jtalks.jcommune.service; import org.jtalks.jcommune.model.entity.User; import org.jtalks.jcommune.service.exceptions.DuplicateException; import org.jtalks.jcommune.service.exceptions.NotFoundException; /** * This interface should have methods which give us more abilities in manipulating User persistent entity. * * @author Osadchuck Eugeny * @author Kirill Afonin */ public interface UserService extends EntityService<User> { /** * Get {@link User} by username. * * @param username username of User * @return {@link User} with given username * @throws NotFoundException if the User not found * @see User */ User getByUsername(String username) throws NotFoundException; /** * Try to register {@link User} with given features. * * @param user user for register * @return registered {@link User} * @throws DuplicateException if user with username or email already exist * @see User */ User registerUser(User user) throws DuplicateException; }
package net.ossrs.yasea; import android.media.MediaCodec; import android.media.MediaFormat; import android.util.Log; import com.github.faucamp.simplertmp.RtmpHandler; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class SrsFlvMuxer { private static final int VIDEO_ALLOC_SIZE = 128 * 1024; private static final int AUDIO_ALLOC_SIZE = 4 * 1024; private static final int CACHE_SIZE = 1000; private volatile boolean connected = false; private SrsRtmpPublisher publisher; private Thread worker; public final SrsFlv flv = new SrsFlv(); public boolean needToFindKeyFrame = true; private SrsFlvFrame mVideoSequenceHeader; private SrsFlvFrame mAudioSequenceHeader; private final SrsAllocator mVideoAllocator = new SrsAllocator(VIDEO_ALLOC_SIZE); private final SrsAllocator mAudioAllocator = new SrsAllocator(AUDIO_ALLOC_SIZE); private final ArrayBlockingQueue<SrsFlvFrame> mFlvTagCache = new ArrayBlockingQueue<>(CACHE_SIZE); public static final int VIDEO_TRACK = 100; public static final int AUDIO_TRACK = 101; private static final String TAG = "SrsFlvMuxer"; private String url; private String user; private String password; /** * constructor. * * @param handler the rtmp event handler. */ public SrsFlvMuxer(RtmpHandler handler) { publisher = new SrsRtmpPublisher(handler); } /** * get cached video frame number in publisher */ public AtomicInteger getVideoFrameCacheNumber() { // Not used anymore return null; } /** * set video resolution for publisher * * @param width width * @param height height */ public void setVideoResolution(int width, int height) { publisher.setVideoResolution(width, height); } /** * Set destination * * @param url URL of RTMP server * @param user Username (optional) * @param password Password (optional) */ public void setDestination(String url, String user, String password) { this.url = url; this.user = user; this.password = password; } /** * Adds a track with the specified format. * * @param format The media format for the track. * @return The track index for this newly added track. */ public int addTrack(MediaFormat format) { if (format.getString(MediaFormat.KEY_MIME).contentEquals(SrsEncoder.VCODEC)) { flv.setVideoTrack(format); publisher.setVideoFormat(format); return VIDEO_TRACK; } else { flv.setAudioTrack(format); publisher.setAudioFormat(format); return AUDIO_TRACK; } } public void disconnect() { try { publisher.close(); } catch (IllegalStateException e) { } mFlvTagCache.clear(); connected = false; mVideoSequenceHeader = null; mAudioSequenceHeader = null; Log.i(TAG, "worker: disconnect ok."); } /** * Connect to RTMP endpoint * * @return Is connected */ public boolean connect() { if (url == null) { Log.e(TAG, "URL is not specified"); return false; } needToFindKeyFrame = true; if (!connected) { Log.i(TAG, String.format("Connecting to RTMP server at %s...", url)); if (publisher.connect(url, user, password)) { connected = publisher.publish("live"); } mVideoSequenceHeader = null; mAudioSequenceHeader = null; } return connected; } private void sendFlvTag(SrsFlvFrame frame) { if (!connected || frame == null) { return; } if (frame.isVideo()) { if (frame.isKeyFrame()) { Log.d(TAG, String.format("worker: send frame type=%d, dts=%d, size=%dB", frame.type, frame.dts, frame.flvTag.array().length)); } publisher.publishVideoData(frame.flvTag.array(), frame.flvTag.size(), frame.dts); mVideoAllocator.release(frame.flvTag); } else if (frame.isAudio()) { publisher.publishAudioData(frame.flvTag.array(), frame.flvTag.size(), frame.dts); mAudioAllocator.release(frame.flvTag); } } /** * Start RTMP muxer */ public synchronized void start() { if (worker != null) throw new RuntimeException("SrsFlvMuxer is already running"); flv.reset(); mFlvTagCache.clear(); worker = new Thread(() -> { Log.i(TAG, "SrsFlvMuxer started"); if (!connect()) { Log.e(TAG, "SrsFlvMuxer disconnected"); return; } Log.i(TAG, "SrsFlvMuxer connected"); Log.i(TAG, "SrsFlvMuxer running"); while (worker != null) { try { SrsFlvFrame frame = mFlvTagCache.take(); if (frame != null) { if (frame.isSequenceHeader()) { if (frame.isVideo()) { mVideoSequenceHeader = frame; sendFlvTag(mVideoSequenceHeader); } else if (frame.isAudio()) { mAudioSequenceHeader = frame; sendFlvTag(mAudioSequenceHeader); } } else { if (frame.isVideo() && mVideoSequenceHeader != null) { sendFlvTag(frame); } else if (frame.isAudio() && mAudioSequenceHeader != null) { sendFlvTag(frame); } } } Thread.yield(); } catch (InterruptedException e) { break; } } disconnect(); Log.i(TAG, "SrsFlvMuxer stopped"); worker = null; }); worker.setPriority(7); worker.setDaemon(true); worker.start(); } /** * stop the muxer, disconnect RTMP connection. */ public synchronized void stop() { if (worker != null) { Thread oldWorker = worker; worker = null; oldWorker.interrupt(); } } /** * @return Muxer is connected */ public synchronized boolean isConnected() { return worker != null && connected; } /** * Mux video sample * * @param byteBuf The encoded sample. * @param bufferInfo The buffer information related to this sample. */ public void writeVideoSample(ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) { flv.writeVideoSample(byteBuf, bufferInfo); } /** * Mux audio sample * * @param byteBuf The encoded sample. * @param bufferInfo The buffer information related to this sample. */ public void writeAudioSample(ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo) { flv.writeAudioSample(byteBuf, bufferInfo); } // E.4.3.1 VIDEODATA // Frame Type UB [4] // Type of video frame. The following values are defined: // 1 = key frame (for AVC, a seekable frame) // 2 = inter frame (for AVC, a non-seekable frame) // 3 = disposable inter frame (H.263 only) // 4 = generated key frame (reserved for server use only) // 5 = video info/command frame private class SrsCodecVideoAVCFrame { // set to the zero to reserved, for array map. public final static int Reserved = 0; public final static int Reserved1 = 6; public final static int KeyFrame = 1; public final static int InterFrame = 2; public final static int DisposableInterFrame = 3; public final static int GeneratedKeyFrame = 4; public final static int VideoInfoFrame = 5; } // AVCPacketType IF CodecID == 7 UI8 // The following values are defined: // 0 = AVC sequence header // 1 = AVC NALU // 2 = AVC end of sequence (lower level NALU sequence ender is // not required or supported) private class SrsCodecVideoAVCType { // set to the max value to reserved, for array map. public final static int Reserved = 3; public final static int SequenceHeader = 0; public final static int NALU = 1; public final static int SequenceHeaderEOF = 2; } /** * E.4.1 FLV Tag, page 75 */ private class SrsCodecFlvTag { // set to the zero to reserved, for array map. public final static int Reserved = 0; // 8 = audio public final static int Audio = 8; // 9 = video public final static int Video = 9; // 18 = script data public final static int Script = 18; } // E.4.3.1 VIDEODATA // CodecID UB [4] // Codec Identifier. The following values are defined: // 2 = Sorenson H.263 // 3 = Screen video // 4 = On2 VP6 // 5 = On2 VP6 with alpha channel // 6 = Screen video version 2 // 7 = AVC private class SrsCodecVideo { // set to the zero to reserved, for array map. public final static int Reserved = 0; public final static int Reserved1 = 1; public final static int Reserved2 = 9; // for user to disable video, for example, use pure audio hls. public final static int Disabled = 8; public final static int SorensonH263 = 2; public final static int ScreenVideo = 3; public final static int On2VP6 = 4; public final static int On2VP6WithAlphaChannel = 5; public final static int ScreenVideoVersion2 = 6; public final static int AVC = 7; } /** * the aac object type, for RTMP sequence header * for AudioSpecificConfig, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33 * for audioObjectType, @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23 */ private class SrsAacObjectType { public final static int Reserved = 0; // @see @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 23 public final static int AacMain = 1; public final static int AacLC = 2; public final static int AacSSR = 3; // AAC HE = LC+SBR public final static int AacHE = 5; // AAC HEv2 = LC+SBR+PS public final static int AacHEV2 = 29; } private class SrsAacProfile { public final static int Reserved = 3; // @see 7.1 Profiles, aac-iso-13818-7.pdf, page 40 public final static int Main = 0; public final static int LC = 1; public final static int SSR = 2; } /** * the FLV/RTMP supported audio sample rate. * Sampling rate. The following values are defined: * 0 = 5.5 kHz = 5512 Hz * 1 = 11 kHz = 11025 Hz * 2 = 22 kHz = 22050 Hz * 3 = 44 kHz = 44100 Hz */ private class SrsCodecAudioSampleRate { public final static int R5512 = 5512; public final static int R11025 = 11025; public final static int R22050 = 22050; public final static int R44100 = 44100; public final static int R32000 = 32000; public final static int R16000 = 16000; } private class SrsAvcNaluType { // Unspecified public final static int Reserved = 0; // Coded slice of a non-IDR picture slice_layer_without_partitioning_rbsp( ) public final static int NonIDR = 1; // Coded slice data partition A slice_data_partition_a_layer_rbsp( ) public final static int DataPartitionA = 2; // Coded slice data partition B slice_data_partition_b_layer_rbsp( ) public final static int DataPartitionB = 3; // Coded slice data partition C slice_data_partition_c_layer_rbsp( ) public final static int DataPartitionC = 4; // Coded slice of an IDR picture slice_layer_without_partitioning_rbsp( ) public final static int IDR = 5; // Supplemental enhancement information (SEI) sei_rbsp( ) public final static int SEI = 6; // Sequence parameter set seq_parameter_set_rbsp( ) public final static int SPS = 7; // Picture parameter set pic_parameter_set_rbsp( ) public final static int PPS = 8; // Access unit delimiter access_unit_delimiter_rbsp( ) public final static int AccessUnitDelimiter = 9; // End of sequence end_of_seq_rbsp( ) public final static int EOSequence = 10; // End of stream end_of_stream_rbsp( ) public final static int EOStream = 11; // Filler data filler_data_rbsp( ) public final static int FilterData = 12; // Sequence parameter set extension seq_parameter_set_extension_rbsp( ) public final static int SPSExt = 13; // Prefix NAL unit prefix_nal_unit_rbsp( ) public final static int PrefixNALU = 14; // Subset sequence parameter set subset_seq_parameter_set_rbsp( ) public final static int SubsetSPS = 15; // Coded slice of an auxiliary coded picture without partitioning slice_layer_without_partitioning_rbsp( ) public final static int LayerWithoutPartition = 19; // Coded slice extension slice_layer_extension_rbsp( ) public final static int CodedSliceExt = 20; } /** * the demuxed tag frame. */ private class SrsFlvFrameBytes { public ByteBuffer data; public int size; } /** * the muxed flv frame. */ private class SrsFlvFrame { // the tag bytes. public SrsAllocator.Allocation flvTag; // the codec type for audio/aac and video/avc for instance. public int avc_aac_type; // the frame type, keyframe or not. public int frame_type; // the tag type, audio, video or data. public int type; // the dts in ms, tbn is 1000. public int dts; public boolean isKeyFrame() { return isVideo() && frame_type == SrsCodecVideoAVCFrame.KeyFrame; } public boolean isSequenceHeader() { return avc_aac_type == 0; } public boolean isVideo() { return type == SrsCodecFlvTag.Video; } public boolean isAudio() { return type == SrsCodecFlvTag.Audio; } } /** * the raw h.264 stream, in annexb. */ private class SrsRawH264Stream { private final static String TAG = "SrsFlvMuxer"; private SrsFlvFrameBytes nalu_header = new SrsFlvFrameBytes(); private SrsFlvFrameBytes seq_hdr = new SrsFlvFrameBytes(); private SrsFlvFrameBytes sps_hdr = new SrsFlvFrameBytes(); private SrsFlvFrameBytes sps_bb = new SrsFlvFrameBytes(); private SrsFlvFrameBytes pps_hdr = new SrsFlvFrameBytes(); private SrsFlvFrameBytes pps_bb = new SrsFlvFrameBytes(); public boolean isSps(SrsFlvFrameBytes frame) { return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.SPS; } public boolean isPps(SrsFlvFrameBytes frame) { return frame.size >= 1 && (frame.data.get(0) & 0x1f) == SrsAvcNaluType.PPS; } public SrsFlvFrameBytes muxNaluHeader(SrsFlvFrameBytes frame) { if (nalu_header.data == null) { nalu_header.data = ByteBuffer.allocate(4); nalu_header.size = 4; } nalu_header.data.rewind(); // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16 // lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size int NAL_unit_length = frame.size; // mux the avc NALU in "ISO Base Media File Format" // from H.264-AVC-ISO_IEC_14496-15.pdf, page 20 // NALUnitLength nalu_header.data.putInt(NAL_unit_length); // reset the buffer. nalu_header.data.rewind(); return nalu_header; } public void muxSequenceHeader(ByteBuffer sps, ByteBuffer pps, ArrayList<SrsFlvFrameBytes> frames) { // 5bytes sps/pps header: // configurationVersion, AVCProfileIndication, profile_compatibility, // AVCLevelIndication, lengthSizeMinusOne // 3bytes size of sps: // numOfSequenceParameterSets, sequenceParameterSetLength(2B) // Nbytes of sps. // sequenceParameterSetNALUnit // 3bytes size of pps: // numOfPictureParameterSets, pictureParameterSetLength // Nbytes of pps: // pictureParameterSetNALUnit // decode the SPS: // @see: 7.3.2.1.1, H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 62 if (seq_hdr.data == null) { seq_hdr.data = ByteBuffer.allocate(5); seq_hdr.size = 5; } seq_hdr.data.rewind(); // @see: Annex A Profiles and levels, H.264-AVC-ISO_IEC_14496-10.pdf, page 205 // Baseline profile profile_idc is 66(0x42). // Main profile profile_idc is 77(0x4d). // Extended profile profile_idc is 88(0x58). byte profile_idc = sps.get(1); //u_int8_t constraint_set = frame[2]; byte level_idc = sps.get(3); // generate the sps/pps header // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16 // configurationVersion seq_hdr.data.put((byte) 0x01); // AVCProfileIndication seq_hdr.data.put(profile_idc); // profile_compatibility seq_hdr.data.put((byte) 0x00); // AVCLevelIndication seq_hdr.data.put(level_idc); // lengthSizeMinusOne, or NAL_unit_length, always use 4bytes size, // so we always set it to 0x03. seq_hdr.data.put((byte) 0x03); // reset the buffer. seq_hdr.data.rewind(); frames.add(seq_hdr); // sps if (sps_hdr.data == null) { sps_hdr.data = ByteBuffer.allocate(3); sps_hdr.size = 3; } sps_hdr.data.rewind(); // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16 // numOfSequenceParameterSets, always 1 sps_hdr.data.put((byte) 0x01); // sequenceParameterSetLength sps_hdr.data.putShort((short) sps.capacity()); sps_hdr.data.rewind(); frames.add(sps_hdr); // sequenceParameterSetNALUnit sps_bb.size = sps.capacity(); sps_bb.data = sps.duplicate(); frames.add(sps_bb); // pps if (pps_hdr.data == null) { pps_hdr.data = ByteBuffer.allocate(3); pps_hdr.size = 3; } pps_hdr.data.rewind(); // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16 // numOfPictureParameterSets, always 1 pps_hdr.data.put((byte) 0x01); // pictureParameterSetLength pps_hdr.data.putShort((short) pps.capacity()); pps_hdr.data.rewind(); frames.add(pps_hdr); // pictureParameterSetNALUnit pps_bb.size = pps.capacity(); pps_bb.data = pps.duplicate(); frames.add(pps_bb); } public SrsAllocator.Allocation muxFlvTag(ArrayList<SrsFlvFrameBytes> frames, int frame_type, int avc_packet_type, int dts, int pts) { // for h264 in RTMP video payload, there is 5bytes header: // 1bytes, FrameType | CodecID // 1bytes, AVCPacketType // 3bytes, CompositionTime, the cts. // @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78 int size = 5; for (int i = 0; i < frames.size(); i++) { size += frames.get(i).size; } SrsAllocator.Allocation allocation = mVideoAllocator.allocate(size); // @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78 // Frame Type, Type of video frame. // CodecID, Codec Identifier. // set the rtmp header allocation.put((byte) ((frame_type << 4) | SrsCodecVideo.AVC)); // AVCPacketType allocation.put((byte) avc_packet_type); // CompositionTime // pts = dts + cts, or // cts = pts - dts. // where cts is the header in rtmp video packet payload header. int cts = pts - dts; allocation.put((byte) (cts >> 16)); allocation.put((byte) (cts >> 8)); allocation.put((byte) cts); // h.264 raw data. for (int i = 0; i < frames.size(); i++) { SrsFlvFrameBytes frame = frames.get(i); frame.data.rewind(); frame.data.get(allocation.array(), allocation.size(), frame.size); allocation.appendOffset(frame.size); } return allocation; } private int searchAnnexb(ByteBuffer bb) { while (bb.position() < bb.capacity()) { int offset = bb.position(); int size = bb.remaining(); // match N[00] 00 00 00 01, where N>=0 if (size > 3 && bb.get(offset) == 0x00 && bb.get(offset + 1) == 0x00 && bb.get(offset + 2) == 0x00 && bb.get(offset + 3) == 0x01) { return 4; } // match N[00] 00 00 01, where N>=0 if (size > 2 && bb.get(offset) == 0x00 && bb.get(offset + 1) == 0x00 && bb.get(offset + 2) == 0x01) { return 3; } bb.get(); } return -1; } public SrsFlvFrameBytes demuxAnnexb(ByteBuffer bb, int offset) { // Skip annexb header for (int i = 0; i < offset; i++) { bb.get(); } // Create FLV frame SrsFlvFrameBytes tbb = new SrsFlvFrameBytes(); tbb.data = bb.slice(); tbb.size = bb.remaining(); return tbb; } } private class SrsRawAacStreamCodec { public byte protection_absent; // SrsAacObjectType public int aac_object; public byte sampling_frequency_index; public byte channel_configuration; public short frame_length; public byte sound_format; public byte sound_rate; public byte sound_size; public byte sound_type; // 0 for sh; 1 for raw data. public byte aac_packet_type; public byte[] frame; } /** * remux the annexb to flv tags. */ private class SrsFlv { private MediaFormat videoTrack; private MediaFormat audioTrack; private int achannel; private int asample_rate; private final SrsRawH264Stream avc = new SrsRawH264Stream(); private final ArrayList<SrsFlvFrameBytes> ipbs = new ArrayList<>(); private SrsAllocator.Allocation audio_tag; private SrsAllocator.Allocation video_tag; private ByteBuffer h264_sps; private ByteBuffer h264_pps; private boolean h264_sps_pps_sent; private boolean aac_specific_config_got; public SrsFlv() { reset(); } public void reset() { h264_sps = null; h264_pps = null; h264_sps_pps_sent = false; aac_specific_config_got = false; } public void setVideoTrack(MediaFormat format) { videoTrack = format; } public void setAudioTrack(MediaFormat format) { audioTrack = format; achannel = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT); asample_rate = format.getInteger(MediaFormat.KEY_SAMPLE_RATE); } public void writeAudioSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) { int dts = (int) (bi.presentationTimeUs / 1000); audio_tag = mAudioAllocator.allocate(bi.size + 2); byte aac_packet_type = 1; // 1 = AAC raw if (!aac_specific_config_got) { // @see aac-mp4a-format-ISO_IEC_14496-3+2001.pdf // AudioSpecificConfig (), page 33 // 1.6.2.1 AudioSpecificConfig // audioObjectType; 5 bslbf byte ch = (byte) (bi.flags == MediaCodec.BUFFER_FLAG_CODEC_CONFIG ? bb.get(0) & 0xf8 : (bb.get(0) & 0xf8) / 2); // 3bits left. // samplingFrequencyIndex; 4 bslbf byte samplingFrequencyIndex = 0x04; //44100 if (asample_rate == SrsCodecAudioSampleRate.R22050) { samplingFrequencyIndex = 0x07; } else if (asample_rate == SrsCodecAudioSampleRate.R11025) { samplingFrequencyIndex = 0x0a; } else if (asample_rate == SrsCodecAudioSampleRate.R32000) { samplingFrequencyIndex = 0x05; } else if (asample_rate == SrsCodecAudioSampleRate.R16000) { samplingFrequencyIndex = 0x08; } ch |= (samplingFrequencyIndex >> 1) & 0x07; audio_tag.put(ch, 2); ch = (byte) ((samplingFrequencyIndex << 7) & 0x80); // 7bits left. // channelConfiguration; 4 bslbf byte channelConfiguration = 1; if (achannel == 2) { channelConfiguration = 2; } ch |= (channelConfiguration << 3) & 0x78; // 3bits left. // GASpecificConfig(), page 451 // 4.4.1 Decoder configuration (GASpecificConfig) // frameLengthFlag; 1 bslbf // dependsOnCoreCoder; 1 bslbf // extensionFlag; 1 bslbf audio_tag.put(ch, 3); aac_specific_config_got = true; aac_packet_type = 0; // 0 = AAC sequence header writeAdtsHeader(audio_tag.array(), 4); audio_tag.appendOffset(7); } else { bb.get(audio_tag.array(), 2, bi.size); audio_tag.appendOffset(bi.size + 2); } byte sound_format = 10; // AAC byte sound_type = 0; // 0 = Mono sound if (achannel == 2) { sound_type = 1; // 1 = Stereo sound } byte sound_size = 1; // 1 = 16-bit samples byte sound_rate = 3; // 44100, 22050, 11025, 5512 if (asample_rate == 22050) { sound_rate = 2; } else if (asample_rate == 11025) { sound_rate = 1; } else if (asample_rate == 5512) { sound_rate = 0; } // for audio frame, there is 1 or 2 bytes header: // 1bytes, SoundFormat|SoundRate|SoundSize|SoundType // 1bytes, AACPacketType for SoundFormat == 10, 0 is sequence header. byte audio_header = (byte) (sound_type & 0x01); audio_header |= (sound_size << 1) & 0x02; audio_header |= (sound_rate << 2) & 0x0c; audio_header |= (sound_format << 4) & 0xf0; audio_tag.put(audio_header, 0); audio_tag.put(aac_packet_type, 1); writeRtmpPacket(SrsCodecFlvTag.Audio, dts, 0, aac_packet_type, audio_tag); } private void writeAdtsHeader(byte[] frame, int offset) { // adts sync word 0xfff (12-bit) frame[offset] = (byte) 0xff; frame[offset + 1] = (byte) 0xf0; // version 0 for MPEG-4, 1 for MPEG-2 (1-bit) frame[offset + 1] |= 0 << 3; // layer 0 (2-bit) frame[offset + 1] |= 0 << 1; // protection absent: 1 (1-bit) frame[offset + 1] |= 1; // profile: audio_object_type - 1 (2-bit) frame[offset + 2] = (SrsAacObjectType.AacLC - 1) << 6; // sampling frequency index: 4 (4-bit) frame[offset + 2] |= (4 & 0xf) << 2; // channel configuration (3-bit) frame[offset + 2] |= (2 & (byte) 0x4) >> 2; frame[offset + 3] = (byte) ((2 & (byte) 0x03) << 6); // original: 0 (1-bit) frame[offset + 3] |= 0 << 5; // home: 0 (1-bit) frame[offset + 3] |= 0 << 4; frame[offset + 3] |= 0 << 3; frame[offset + 3] |= 0 << 2; // frame size (13-bit) frame[offset + 3] |= ((frame.length - 2) & 0x1800) >> 11; frame[offset + 4] = (byte) (((frame.length - 2) & 0x7f8) >> 3); frame[offset + 5] = (byte) (((frame.length - 2) & 0x7) << 5); // buffer fullness (0x7ff for variable bitrate) frame[offset + 5] |= (byte) 0x1f; frame[offset + 6] = (byte) 0xfc; // number of data block (nb - 1) frame[offset + 6] |= 0x0; } public void writeVideoSample(final ByteBuffer bb, MediaCodec.BufferInfo bi) { int pts = (int) (bi.presentationTimeUs / 1000); int dts = pts; int offset = avc.searchAnnexb(bb); if (offset < 0) { Log.e(TAG, "Invalid frame, Annex B header missing"); return; } int nal_unit_type = bb.get(offset) & 0x1f; // SPS/PPS if (nal_unit_type == SrsAvcNaluType.SPS || nal_unit_type == SrsAvcNaluType.PPS) { SrsFlvFrameBytes frame_sps = avc.demuxAnnexb(bb, offset); offset = avc.searchAnnexb(bb); if (offset < 0) { Log.e(TAG, "Invalid frame, Annex B header for PPS missing"); return; } SrsFlvFrameBytes frame_pps = avc.demuxAnnexb(bb, offset); // SPS byte[] sps = new byte[frame_sps.size - frame_pps.size - 4]; frame_sps.data.get(sps); h264_sps = ByteBuffer.wrap(sps); // PPS byte[] pps = new byte[frame_pps.size]; frame_pps.data.get(pps); h264_pps = ByteBuffer.wrap(pps); writeH264SpsPps(dts, pts); h264_sps_pps_sent = true; } // IDR/NonIDR if (nal_unit_type == SrsAvcNaluType.IDR || nal_unit_type == SrsAvcNaluType.NonIDR) { SrsFlvFrameBytes frame = avc.demuxAnnexb(bb, offset); int type = SrsCodecVideoAVCFrame.InterFrame; if (nal_unit_type == SrsAvcNaluType.IDR) type = SrsCodecVideoAVCFrame.KeyFrame; ipbs.add(avc.muxNaluHeader(frame)); ipbs.add(frame); writeH264IpbFrame(ipbs, type, dts, pts); ipbs.clear(); } } private void writeH264SpsPps(int dts, int pts) { // h264 raw to h264 packet. ArrayList<SrsFlvFrameBytes> frames = new ArrayList<>(); avc.muxSequenceHeader(h264_sps, h264_pps, frames); // h264 packet to flv packet. int frame_type = SrsCodecVideoAVCFrame.KeyFrame; int avc_packet_type = SrsCodecVideoAVCType.SequenceHeader; video_tag = avc.muxFlvTag(frames, frame_type, avc_packet_type, dts, pts); // the timestamp in rtmp message header is dts. writeRtmpPacket(SrsCodecFlvTag.Video, dts, frame_type, avc_packet_type, video_tag); Log.i(TAG, String.format("flv: h264 sps/pps sent, sps=%dB, pps=%dB", h264_sps.array().length, h264_pps.array().length)); } private void writeH264IpbFrame(ArrayList<SrsFlvFrameBytes> frames, int frame_type, int dts, int pts) { // when sps or pps not sent, ignore the packet. if (!h264_sps_pps_sent) return; video_tag = avc.muxFlvTag(frames, frame_type, SrsCodecVideoAVCType.NALU, dts, pts); // the timestamp in rtmp message header is dts. writeRtmpPacket(SrsCodecFlvTag.Video, dts, frame_type, SrsCodecVideoAVCType.NALU, video_tag); } private void writeRtmpPacket(int type, int dts, int frame_type, int avc_aac_type, SrsAllocator.Allocation tag) { SrsFlvFrame frame = new SrsFlvFrame(); frame.flvTag = tag; frame.type = type; frame.dts = dts; frame.frame_type = frame_type; frame.avc_aac_type = avc_aac_type; if (frame.isVideo()) { if (needToFindKeyFrame) { if (frame.isKeyFrame()) { needToFindKeyFrame = false; flvTagCacheAdd(frame); } } else { flvTagCacheAdd(frame); } } else if (frame.isAudio()) { flvTagCacheAdd(frame); } } private void flvTagCacheAdd(SrsFlvFrame frame) { if (!mFlvTagCache.offer(frame)) { needToFindKeyFrame = true; Log.w(TAG, "Network throughput too low"); } } } }
package org.mtransit.parser; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.gtfs.GAgencyTools; import org.mtransit.parser.gtfs.GReader; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GFrequency; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GStopTime; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.MGenerator; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MSpec; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class DefaultAgencyTools implements GAgencyTools { public static final int THREAD_POOL_SIZE = 1; public static void main(String[] args) { new DefaultAgencyTools().start(args); } public void start(String[] args) { System.out.printf("Generating agency data...\n"); long start = System.currentTimeMillis(); // GTFS parsing GSpec gtfs = GReader.readGtfsZipFile(args[0], this, false); gtfs.tripStops = GReader.extractTripStops(gtfs); Map<Long, GSpec> gtfsByMRouteId = GReader.splitByRouteId(gtfs, this); // Objects generation MSpec mSpec = MGenerator.generateMSpec(gtfsByMRouteId, gtfs.stops, this); // Dump to files MGenerator.dumpFiles(mSpec, args[1], args[2]); System.out.printf("Generating agency data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public String getAgencyColor() { return null; } @Override public Integer getAgencyRouteType() { return null; } @Override public String cleanServiceId(String serviceId) { return serviceId; } @Override public long getRouteId(GRoute gRoute) { try { return Long.valueOf(gRoute.route_id); } catch (Exception e) { System.out.println("Error while extracting route ID from " + gRoute); e.printStackTrace(); System.exit(-1); return -1; } } @Override public String getRouteShortName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.route_short_name)) { System.out.println("No default route short name for " + gRoute); System.exit(-1); return null; } return gRoute.route_short_name; } @Override public String getRouteLongName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.route_long_name)) { System.out.println("No default route long name for " + gRoute); System.exit(-1); return null; } return MSpec.cleanLabel(gRoute.route_long_name); } @Override public boolean mergeRouteLongName(MRoute mRoute, MRoute mRouteToMerge) { return mRoute.mergeLongName(mRouteToMerge); } @Override public String getRouteColor(GRoute gRoute) { if (getAgencyColor() != null && getAgencyColor().equals(gRoute.route_color)) { return null; } return gRoute.route_color; } @Override public boolean excludeRoute(GRoute gRoute) { if (getAgencyRouteType() == null) { System.out.println("ERROR: unspecified agency route type '" + getAgencyRouteType() + "'!"); System.exit(-1); } if (getAgencyRouteType() != gRoute.route_type) { return true; } return false; } @Override public HashSet<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { HashSet<MTrip> mTrips = new HashSet<MTrip>(); mTrips.add(new MTrip(mRoute.id)); return mTrips; } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, HashSet<MTrip> splitTrips, GSpec gtfs) { return new Pair<Long[], Integer[]>(new Long[] { splitTrips.iterator().next().getId() }, new Integer[] { gTripStop.stop_sequence }); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (gTrip.direction_id < 0 || gTrip.direction_id > 1) { System.out.println("ERROR: default agency implementation required 'direction_id' field in 'trips.txt'!"); System.exit(-1); } try { mTrip.setHeadsignString(cleanTripHeadsign(gTrip.trip_headsign), gTrip.direction_id); } catch (NumberFormatException nfe) { System.out.println("ERROR: default agency implementation not possible!"); nfe.printStackTrace(); System.exit(-1); } } @Override public String cleanTripHeadsign(String tripHeadsign) { return tripHeadsign; } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { return mTrip.mergeHeadsignValue(mTripToMerge); } @Override public boolean excludeStopTime(GStopTime gStopTime) { return false; } @Override public boolean excludeTrip(GTrip gTrip) { return false; } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { return false; } @Override public boolean excludeCalendar(GCalendar gCalendar) { return false; } @Override public String cleanStopName(String gStopName) { return MSpec.cleanLabel(gStopName); } public String cleanStopNameFR(String stopName) { return MSpec.cleanLabelFR(stopName); } @Override public String getStopCode(GStop gStop) { return gStop.stop_code; } @Override public int getStopId(GStop gStop) { try { return Integer.parseInt(gStop.stop_id); } catch (Exception e) { System.out.println("Error while extracting stop ID from " + gStop); e.printStackTrace(); System.exit(-1); return -1; } } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { return 0; // nothing } @Override public int compare(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { return 0; // nothing } @Override public boolean excludeStop(GStop gStop) { return false; } @Override public int getThreadPoolSize() { return THREAD_POOL_SIZE; } private static final int PRECISON_IN_SECONDS = 10; private static final String TIME_SEPARATOR = ":"; private static final SimpleDateFormat HHMMSS = new SimpleDateFormat("HHmmss"); @Override public int getDepartureTime(GStopTime gStopTime, List<GStopTime> gStopTimes) { String departureTimeS = null; if (StringUtils.isEmpty(gStopTime.departure_time)) { try { Integer newDepartureTime = null; Integer previousDepartureTime = null; Integer previousDepartureTimeStopSequence = null; Integer nextDepartureTime = null; Integer nextDepartureTimeStopSequence = null; for (GStopTime aStopTime : gStopTimes) { if (!gStopTime.trip_id.equals(aStopTime.trip_id)) { continue; } if (aStopTime.stop_sequence < gStopTime.stop_sequence) { if (!StringUtils.isEmpty(aStopTime.departure_time)) { newDepartureTime = Integer.valueOf(aStopTime.departure_time.replaceAll(TIME_SEPARATOR, Constants.EMPTY)); if (previousDepartureTime == null || previousDepartureTimeStopSequence == null || previousDepartureTimeStopSequence < aStopTime.stop_sequence) { previousDepartureTime = newDepartureTime; previousDepartureTimeStopSequence = aStopTime.stop_sequence; } } } else if (aStopTime.stop_sequence > gStopTime.stop_sequence) { if (!StringUtils.isEmpty(aStopTime.departure_time)) { newDepartureTime = Integer.valueOf(aStopTime.departure_time.replaceAll(TIME_SEPARATOR, Constants.EMPTY)); if (nextDepartureTime == null || nextDepartureTimeStopSequence == null || nextDepartureTimeStopSequence > aStopTime.stop_sequence) { nextDepartureTime = newDepartureTime; nextDepartureTimeStopSequence = aStopTime.stop_sequence; } } } } long previousDepartureTimeInMs = HHMMSS.parse(String.valueOf(previousDepartureTime)).getTime(); long nextDepartureTimeInMs = HHMMSS.parse(String.valueOf(nextDepartureTime)).getTime(); long timeDiffInMs = nextDepartureTimeInMs - previousDepartureTimeInMs; int nbStop = nextDepartureTimeStopSequence - previousDepartureTimeStopSequence; long timeBetweenStopInMs = timeDiffInMs / nbStop; long departureTimeInMs = previousDepartureTimeInMs + (timeBetweenStopInMs * (gStopTime.stop_sequence - previousDepartureTimeStopSequence)); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(departureTimeInMs); departureTimeS = HHMMSS.format(calendar.getTime()); if (calendar.get(Calendar.DAY_OF_YEAR) > 1) { departureTimeS = String.valueOf(240000 + Integer.valueOf(departureTimeS)); } } catch (Exception e) { System.out.println("Error while interpolating departure time for " + gStopTime + "!"); e.printStackTrace(); System.exit(-1); departureTimeS = null; } } else { departureTimeS = gStopTime.departure_time.replaceAll(TIME_SEPARATOR, Constants.EMPTY); } Integer departureTime = Integer.valueOf(departureTimeS); int extraSeconds = departureTime == null ? 0 : departureTime.intValue() % PRECISON_IN_SECONDS; if (extraSeconds > 0) { // IF too precise DO return cleanDepartureTime(departureTimeS, extraSeconds); } return departureTime; // GTFS standard } private static final String CLEAN_DEPARTURE_TIME_FORMAT = "%02d"; private static final String CLEAN_DEPARTURE_TIME_LEADING_ZERO = "0"; private static final String CLEAN_DEPARTURE_TIME_DEFAULT_MINUTES = "00"; private static final String CLEAN_DEPARTURE_TIME_DEFAULT_SECONDS = "00"; private int cleanDepartureTime(String departureTimeS, int extraSeconds) { try { while (departureTimeS.length() < 6) { departureTimeS = CLEAN_DEPARTURE_TIME_LEADING_ZERO + departureTimeS; } String newHours = departureTimeS.substring(0, 2); String newMinutes = departureTimeS.substring(2, 4); String newSeconds = departureTimeS.substring(4, 6); int seconds = Integer.parseInt(newSeconds); if (extraSeconds < 5) { if (extraSeconds > seconds) { newSeconds = CLEAN_DEPARTURE_TIME_DEFAULT_SECONDS; } else { newSeconds = String.format(CLEAN_DEPARTURE_TIME_FORMAT, seconds - extraSeconds); } return Integer.valueOf(newHours + newMinutes + newSeconds); } int secondsToAdd = PRECISON_IN_SECONDS - extraSeconds; if (seconds + secondsToAdd < 60) { newSeconds = String.format(CLEAN_DEPARTURE_TIME_FORMAT, seconds + secondsToAdd); return Integer.valueOf(newHours + newMinutes + newSeconds); } newSeconds = CLEAN_DEPARTURE_TIME_DEFAULT_SECONDS; int minutes = Integer.parseInt(newMinutes); if (minutes + 1 < 60) { newMinutes = String.format(CLEAN_DEPARTURE_TIME_FORMAT, minutes + 1); return Integer.valueOf(newHours + newMinutes + newSeconds); } newMinutes = CLEAN_DEPARTURE_TIME_DEFAULT_MINUTES; int hours = Integer.parseInt(newHours); newHours = String.valueOf(hours + 1); return Integer.valueOf(newHours + newMinutes + newSeconds); } catch (Exception e) { System.out.println("Error while cleaning departure time '" + departureTimeS + "' '" + extraSeconds + "' !"); e.printStackTrace(); System.exit(-1); return -1; } } @Override public int getStartTime(GFrequency gFrequency) { return Integer.valueOf(gFrequency.start_time.replaceAll(TIME_SEPARATOR, Constants.EMPTY)); // GTFS standard } @Override public int getEndTime(GFrequency gFrequency) { return Integer.valueOf(gFrequency.end_time.replaceAll(TIME_SEPARATOR, Constants.EMPTY)); // GTFS standard } private static final int MIN_COVERAGE_AFTER_TODAY_IN_DAYS = 1; private static final int MIN_COVERAGE_AFTER_TOTAL_IN_DAYS = 30; public static HashSet<String> extractUsefulServiceIds(String[] args, DefaultAgencyTools agencyTools) { System.out.printf("Extracting useful service IDs...\n"); GSpec gtfs = GReader.readGtfsZipFile(args[0], agencyTools, true); Integer startDate = null; Integer endDate = null; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_MONTH, 1); // TOMORROW (too late to publish today's schedule) Integer todayStringInt = Integer.valueOf(simpleDateFormat.format(c.getTime())); if (gtfs.calendars != null && gtfs.calendars.size() > 0) { for (GCalendar gCalendar : gtfs.calendars) { if (gCalendar.start_date <= todayStringInt && gCalendar.end_date >= todayStringInt) { if (startDate == null || gCalendar.start_date < startDate) { startDate = gCalendar.start_date; } if (endDate == null || gCalendar.end_date > endDate) { endDate = gCalendar.end_date; } } } } else if (gtfs.calendarDates != null && gtfs.calendarDates.size() > 0) { HashSet<String> todayServiceIds = new HashSet<String>(); for (GCalendarDate gCalendarDate : gtfs.calendarDates) { if (gCalendarDate.date == todayStringInt) { todayServiceIds.add(gCalendarDate.service_id); } } if (todayServiceIds != null && todayServiceIds.size() > 0) { for (GCalendarDate gCalendarDate : gtfs.calendarDates) { for (String todayServiceId : todayServiceIds) { if (gCalendarDate.service_id.equals(todayServiceId)) { if (startDate == null || gCalendarDate.date < startDate) { startDate = gCalendarDate.date; } if (endDate == null || gCalendarDate.date > endDate) { endDate = gCalendarDate.date; } } } } if (endDate - startDate < MIN_COVERAGE_AFTER_TODAY_IN_DAYS) { endDate = startDate + MIN_COVERAGE_AFTER_TODAY_IN_DAYS; } boolean newDates; while (true) { newDates = false; for (GCalendarDate gCalendarDate : gtfs.calendarDates) { if (gCalendarDate.date >= startDate && gCalendarDate.date <= endDate) { todayServiceIds.add(gCalendarDate.service_id); } } for (GCalendarDate gCalendarDate : gtfs.calendarDates) { if (todayServiceIds.contains(gCalendarDate.service_id)) { if (startDate == null || gCalendarDate.date < startDate) { startDate = gCalendarDate.date; newDates = true; } if (endDate == null || gCalendarDate.date > endDate) { endDate = gCalendarDate.date; newDates = true; } } } if (newDates) { continue; } if (endDate - startDate < MIN_COVERAGE_AFTER_TOTAL_IN_DAYS) { try { c.setTime(simpleDateFormat.parse(String.valueOf(endDate))); c.add(Calendar.DAY_OF_MONTH, 1); endDate = Integer.valueOf(simpleDateFormat.format(c.getTime())); } catch (Exception e) { System.out.println("Error while increasing end date!"); e.printStackTrace(); System.exit(-1); } } else { break; } } } else { System.out.println("NO schedule available for " + todayStringInt + "!"); System.exit(-1); return null; } } else { System.out.println("NO schedule available for " + todayStringInt + "!"); System.exit(-1); return null; } System.out.println("Generated on " + todayStringInt + " | Schedules from " + startDate + " to " + endDate); HashSet<String> serviceIds = new HashSet<String>(); if (gtfs.calendars != null) { for (GCalendar gCalendar : gtfs.calendars) { if ((gCalendar.start_date >= startDate && gCalendar.start_date <= endDate) || (gCalendar.end_date >= startDate && gCalendar.end_date <= endDate)) { serviceIds.add(gCalendar.service_id); } } } if (gtfs.calendarDates != null) { for (GCalendarDate gCalendarDate : gtfs.calendarDates) { if (gCalendarDate.date >= startDate && gCalendarDate.date <= endDate) { serviceIds.add(gCalendarDate.service_id); } } } System.out.println("Service IDs: " + serviceIds); gtfs = null; System.out.printf("Extracting useful service IDs... DONE\n"); return serviceIds; } public static boolean excludeUselessCalendar(GCalendar gCalendar, HashSet<String> serviceIds) { if (serviceIds == null) { return false; // keep } return !serviceIds.contains(gCalendar.service_id); } public static boolean excludeUselessCalendarDate(GCalendarDate gCalendarDate, HashSet<String> serviceIds) { if (serviceIds == null) { return false; // keep } return !serviceIds.contains(gCalendarDate.service_id); } public static boolean excludeUselessTrip(GTrip gTrip, HashSet<String> serviceIds) { if (serviceIds == null) { return false; // keep } return !serviceIds.contains(gTrip.service_id); } }
package controllers.helper; import java.io.*; import java.util.*; import java.util.zip.*; import scala.Option; import scala.runtime.AbstractFunction0; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultTransaction; import org.geotools.data.Transaction; import org.geotools.data.collection.ListFeatureCollection; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.ShapefileDataStoreFactory; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureStore; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.geometry.jts.JTSFactoryFinder; import org.locationtech.jts.geom.GeometryFactory; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.locationtech.jts.geom.Coordinate; import models.attribute.GlobalAttributeForAPI; import models.attribute.GlobalAttributeWithLabelForAPI; import controllers.NeighborhoodAttributeSignificance; import controllers.StreetAttributeSignificance; /** * This example reads data for point locations and associated attributes from a comma separated text * (CSV) file and exports them as a new shapefile. It illustrates how to build a feature type. * * <p>Note: to keep things simple in the code below the input file should not have additional spaces * or tabs between fields. */ public class ShapefilesCreatorHelper { public static void createGeneralShapeFile(String outputFile, SimpleFeatureType TYPE, List<SimpleFeature> features) throws Exception{ /* * Get an output file name and create the new shapefile */ ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<>(); params.put("url", new File(outputFile + ".shp").toURI().toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); /* * TYPE is used as a template to describe the file contents */ newDataStore.createSchema(TYPE); /* * Write the features to the shapefile */ Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureType SHAPE_TYPE = featureSource.getSchema(); /* * The Shapefile format has a couple limitations: * - "the_geom" is always first, and used for the geometry attribute name * - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon * - Attribute names are limited in length * - Not all data types are supported (example Timestamp represented as Date) * * Each data store has different limitations so check the resulting SimpleFeatureType. */ if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; /* * SimpleFeatureStore has a method to add features from a * SimpleFeatureCollection object, so we use the ListFeatureCollection * class to wrap our list of features. */ SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features); featureStore.setTransaction(transaction); try { featureStore.addFeatures(collection); transaction.commit(); } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); } finally { transaction.close(); } } } public static void createAttributeShapeFile(String outputFile, List<GlobalAttributeForAPI> attributes) throws Exception { /* * We use the DataUtilities class to create a FeatureType that will describe the data in our * shapefile. * * See also the createFeatureType method below for another, more flexible approach. */ final SimpleFeatureType TYPE = DataUtilities.createType( "Location", "the_geom:Point:srid=4326," + // <- the geometry attribute: Point type "id:Integer," + // <- a attribute ID "label_type:String," + // <- Label type "name:String," + // <- Neighborhood Name "severity:Integer," + // <- Severity "temporary:Boolean" // Temporary flag ); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); for(GlobalAttributeForAPI a : attributes){ featureBuilder.add(geometryFactory.createPoint(new Coordinate(a.lng(), a.lat()))); featureBuilder.add(a.globalAttributeId()); featureBuilder.add(a.labelType()); featureBuilder.add(a.neighborhoodName()); featureBuilder.add(a.severity().getOrElse(new AbstractFunction0<Integer>() { @Override public Integer apply() { return null; } })); featureBuilder.add(a.temporary()); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } createGeneralShapeFile(outputFile, TYPE, features); } public static void createLabelShapeFile(String outputFile, List<GlobalAttributeWithLabelForAPI> labels) throws Exception { /* * We use the DataUtilities class to create a FeatureType that will describe the data in our * shapefile. * * See also the createFeatureType method below for another, more flexible approach. */ final SimpleFeatureType TYPE = DataUtilities.createType( "Location", "the_geom:Point:srid=4326," + // <- the geometry attribute: Point type "labelId:Integer," + // <- label ID "attribId:Integer," + // <- attribute ID "lblType:String," + // <- Label type "name:String," + // <- Neighborhood Name "severity:Integer," + // <- Severity "temporary:Boolean," + // <- Temporary flag "nbr:String," + // <- neighborhood name "gsvPanoID:String," + // <- GSV Panorama ID "heading:Double," + // <- heading of panorama "pitch:Double," + // <- pitch of panorama "zoom:Integer," + // <- zoom of panorama "canvasX:Integer," + // <- canvasX position of panorama "canvasY:Integer," + // <- canvasY position of panorama "canvasW:Integer," + // <- width of source viewfinder "canvasH:Integer" // height of source viewfinder ); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); for(GlobalAttributeWithLabelForAPI l : labels){ featureBuilder.add(geometryFactory.createPoint(new Coordinate((double) l.labelLng(), (double) l.labelLat()))); featureBuilder.add(l.labelId()); featureBuilder.add(l.globalAttributeId()); featureBuilder.add(l.labelType()); featureBuilder.add(l.neighborhoodName()); featureBuilder.add(l.labelSeverity().getOrElse(new AbstractFunction0<Integer>() { @Override public Integer apply() { return null; } })); featureBuilder.add(l.labelTemporary()); featureBuilder.add(l.neighborhoodName()); featureBuilder.add(l.gsvPanoramaId()); featureBuilder.add(l.heading()); featureBuilder.add(l.pitch()); featureBuilder.add(l.zoom()); featureBuilder.add(l.canvasX()); featureBuilder.add(l.canvasY()); featureBuilder.add(l.canvasWidth()); featureBuilder.add(l.canvasHeight()); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } createGeneralShapeFile(outputFile, TYPE, features); } public static void createStreetShapefile(String outputFile, List<StreetAttributeSignificance> streets) throws Exception{ /* * We use the DataUtilities class to create a FeatureType that will describe the data in our * shapefile. * * See also the createFeatureType method below for another, more flexible approach. */ final SimpleFeatureType TYPE = DataUtilities.createType( "Location", "the_geom:LineString:srid=4326," + // <- the geometry attribute: Line type "streetId:Integer," + // <- StreetId "score:Double," + // street score "sigRamp:Double," + // curb ramp significance score "sigNoRamp:Double," + // no Curb ramp significance score "sigObs:Double," + // obstacle significance score "sigSurfce:Double," + // Surface problem significance score "nRamp:Double," + // curb ramp feature score "nNoRamp:Double," + // no Curb ramp feature score "nObs:Double," + // obstacle feature score "nSurfce:Double" // Surface problem feature score ); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); // for(Street s : streets){ // featureBuilder.add(geometryFactory.createLineString(s.geometry)); // featureBuilder.add(s.streetId); // featureBuilder.add(s.score); // SimpleFeature feature = featureBuilder.buildFeature(null); // features.add(feature); for (int i = 0; i < streets.size(); i++) { StreetAttributeSignificance s = streets.get(i); featureBuilder.add(geometryFactory.createLineString(s.geometry())); featureBuilder.add(s.streetID()); featureBuilder.add(s.score()); featureBuilder.add(s.significanceScores()[0]); featureBuilder.add(s.significanceScores()[1]); featureBuilder.add(s.significanceScores()[2]); featureBuilder.add(s.significanceScores()[3]); featureBuilder.add(s.attributeScores()[0]); featureBuilder.add(s.attributeScores()[1]); featureBuilder.add(s.attributeScores()[2]); featureBuilder.add(s.attributeScores()[3]); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } createGeneralShapeFile(outputFile, TYPE, features); } public static void createNeighborhoodShapefile(String outputFile, List<NeighborhoodAttributeSignificance> neighborhoods) throws Exception{ /* * We use the DataUtilities class to create a FeatureType that will describe the data in our * shapefile. * * See also the createFeatureType method below for another, more flexible approach. */ final SimpleFeatureType TYPE = DataUtilities.createType( "Location", "the_geom:Polygon:srid=4326," + // line geometry "name:String," + // <- Neighborhood Name "regionId:Integer," + // <- Neighborhood Id "coverage:Double," + // coverage score "score:Double," + // obstacle score "sigRamp:Double," + // curb ramp significance score "sigNoRamp:Double," + // no Curb ramp significance score "sigObs:Double," + // obstacle significance score "sigSurfce:Double," + // Surface problem significance score "nRamp:Double," + // curb ramp feature score "nNoRamp:Double," + // no Curb ramp feature score "nObs:Double," + // obstacle feature score "nSurfce:Double" // Surface problem feature score ); /* * A list to collect features as we create them. */ List<SimpleFeature> features = new ArrayList<>(); /* * GeometryFactory will be used to create the geometry attribute of each feature, * using a Point object for the location. */ GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); for(NeighborhoodAttributeSignificance n : neighborhoods){ featureBuilder.add(geometryFactory.createPolygon(n.geometry())); featureBuilder.add(n.name()); featureBuilder.add(n.regionID()); featureBuilder.add(n.coverage()); featureBuilder.add(n.score()); featureBuilder.add(n.significanceScores()[0]); featureBuilder.add(n.significanceScores()[1]); featureBuilder.add(n.significanceScores()[2]); featureBuilder.add(n.significanceScores()[3]); featureBuilder.add(n.attributeScores()[0]); featureBuilder.add(n.attributeScores()[1]); featureBuilder.add(n.attributeScores()[2]); featureBuilder.add(n.attributeScores()[3]); SimpleFeature feature = featureBuilder.buildFeature(null); features.add(feature); } createGeneralShapeFile(outputFile, TYPE, features); } public static File zipShapeFiles(String name, String[] files) throws IOException{ FileOutputStream fos = new FileOutputStream(name + ".zip"); ZipOutputStream zipOut = new ZipOutputStream(fos); for (String outputFile: files){ List<String> components = Arrays.asList(outputFile + ".dbf", outputFile + ".fix", outputFile + ".prj", outputFile + ".shp", outputFile + ".shx"); for (String srcFile : components){ try { File fileToZip = new File(srcFile); FileInputStream fis = new FileInputStream(srcFile); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); fileToZip.delete(); } catch (Exception e){ } } } zipOut.close(); fos.close(); return new File(name + ".zip"); } }
package onion.compiler.pass; 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 java.util.Stack; import java.util.TreeSet; import onion.compiler.*; import onion.compiler.ClassTable; import onion.compiler.ClosureLocalBinding; import onion.compiler.ImportItem; import onion.compiler.ImportList; import onion.compiler.LocalContext; import onion.compiler.LocalFrame; import onion.compiler.StaticImportItem; import onion.compiler.StaticImportList; import onion.compiler.CompilationException; import onion.compiler.util.Boxing; import onion.compiler.util.Classes; import onion.compiler.util.Paths; import onion.compiler.util.Systems; import onion.lang.syntax.*; import onion.lang.syntax.visitor.ASTVisitor; import static onion.compiler.SemanticErrorReporter.Constants.*; import static onion.compiler.IxCode.BinaryExpression.Constants.*; import static onion.compiler.IxCode.UnaryExpression.Constants.*; public class CodeAnalysis { private SemanticErrorReporter reporter; private CompilerConfig config; private ClassTable table; private Map<IxCode.Node, AstNode> irt2ast; private Map<AstNode, IxCode.Node> ast2irt; private Map<String, NameResolution> solvers; private CompilationUnit unit; private StaticImportList staticImport; private ImportList currentImport; private IxCode.ClassDefinition contextClass; private NameResolution solver; private int access; public String topClass(){ ModuleDeclaration module = unit.getModuleDeclaration(); String moduleName = module != null ? module.getName() : null; return createName(moduleName, Paths.cutExtension(unit.getSourceFileName()) + "Main"); } public void put(AstNode astNode, IxCode.Node kernelNode){ ast2irt.put(astNode, kernelNode); irt2ast.put(kernelNode, astNode); } public AstNode lookupAST(IxCode.Node kernelNode){ return irt2ast.get(kernelNode); } public IxCode.Node lookupKernelNode(AstNode astNode){ return ast2irt.get(astNode); } public void addSolver(String className, NameResolution solver) { solvers.put(className, solver); } public NameResolution findSolver(String className){ return solvers.get(className); } private String createName(String moduleName, String simpleName){ return (moduleName != null ? moduleName + "." : "") + simpleName; } private String classpath(String[] classPaths){ StringBuffer path = new StringBuffer(); if(classPaths.length > 0){ path.append(classPaths[0]); for(int i = 1; i < classPaths.length; i++){ path.append(Systems.getPathSeparator()); path.append(classPaths[i]); } } return new String(path); } public IxCode.TypeRef resolve(TypeSpec type, NameResolution resolver) { IxCode.TypeRef resolvedType = resolver.resolve(type); if(resolvedType == null) report(CLASS_NOT_FOUND, type, type.getComponentName()); return resolvedType; } public IxCode.TypeRef resolve(TypeSpec type) { return resolve(type, solver); } public void report(int error, AstNode node, Object... items) { reporter.setSourceFile(unit.getSourceFileName()); reporter.report(error, node.getLocation(), items); } public IxCode.ClassTypeRef load(String name) { return table.load(name); } public IxCode.ClassTypeRef loadTopClass() { return table.load(topClass()); } public IxCode.ArrayTypeRef loadArray(IxCode.TypeRef type, int dimension) { return table.loadArray(type, dimension); } public IxCode.ClassTypeRef rootClass() { return table.rootClass(); } public CompileError[] getProblems() { return reporter.getProblems(); } public IxCode.ClassDefinition[] getSourceClasses() { return table.classes().values().toArray(new IxCode.ClassDefinition[0]); } private class ClassTableBuilder extends ASTVisitor<String> { public ClassTableBuilder() { } public void process(CompilationUnit unit){ CodeAnalysis.this.unit = unit; ModuleDeclaration module = unit.getModuleDeclaration(); ImportListDeclaration imports = unit.getImportListDeclaration(); String moduleName = module != null ? module.getName() : null; ImportList list = new ImportList(); list.add(new ImportItem("*", "java.lang.*")); list.add(new ImportItem("*", "java.io.*")); list.add(new ImportItem("*", "java.util.*")); list.add(new ImportItem("*", "javax.swing.*")); list.add(new ImportItem("*", "java.awt.event.*")); list.add(new ImportItem("*", "onion.*")); list.add(new ImportItem("*", moduleName != null ? moduleName + ".*" : "*")); if(imports != null){ for(int i = 0; i < imports.size(); i++){ list.add(new ImportItem(imports.getName(i), imports.getFQCN(i))); } } StaticImportList staticList = new StaticImportList(); staticList.add(new StaticImportItem("java.lang.System", true)); staticList.add(new StaticImportItem("java.lang.Runtime", true)); staticList.add(new StaticImportItem("java.lang.Math", true)); currentImport = list; staticImport = staticList; int count = 0; for(TopLevelElement top:unit.getTopLevels()) { if(top instanceof TypeDeclaration){ accept(top, moduleName); }else { count++; } } ClassTable table = CodeAnalysis.this.table; if(count > 0){ IxCode.ClassDefinition node = IxCode.ClassDefinition.newClass(0, topClass(), table.rootClass(), new IxCode.ClassTypeRef[0]); node.setSourceFile(Paths.nameOf(unit.getSourceFileName())); node.setResolutionComplete(true); table.classes().add(node); node.addDefaultConstructor(); put(unit, node); addSolver(node.name(), new NameResolution(list)); } } public Object visit(ClassDeclaration ast, String context) { String module = context; IxCode.ClassDefinition node = IxCode.ClassDefinition.newClass(ast.getModifier(), createFQCN(module, ast.getName())); node.setSourceFile(Paths.nameOf(unit.getSourceFileName())); if(table.lookup(node.name()) != null){ report(DUPLICATE_CLASS, ast, node.name()); return null; } table.classes().add(node); put(ast, node); addSolver(node.name(), new NameResolution(currentImport)); return null; } public Object visit(InterfaceDeclaration ast, String context) { String module = context; IxCode.ClassDefinition node = IxCode.ClassDefinition.newInterface(ast.getModifier(), createFQCN(module, ast.getName()), null); node.setSourceFile(Paths.nameOf(unit.getSourceFileName())); ClassTable table = CodeAnalysis.this.table; if(table.lookup(node.name()) != null){ report(DUPLICATE_CLASS, ast, node.name()); return null; } table.classes().add(node); put(ast, node); addSolver(node.name(), new NameResolution(currentImport) ); return null; } private String createFQCN(String moduleName, String simpleName) { return (moduleName != null ? moduleName + "." : "") + simpleName; } } private class TypeHeaderAnalysis extends ASTVisitor<Void> { private int countConstructor; public TypeHeaderAnalysis() { } public void process(CompilationUnit unit){ CodeAnalysis.this.unit = unit; TopLevelElement[] toplevels = unit.getTopLevels(); for(int i = 0; i < toplevels.length; i++){ CodeAnalysis.this.solver = findSolver(topClass()); accept(toplevels[i]); } } public Object visit(ClassDeclaration ast, Void context) { countConstructor = 0; IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast); CodeAnalysis.this.contextClass = node; CodeAnalysis.this.solver = findSolver(node.name()); constructTypeHierarchy(node, new ArrayList()); if(hasCyclicity(node)) report(CYCLIC_INHERITANCE, ast, node.name()); if(ast.getDefaultSection() != null){ accept(ast.getDefaultSection()); } AccessSection[] sections = ast.getSections(); for(int i = 0; i < sections.length; i++){ accept(sections[i]); } if(countConstructor == 0){ node.addDefaultConstructor(); } return null; } public Object visit(InterfaceDeclaration ast, Void context) { IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast); CodeAnalysis.this.contextClass = node; CodeAnalysis.this.solver = findSolver(node.name()); constructTypeHierarchy(node, new ArrayList()); if(hasCyclicity(node)){ report(CYCLIC_INHERITANCE, ast, node.name()); } InterfaceMethodDeclaration[] members = ast.getDeclarations(); for(int i = 0; i < members.length; i++){ accept(members[i], context); } return null; } public Object visit(DelegationDeclaration ast, Void context) { IxCode.TypeRef type = resolve(ast.getType()); if(type == null) return null; if(!(type.isObjectType() && ((IxCode.ObjectTypeRef)type).isInterface())){ report(INTERFACE_REQUIRED, ast.getType(), type); return null; } IxCode.ClassDefinition contextClass = CodeAnalysis.this.contextClass; int modifier = ast.getModifier() | access | Modifier.FORWARDED; String name = ast.getName(); IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, contextClass, name, type); put(ast, node); contextClass.add(node); return null; } public Object visit(ConstructorDeclaration ast, Void context) { countConstructor++; IxCode.TypeRef[] args = typesOf(ast.getArguments()); IxCode.ClassDefinition contextClass = CodeAnalysis.this.contextClass; if(args == null) return null; int modifier = ast.getModifier() | access; IxCode.ConstructorDefinition node = new IxCode.ConstructorDefinition(modifier, contextClass, args, null, null); put(ast, node); contextClass.add(node); return null; } public Object visit(MethodDeclaration ast, Void context) { IxCode.TypeRef[] args = typesOf(ast.getArguments()); IxCode.TypeRef returnType; if(ast.getReturnType() != null){ returnType = resolve(ast.getReturnType()); }else{ returnType = IxCode.BasicTypeRef.VOID; } if(args == null || returnType == null) return null; IxCode.ClassDefinition contextClass = CodeAnalysis.this.contextClass; int modifier = ast.getModifier() | access; if(ast.getBlock() == null) modifier |= Modifier.ABSTRACT; String name = ast.getName(); IxCode.MethodDefinition node = new IxCode.MethodDefinition(modifier, contextClass, name, args, returnType, null); put(ast, node); contextClass.add(node); return null; } public Object visit(FieldDeclaration ast, Void context) { IxCode.TypeRef type = resolve(ast.getType()); if(type == null) return null; IxCode.ClassDefinition contextClass = CodeAnalysis.this.contextClass; int modifier = ast.getModifier() | access; String name = ast.getName(); IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, contextClass, name, type); put(ast, node); contextClass.add(node); return node; } private IxCode.TypeRef[] typesOf(Argument[] ast){ IxCode.TypeRef[] types = new IxCode.TypeRef[ast.length]; boolean success = true; for (int i = 0; i < ast.length; i++) { types[i] = (IxCode.TypeRef) accept(ast[i]); if(types[i] == null) success = false; } if(success){ return types; }else{ return null; } } public Object visit(Argument ast, Void context){ IxCode.TypeRef type = resolve(ast.getType()); return type; } private IxCode.FieldDefinition createFieldNode(FieldDeclaration ast){ IxCode.TypeRef type = resolve(ast.getType()); if(type == null) return null; IxCode.FieldDefinition node = new IxCode.FieldDefinition( ast.getModifier() | access, contextClass, ast.getName(), type); return node; } public Object visit(InterfaceMethodDeclaration ast, Void context) { IxCode.TypeRef[] args = typesOf(ast.getArguments()); IxCode.TypeRef returnType; if(ast.getReturnType() != null){ returnType = resolve(ast.getReturnType()); }else{ returnType = IxCode.BasicTypeRef.VOID; } if(args == null || returnType == null) return null; int modifier = Modifier.PUBLIC | Modifier.ABSTRACT; IxCode.ClassDefinition classType = contextClass; String name = ast.getName(); IxCode.MethodDefinition node = new IxCode.MethodDefinition(modifier, classType, name, args, returnType, null); put(ast, node); classType.add(node); return null; } public Object visit(FunctionDeclaration ast, Void context) { IxCode.TypeRef[] args = typesOf(ast.getArguments()); IxCode.TypeRef returnType; if(ast.getReturnType() != null){ returnType = resolve(ast.getReturnType()); }else{ returnType = IxCode.BasicTypeRef.VOID; } if(args == null || returnType == null) return null; IxCode.ClassDefinition classType = (IxCode.ClassDefinition) loadTopClass(); int modifier = ast.getModifier() | Modifier.PUBLIC; String name = ast.getName(); IxCode.MethodDefinition node = new IxCode.MethodDefinition(modifier, classType, name, args, returnType, null); put(ast, node); classType.add(node); return null; } public Object visit(GlobalVariableDeclaration ast, Void context) { IxCode.TypeRef type = resolve(ast.getType()); if(type == null) return null; int modifier = ast.getModifier() | Modifier.PUBLIC; IxCode.ClassDefinition classType = (IxCode.ClassDefinition)loadTopClass(); String name = ast.getName(); IxCode.FieldDefinition node = new IxCode.FieldDefinition(modifier, classType, name, type); put(ast, node); classType.add(node); return null; } public Object visit(AccessSection section, Void context){ if(section == null) return null; CodeAnalysis.this.access = section.getID(); MemberDeclaration[] members = section.getMembers(); for(int i = 0; i < members.length; i++){ accept(members[i], context); } return null; } public boolean hasCyclicity(IxCode.ClassDefinition start){ return hasCylicitySub(start, new HashSet()); } private boolean hasCylicitySub(IxCode.ClassTypeRef symbol, HashSet visit){ if(symbol == null) return false; if(visit.contains(symbol)){ return true; } visit.add(symbol); if(hasCylicitySub(symbol.getSuperClass(), (HashSet)visit.clone())){ return true; } IxCode.ClassTypeRef[] interfaces = symbol.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if(hasCylicitySub(interfaces[i], (HashSet)visit.clone())){ return true; } } return false; } private void constructTypeHierarchy(IxCode.ClassTypeRef ref, List<IxCode.ClassTypeRef> visit) { if(ref == null || visit.indexOf(ref) >= 0) return; visit.add(ref); if(ref instanceof IxCode.ClassDefinition){ IxCode.ClassDefinition node = (IxCode.ClassDefinition) ref; if(node.isResolutionComplete()) return; IxCode.ClassTypeRef superClass = null; List<IxCode.ClassTypeRef> interfaces = new ArrayList<IxCode.ClassTypeRef>(); NameResolution resolver = findSolver(node.name()); if(node.isInterface()){ InterfaceDeclaration ast = (InterfaceDeclaration) lookupAST(node); superClass = rootClass(); TypeSpec[] typeSpecifiers = ast.getInterfaces(); for(TypeSpec typeSpec:ast.getInterfaces()) { IxCode.ClassTypeRef superType = validateSuperType(typeSpec, true, resolver); if(superType != null) interfaces.add(superType); } }else{ ClassDeclaration ast = (ClassDeclaration) lookupAST(node); superClass = validateSuperType(ast.getSuperClass(), false, resolver); for(TypeSpec typeSpec:ast.getInterfaces()) { IxCode.ClassTypeRef superType = validateSuperType(typeSpec, true, resolver); if(superType != null) interfaces.add(superType); } } constructTypeHierarchy(superClass, visit); for(IxCode.ClassTypeRef superType:interfaces) { constructTypeHierarchy(superType, visit); } node.setSuperClass(superClass); node.setInterfaces(interfaces.toArray(new IxCode.ClassTypeRef[0])); node.setResolutionComplete(true); }else{ constructTypeHierarchy(ref.getSuperClass(), visit); IxCode.ClassTypeRef[] interfaces = ref.getInterfaces(); for(int i = 0; i < interfaces.length; i++){ constructTypeHierarchy(interfaces[i], visit); } } } private IxCode.ClassTypeRef validateSuperType( TypeSpec ast, boolean shouldInterface, NameResolution resolver){ IxCode.ClassTypeRef symbol = null; if(ast == null){ symbol = table.rootClass(); }else{ symbol = (IxCode.ClassTypeRef) resolve(ast, resolver); } if(symbol == null) return null; boolean isInterface = symbol.isInterface(); if(((!isInterface) && shouldInterface) || (isInterface && (!shouldInterface))){ AstNode astNode = null; if(symbol instanceof IxCode.ClassDefinition){ astNode = lookupAST((IxCode.ClassDefinition)symbol); } report(ILLEGAL_INHERITANCE, astNode, symbol.name()); } return symbol; } } private class DuplicationChecker extends ASTVisitor<Void> { private Set methods; private Set constructors; private Set fields; private Set variables; private Set functions; public DuplicationChecker() { this.methods = new TreeSet(new IxCode.MethodRefComparator()); this.fields = new TreeSet(new IxCode.FieldRefComparator()); this.constructors = new TreeSet(new IxCode.ConstructorRefComparator()); this.variables = new TreeSet(new IxCode.FieldRefComparator()); this.functions = new TreeSet(new IxCode.MethodRefComparator()); } public void process(CompilationUnit unit){ CodeAnalysis.this.unit = unit; variables.clear(); functions.clear(); TopLevelElement[] toplevels = unit.getTopLevels(); for(int i = 0; i < toplevels.length; i++){ CodeAnalysis.this.solver = findSolver(topClass()); accept(toplevels[i]); } } public Object visit(ClassDeclaration ast, Void context) { IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast); if(node == null) return null; methods.clear(); fields.clear(); constructors.clear(); CodeAnalysis.this.contextClass = node; CodeAnalysis.this.solver = findSolver(node.name()); if(ast.getDefaultSection() != null){ accept(ast.getDefaultSection()); } AccessSection[] sections = ast.getSections(); for(int i = 0; i < sections.length; i++){ accept(sections[i]); } generateMethods(); return null; } private void generateMethods(){ Set generated = new TreeSet(new IxCode.MethodRefComparator()); Set methodSet = new TreeSet(new IxCode.MethodRefComparator()); for(Iterator i = fields.iterator(); i.hasNext();){ IxCode.FieldDefinition node = (IxCode.FieldDefinition)i.next(); if(Modifier.isForwarded(node.modifier())){ generateDelegationMethods(node ,generated, methodSet); } } } private void generateDelegationMethods(IxCode.FieldDefinition node, Set generated, Set methodSet){ IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) node.getType(); Set src = Classes.getInterfaceMethods(type); for (Iterator i = src.iterator(); i.hasNext();) { IxCode.MethodRef method = (IxCode.MethodRef) i.next(); if(!methodSet.contains(method)) { if(generated.contains(method)){ report(DUPLICATE_GENERATED_METHOD, lookupAST(node), method.affiliation(), method.name(), method.arguments()); }else { IxCode.MethodDefinition generatedMethod = createEmptyMethod(node, method); generated.add(generatedMethod); contextClass.add(generatedMethod); } } } } private IxCode.MethodDefinition createEmptyMethod(IxCode.FieldRef field, IxCode.MethodRef method){ IxCode.Expression target; target = new IxCode.RefField(new IxCode.This(contextClass), field); IxCode.TypeRef[] args = method.arguments(); IxCode.Expression[] params = new IxCode.Expression[args.length]; LocalFrame frame = new LocalFrame(null); for(int i = 0; i < params.length; i++){ int index = frame.add("arg" + i, args[i]); params[i] = new IxCode.RefLocal(new ClosureLocalBinding(0, index, args[i])); } target = new IxCode.Call(target, method, params); IxCode.StatementBlock statement; if(method.returnType() != IxCode.BasicTypeRef.VOID){ statement = new IxCode.StatementBlock(new IxCode.Return(target)); }else{ statement = new IxCode.StatementBlock(new IxCode.ExpressionStatement(target), new IxCode.Return(null)); } IxCode.MethodDefinition node = new IxCode.MethodDefinition( Modifier.PUBLIC, contextClass, method.name(), method.arguments(), method.returnType(), statement ); node.setFrame(frame); return node; } public Object visit(InterfaceDeclaration ast, Void context) { IxCode.ClassDefinition node = (IxCode.ClassDefinition) lookupKernelNode(ast); if(node == null) return null; methods.clear(); fields.clear(); constructors.clear(); CodeAnalysis.this.contextClass = node; CodeAnalysis.this.solver = findSolver(node.name()); InterfaceMethodDeclaration[] members = ast.getDeclarations(); for(int i = 0; i < members.length; i++){ accept(members[i], context); } return null; } public Object visit(ConstructorDeclaration ast, Void context) { IxCode.ConstructorDefinition node = (IxCode.ConstructorDefinition) lookupKernelNode(ast); if(node == null) return null; if(constructors.contains(node)){ IxCode.ClassTypeRef classType = node.affiliation(); IxCode.TypeRef[] args = node.getArgs(); report(DUPLICATE_CONSTRUCTOR, ast, classType, args); }else{ constructors.add(node); } return null; } public Object visit(DelegationDeclaration ast, Void context) { IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast); if(node == null) return null; if(fields.contains(node)){ IxCode.ClassTypeRef classType = node.affiliation(); String name = node.name(); report(DUPLICATE_FIELD, ast, classType, name); }else{ fields.add(node); } return null; } public Object visit(MethodDeclaration ast, Void context) { IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast); if(node == null) return null; if(methods.contains(node)){ IxCode.ClassTypeRef classType = node.affiliation(); String name = node.name(); IxCode.TypeRef[] args = node.arguments(); report(DUPLICATE_METHOD, ast, classType, name, args); }else{ methods.add(node); } return null; } public Object visit(FieldDeclaration ast, Void context) { IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast); if(node == null) return null; if(fields.contains(node)){ IxCode.ClassTypeRef classType = node.affiliation(); String name = node.name(); report(DUPLICATE_FIELD, ast, classType, name); }else{ fields.add(node); } return null; } public Object visit(InterfaceMethodDeclaration ast, Void context) { IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast); if(node == null) return null; if(methods.contains(node)){ IxCode.ClassTypeRef classType = node.affiliation(); String name = node.name(); IxCode.TypeRef[] args = node.arguments(); report(DUPLICATE_METHOD, ast, classType, name, args); }else{ methods.add(node); } return null; } public Object visit(FunctionDeclaration ast, Void context) { IxCode.MethodDefinition node = (IxCode.MethodDefinition) lookupKernelNode(ast); if(node == null) return null; if(functions.contains(node)){ String name = node.name(); IxCode.TypeRef[] args = node.arguments(); report(DUPLICATE_FUNCTION, ast, name, args); }else{ functions.add(node); } return null; } public Object visit(GlobalVariableDeclaration ast, Void context) { IxCode.FieldDefinition node = (IxCode.FieldDefinition) lookupKernelNode(ast); if(node == null) return null; if(variables.contains(node)){ String name = node.name(); report(DUPLICATE_GLOBAL_VARIABLE, ast, name); }else{ variables.add(node); } return null; } public Object visit(AccessSection section, Void context){ if(section == null) return null; MemberDeclaration[] members = section.getMembers(); for(int i = 0; i < members.length; i++){ accept(members[i], context); } return null; } } private class TypeChecker extends ASTVisitor<LocalContext> { public TypeChecker(){ } public void process(CompilationUnit unit){ accept(unit); } public Object visit(CompilationUnit unit, LocalContext object) { CodeAnalysis.this.unit = unit; TopLevelElement[] toplevels = unit.getTopLevels(); LocalContext context = new LocalContext(); List<IxCode.ActionStatement> statements = new ArrayList<IxCode.ActionStatement>(); String className = topClass(); CodeAnalysis.this.solver = findSolver(topClass()); IxCode.ClassDefinition klass = (IxCode.ClassDefinition) loadTopClass(); IxCode.ArrayTypeRef argsType = loadArray(load("java.lang.String"), 1); IxCode.MethodDefinition method = new IxCode.MethodDefinition(Modifier.PUBLIC, klass, "start", new IxCode.TypeRef[]{argsType}, IxCode.BasicTypeRef.VOID, null); context.add("args", argsType); for(TopLevelElement element:toplevels) { if(!(element instanceof TypeDeclaration)){ CodeAnalysis.this.contextClass = klass; } if(element instanceof Statement){ context.setMethod(method); IxCode.ActionStatement statement = (IxCode.ActionStatement) accept(element, context); statements.add(statement); }else{ accept(element, null); } } if(klass != null){ statements.add(new IxCode.Return(null)); method.setBlock(new IxCode.StatementBlock(statements)); method.setFrame(context.getContextFrame()); klass.add(method); klass.add(createMain(klass, method, "main", new IxCode.TypeRef[]{argsType}, IxCode.BasicTypeRef.VOID)); } return null; } private IxCode.MethodDefinition createMain(IxCode.ClassTypeRef top, IxCode.MethodRef ref, String name, IxCode.TypeRef[] args, IxCode.TypeRef ret) { IxCode.MethodDefinition method = new IxCode.MethodDefinition(Modifier.STATIC | Modifier.PUBLIC, top, name, args, ret, null); LocalFrame frame = new LocalFrame(null); IxCode.Expression[] params = new IxCode.Expression[args.length]; for(int i = 0; i < args.length; i++){ int index = frame.add("args" + i, args[i]); params[i] = new IxCode.RefLocal(0, index, args[i]); } method.setFrame(frame); IxCode.ConstructorRef cref = top.findConstructor(new IxCode.Expression[0])[0]; IxCode.StatementBlock block = new IxCode.StatementBlock( new IxCode.ExpressionStatement(new IxCode.Call(new IxCode.NewObject(cref, new IxCode.Expression[0]), ref, params)) ); block = addReturnNode(block, IxCode.BasicTypeRef.VOID); method.setBlock(block); return method; } public Object visit(InterfaceDeclaration ast, LocalContext context) { CodeAnalysis.this.contextClass = (IxCode.ClassDefinition) lookupKernelNode(ast); return null; } public Object visit(ClassDeclaration ast, LocalContext context) { CodeAnalysis.this.contextClass = (IxCode.ClassDefinition) lookupKernelNode(ast); CodeAnalysis.this.solver = findSolver(contextClass.name()); if(ast.getDefaultSection() != null){ accept(ast.getDefaultSection(), context); } acceptEach(ast.getSections(), context); return null; } public Object visit(AccessSection ast, LocalContext context) { acceptEach(ast.getMembers(), context); return null; } public Object visit(Addition ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; if(left.isBasicType() && right.isBasicType()){ return checkNumExp(ADD, ast, left, right, context); } if(left.isBasicType()){ if(left.type() == IxCode.BasicTypeRef.VOID){ report(IS_NOT_BOXABLE_TYPE, ast.getLeft(), left.type()); return null; }else{ left = Boxing.boxing(table, left); } } if(right.isBasicType()){ if(right.type() == IxCode.BasicTypeRef.VOID){ report(IS_NOT_BOXABLE_TYPE, ast.getRight(), right.type()); return null; }else{ right = Boxing.boxing(table, right); } } IxCode.MethodRef toString; toString = findMethod(ast.getLeft(), (IxCode.ObjectTypeRef)left.type(), "toString"); left = new IxCode.Call(left, toString, new IxCode.Expression[0]); toString = findMethod(ast.getRight(), (IxCode.ObjectTypeRef)right.type(), "toString"); right = new IxCode.Call(right, toString, new IxCode.Expression[0]); IxCode.MethodRef concat = findMethod(ast, (IxCode.ObjectTypeRef)left.type(), "concat", new IxCode.Expression[]{right}); return new IxCode.Call(left, concat, new IxCode.Expression[]{right}); } public Object visit(PostIncrement node, LocalContext context) { IxCode.Expression operand = typeCheck(node.getTarget(), context); if(operand == null) return null; if((!operand.isBasicType()) || !hasNumericType(operand)){ report(INCOMPATIBLE_OPERAND_TYPE, node, node.getSymbol(), new IxCode.TypeRef[]{operand.type()}); return null; } IxCode.Expression result = null; if(operand instanceof IxCode.RefLocal){ int varIndex = context.add(context.newName(), operand.type()); IxCode.RefLocal ref = (IxCode.RefLocal)operand; result = new IxCode.Begin( new IxCode.SetLocal(0, varIndex, operand.type(), operand), new IxCode.SetLocal( ref.frame(), ref.index(), ref.type(), new IxCode.BinaryExpression( ADD, operand.type(), new IxCode.RefLocal(0, varIndex, operand.type()), new IxCode.IntLiteral(1) ) ), new IxCode.RefLocal(0, varIndex, operand.type()) ); }else if(operand instanceof IxCode.RefField){ IxCode.RefField ref = (IxCode.RefField)operand; int varIndex = context.add(context.newName(), ref.target.type()); result = new IxCode.Begin( new IxCode.SetLocal(0, varIndex, ref.target.type(), ref.target), new IxCode.SetField( new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field, new IxCode.BinaryExpression( ADD, operand.type(), new IxCode.RefField(new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field), new IxCode.IntLiteral(1) ) ) ); }else { report(UNIMPLEMENTED_FEATURE, node); } return result; } public Object visit(PostDecrement node, LocalContext context) { IxCode.Expression operand = typeCheck(node.getTarget(), context); if(operand == null) return null; if((!operand.isBasicType()) || !hasNumericType(operand)){ report(INCOMPATIBLE_OPERAND_TYPE, node, node.getSymbol(), new IxCode.TypeRef[]{operand.type()}); return null; } IxCode.Expression result = null; if(operand instanceof IxCode.RefLocal){ int varIndex = context.add(context.newName(), operand.type()); IxCode.RefLocal ref = (IxCode.RefLocal)operand; result = new IxCode.Begin( new IxCode.SetLocal(0, varIndex, operand.type(), operand), new IxCode.SetLocal( ref.frame(), ref.index(), ref.type(), new IxCode.BinaryExpression( SUBTRACT, operand.type(), new IxCode.RefLocal(0, varIndex, operand.type()), new IxCode.IntLiteral(1) ) ), new IxCode.RefLocal(0, varIndex, operand.type()) ); }else if(operand instanceof IxCode.RefField){ IxCode.RefField ref = (IxCode.RefField)operand; int varIndex = context.add(context.newName(), ref.target.type()); result = new IxCode.Begin( new IxCode.SetLocal(0, varIndex, ref.target.type(), ref.target), new IxCode.SetField( new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field, new IxCode.BinaryExpression( SUBTRACT, operand.type(), new IxCode.RefField(new IxCode.RefLocal(0, varIndex, ref.target.type()), ref.field), new IxCode.IntLiteral(1) ) ) ); }else { report(UNIMPLEMENTED_FEATURE, node); } return result; } @Override public Object visit(Elvis ast, LocalContext context) { IxCode.Expression l = typeCheck(ast.getLeft(), context); IxCode.Expression r = typeCheck(ast.getRight(), context); if(l.isBasicType() || r.isBasicType() || !IxCode.TypeRules.isAssignable(l.type(), r.type())) { report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{l.type(), r.type()}); return null; } return new IxCode.BinaryExpression(ELVIS, l.type(), l, r); } public Object visit(Subtraction ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; return checkNumExp(SUBTRACT, ast, left, right, context); } public Object visit(Multiplication ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; return checkNumExp(MULTIPLY, ast, left, right, context); } public Object visit(Division ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; return checkNumExp(DIVIDE, ast, left, right, context); } public Object visit(Modulo ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; return checkNumExp(MOD, ast, left, right, context); } public Object visit(XOR ast, LocalContext context) { return checkBitExp(XOR, ast, context); } public Object visit(Equal ast, LocalContext context) { return checkEqualExp(EQUAL, ast, context); } public Object visit(NotEqual ast, LocalContext context) { return checkEqualExp(NOT_EQUAL, ast, context); } public Object visit(ReferenceEqual ast, LocalContext context) { return checkRefEqualsExp(EQUAL, ast, context); } public Object visit(ReferenceNotEqual ast, LocalContext context) { return checkRefEqualsExp(NOT_EQUAL, ast, context); } public Object visit(LessOrEqual ast, LocalContext context) { IxCode.Expression[] ops = processComparableExpression(ast, context); if(ops == null){ return null; } return new IxCode.BinaryExpression(LESS_OR_EQUAL, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(LessThan ast, LocalContext context) { IxCode.Expression[] ops = processComparableExpression(ast, context); if(ops == null) return null; return new IxCode.BinaryExpression( LESS_THAN, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(GreaterOrEqual ast, LocalContext context) { IxCode.Expression[] ops = processComparableExpression(ast, context); if(ops == null) return null; return new IxCode.BinaryExpression( GREATER_OR_EQUAL, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(GreaterThan ast, LocalContext context) { IxCode.Expression[] ops = processComparableExpression(ast, context); if(ops == null) return null; return new IxCode.BinaryExpression( GREATER_THAN, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(LogicalAnd ast, LocalContext context) { IxCode.Expression[] ops = processLogicalExpression(ast, context); if(ops == null) return null; return new IxCode.BinaryExpression( LOGICAL_AND, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(LogicalOr ast, LocalContext context) { IxCode.Expression[] ops = processLogicalExpression(ast, context); if(ops == null) return null; return new IxCode.BinaryExpression( LOGICAL_OR, IxCode.BasicTypeRef.BOOLEAN, ops[0], ops[1]); } public Object visit(LogicalRightShift ast, LocalContext context) { return processShiftExpression(BIT_SHIFT_R3, ast, context); } public Object visit(MathLeftShift ast, LocalContext context) { return processShiftExpression(BIT_SHIFT_L2, ast, context); } public Object visit(MathRightShift ast, LocalContext context) { return processShiftExpression(BIT_SHIFT_R2, ast, context); } public Object visit(BitAnd ast, LocalContext context) { return checkBitExp(BIT_AND, ast, context); } public Object visit(BitOr expression, LocalContext context) { return checkBitExp(BIT_AND, expression, context); } IxCode.Expression[] processLogicalExpression(onion.lang.syntax.BinaryExpression ast, LocalContext context){ IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; IxCode.TypeRef leftType = left.type(), rightType = right.type(); if((leftType != IxCode.BasicTypeRef.BOOLEAN) || (rightType != IxCode.BasicTypeRef.BOOLEAN)){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } return new IxCode.Expression[]{left, right}; } IxCode.Expression processShiftExpression( int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){ IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; if(!left.type().isBasicType()){ IxCode.Expression[] params = new IxCode.Expression[]{right}; Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)left.type(), "add", params); if(result._2 == null){ report(METHOD_NOT_FOUND, ast, left.type(), "add", types(params)); return null; } return new IxCode.Call(left, result._2, params); } if(!right.type().isBasicType()){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } IxCode.BasicTypeRef leftType = (IxCode.BasicTypeRef)left.type(); IxCode.BasicTypeRef rightType = (IxCode.BasicTypeRef)right.type(); if((!leftType.isInteger()) || (!rightType.isInteger())){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } IxCode.TypeRef leftResultType = promoteInteger(leftType); if(leftResultType != leftType){ left = new IxCode.AsInstanceOf(left, leftResultType); } if(rightType != IxCode.BasicTypeRef.INT){ right = new IxCode.AsInstanceOf(right, IxCode.BasicTypeRef.INT); } return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right); } IxCode.TypeRef promoteInteger(IxCode.TypeRef type){ if(type == IxCode.BasicTypeRef.BYTE || type == IxCode.BasicTypeRef.SHORT || type == IxCode.BasicTypeRef.CHAR || type == IxCode.BasicTypeRef.INT){ return IxCode.BasicTypeRef.INT; } if(type == IxCode.BasicTypeRef.LONG){ return IxCode.BasicTypeRef.LONG; } return null; } IxCode.Expression checkBitExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){ IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; if((!left.isBasicType()) || (!right.isBasicType())){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } IxCode.BasicTypeRef leftType = (IxCode.BasicTypeRef)left.type(); IxCode.BasicTypeRef rightType = (IxCode.BasicTypeRef)right.type(); IxCode.TypeRef resultType = null; if(leftType.isInteger() && rightType.isInteger()){ resultType = promote(leftType, rightType); }else if(leftType.isBoolean() && rightType.isBoolean()){ resultType = IxCode.BasicTypeRef.BOOLEAN; }else{ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}); return null; } if(left.type() != resultType){ left = new IxCode.AsInstanceOf(left, resultType); } if(right.type() != resultType){ right = new IxCode.AsInstanceOf(right, resultType); } return new IxCode.BinaryExpression(kind, resultType, left, right); } IxCode.Expression checkNumExp(int kind, onion.lang.syntax.BinaryExpression ast, IxCode.Expression left, IxCode.Expression right, LocalContext context) { if((!hasNumericType(left)) || (!hasNumericType(right))){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } IxCode.TypeRef resultType = promote(left.type(), right.type()); if(left.type() != resultType){ left = new IxCode.AsInstanceOf(left, resultType); } if(right.type() != resultType){ right = new IxCode.AsInstanceOf(right, resultType); } return new IxCode.BinaryExpression(kind, resultType, left, right); } IxCode.Expression checkRefEqualsExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){ IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; IxCode.TypeRef leftType = left.type(); IxCode.TypeRef rightType = right.type(); if( (left.isBasicType() && (!right.isBasicType())) || ((!left.isBasicType()) && (right.isBasicType()))){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}); return null; } if(left.isBasicType() && right.isBasicType()){ if(hasNumericType(left) && hasNumericType(right)){ IxCode.TypeRef resultType = promote(leftType, rightType); if(resultType != left.type()){ left = new IxCode.AsInstanceOf(left, resultType); } if(resultType != right.type()){ right = new IxCode.AsInstanceOf(right, resultType); } }else if(leftType != IxCode.BasicTypeRef.BOOLEAN || rightType != IxCode.BasicTypeRef.BOOLEAN){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}); return null; } } return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right); } IxCode.Expression checkEqualExp(int kind, onion.lang.syntax.BinaryExpression ast, LocalContext context){ IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; IxCode.TypeRef leftType = left.type(), rightType = right.type(); if((left.isBasicType() && (!right.isBasicType())) || ((!left.isBasicType()) && (right.isBasicType()))){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}); return null; } if(left.isBasicType() && right.isBasicType()){ if(hasNumericType(left) && hasNumericType(right)){ IxCode.TypeRef resultType = promote(leftType, rightType); if(resultType != left.type()){ left = new IxCode.AsInstanceOf(left, resultType); } if(resultType != right.type()){ right = new IxCode.AsInstanceOf(right, resultType); } }else if(leftType != IxCode.BasicTypeRef.BOOLEAN || rightType != IxCode.BasicTypeRef.BOOLEAN){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{leftType, rightType}); return null; } }else if(left.isReferenceType() && right.isReferenceType()){ return createEquals(kind, left, right); } return new IxCode.BinaryExpression(kind, IxCode.BasicTypeRef.BOOLEAN, left, right); } IxCode.Expression createEquals(int kind, IxCode.Expression left, IxCode.Expression right){ right = new IxCode.AsInstanceOf(right, rootClass()); IxCode.Expression[] params = {right}; IxCode.ObjectTypeRef target = (IxCode.ObjectTypeRef) left.type(); IxCode.MethodRef[] methods = target.findMethod("equals", params); IxCode.Expression node = new IxCode.Call(left, methods[0], params); if(kind == IxCode.BinaryExpression.Constants.NOT_EQUAL){ node = new IxCode.UnaryExpression(NOT, IxCode.BasicTypeRef.BOOLEAN, node); } return node; } IxCode.Expression[] processComparableExpression(onion.lang.syntax.BinaryExpression ast, LocalContext context) { IxCode.Expression left = typeCheck(ast.getLeft(), context); IxCode.Expression right = typeCheck(ast.getRight(), context); if(left == null || right == null) return null; IxCode.TypeRef leftType = left.type(), rightType = right.type(); if((!numeric(left.type())) || (!numeric(right.type()))){ report(INCOMPATIBLE_OPERAND_TYPE, ast, ast.getSymbol(), new IxCode.TypeRef[]{left.type(), right.type()}); return null; } IxCode.TypeRef resultType = promote(leftType, rightType); if(leftType != resultType){ left = new IxCode.AsInstanceOf(left, resultType); } if(rightType != resultType){ right = new IxCode.AsInstanceOf(right, resultType); } return new IxCode.Expression[]{left, right}; } public Object visit(onion.lang.syntax.FloatLiteral ast, LocalContext context) { return new IxCode.FloatLiteral(ast.getValue()); } public Object visit(SuperMethodCall ast, LocalContext context) { IxCode.Expression[] params; params = typeCheckExps(ast.getParams(), context); if(params == null) return null; IxCode.ClassTypeRef contextClass = CodeAnalysis.this.contextClass; Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, contextClass.getSuperClass(), ast.getName(), params); if(result._2 == null){ if(result._1) report(METHOD_NOT_FOUND, ast, contextClass, ast.getName(), types(params)); return null; } return new IxCode.CallSuper(new IxCode.This(contextClass), result._2, params); } public Object visit(onion.lang.syntax.DoubleLiteral ast, LocalContext context) { return new IxCode.DoubleLiteral(ast.getValue()); } public Object visit(IntegerLiteral node, LocalContext context) { return new IxCode.IntLiteral(node.getValue()); } public Object visit(onion.lang.syntax.CharacterLiteral node, LocalContext context) { return new IxCode.CharacterLiteral(node.getValue()); } public Object visit(onion.lang.syntax.LongLiteral ast, LocalContext context) { return new IxCode.LongLiteral(ast.getValue()); } public Object visit(BooleanLiteral ast, LocalContext context) { return new IxCode.BoolLiteral(ast.getValue()); } public Object visit(onion.lang.syntax.ListLiteral ast, LocalContext context) { IxCode.Expression[] elements = new IxCode.Expression[ast.size()]; for(int i = 0; i < ast.size(); i++){ elements[i] = typeCheck(ast.getExpression(i), context); } IxCode.ListLiteral node = new IxCode.ListLiteral(elements, load("java.util.List")); return node; } public Object visit(onion.lang.syntax.StringLiteral ast, LocalContext context) { return new IxCode.StringLiteral(ast.getValue(), load("java.lang.String")); } public Object visit(onion.lang.syntax.NullLiteral ast, LocalContext context) { return new IxCode.NullLiteral(); } public Object visit(Posit ast, LocalContext context) { IxCode.Expression node = typeCheck(ast.getTarget(), context); if(node == null) return null; if(!hasNumericType(node)){ report(INCOMPATIBLE_OPERAND_TYPE, ast, "+", new IxCode.TypeRef[]{node.type()}); return null; } node = new IxCode.UnaryExpression(PLUS, node.type(), node); return node; } public Object visit(Negate ast, LocalContext context) { IxCode.Expression node = typeCheck(ast.getTarget(), context); if(node == null) return null; if(!hasNumericType(node)){ report(INCOMPATIBLE_OPERAND_TYPE, ast, "-", new IxCode.TypeRef[]{node.type()}); return null; } node = new IxCode.UnaryExpression(MINUS, node.type(), node); return node; } public Object visit(Not ast, LocalContext context) { IxCode.Expression node = typeCheck(ast.getTarget(), context); if(node == null) return null; if(node.type() != IxCode.BasicTypeRef.BOOLEAN){ report(INCOMPATIBLE_OPERAND_TYPE, ast, "!", new IxCode.TypeRef[]{node.type()}); return null; } node = new IxCode.UnaryExpression(NOT, IxCode.BasicTypeRef.BOOLEAN, node); return node; } public Object visit(Assignment ast, LocalContext context) { onion.lang.syntax.Expression left = ast.getLeft(); if(left instanceof Id){ return processLocalAssign(ast, context); }else if(left instanceof SelfFieldReference){ return processSelfFieldAssign(ast, context); }else if(left instanceof Indexing){ return processArrayAssign(ast, context); }else if(left instanceof FieldOrMethodRef){ return processFieldOrMethodAssign(ast, context); } return null; } private IxCode.Expression processLocalAssign(Assignment ast, LocalContext context){ IxCode.Expression value = typeCheck(ast.getRight(), context); if(value == null) return null; Id id = (Id) ast.getLeft(); ClosureLocalBinding bind = context.lookup(id.getName()); int frame, index; IxCode.TypeRef leftType, rightType = value.type(); if(bind != null){ frame = bind.getFrame(); index = bind.getIndex(); leftType = bind.getType(); }else{ frame = 0; if(rightType.isNullType()){ leftType = rootClass(); }else{ leftType = rightType; } index = context.add(id.getName(), leftType); } value = processAssignable(ast.getRight(), leftType, value); if(value == null) return null; return new IxCode.SetLocal(frame, index, leftType, value); } private Object processSelfFieldAssign(Assignment ast, LocalContext context){ IxCode.Expression value = typeCheck(ast.getRight(), context); if(value == null) return null; SelfFieldReference ref = (SelfFieldReference) ast.getLeft(); IxCode.ClassTypeRef selfClass; if(context.isGlobal()){ selfClass = loadTopClass(); }else { if(context.method() != null){ selfClass = context.method().affiliation(); }else{ selfClass = context.constructor().affiliation(); } } IxCode.FieldRef field = findField(selfClass, ref.getName()); if(field == null){ report(FIELD_NOT_FOUND, ref, selfClass, ref.getName()); return null; } if(!isAccessible(field, selfClass)){ report(FIELD_NOT_ACCESSIBLE, ast, field.affiliation(), field.name(), selfClass); return null; } value = processAssignable(ast.getRight(), field.getType(), value); if(value == null) return null; return new IxCode.SetField(new IxCode.This(selfClass), field, value); } Object processArrayAssign(Assignment ast, LocalContext context){ IxCode.Expression value = typeCheck(ast.getRight(), context); Indexing indexing = (Indexing) ast.getLeft(); IxCode.Expression target = typeCheck(indexing.getLeft(), context); IxCode.Expression index = typeCheck(indexing.getRight(), context); if(value == null || target == null || index == null) return null; if(target.isBasicType()){ report(INCOMPATIBLE_TYPE, indexing.getLeft(), rootClass(), target.type()); return null; } if(target.isArrayType()){ IxCode.ArrayTypeRef targetType = ((IxCode.ArrayTypeRef)target.type()); if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){ report(INCOMPATIBLE_TYPE, indexing.getRight(), IxCode.BasicTypeRef.INT, index.type()); return null; } IxCode.TypeRef base = targetType.getBase(); value = processAssignable(ast.getRight(), base, value); if(value == null) return null; return new IxCode.ArraySet(target, index, value); } IxCode.Expression[] params; params = new IxCode.Expression[]{index, value}; Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)target.type(), "set", new IxCode.Expression[]{index, value}); if(result._2 == null){ report(METHOD_NOT_FOUND, ast, target.type(), "set", types(params)); return null; } return new IxCode.Call(target, result._2, params); } Object processFieldOrMethodAssign(Assignment ast, LocalContext context){ IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(AdditionAssignment ast, LocalContext context) { IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(SubtractionAssignment ast, LocalContext context) { IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(MultiplicationAssignment ast, LocalContext context) { IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(DivisionAssignment ast, LocalContext context) { IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(ModuloAssignment ast, LocalContext context) { IxCode.Expression right = typeCheck(ast.getRight(), context); report(UNIMPLEMENTED_FEATURE, ast); return null; } public Object visit(Id ast, LocalContext context) { ClosureLocalBinding bind = context.lookup(ast.getName()); if(bind == null){ report(VARIABLE_NOT_FOUND, ast, ast.getName()); return null; } return new IxCode.RefLocal(bind); } IxCode.MethodRef findMethod(AstNode ast, IxCode.ObjectTypeRef type, String name) { return findMethod(ast, type, name, new IxCode.Expression[0]); } IxCode.MethodRef findMethod(AstNode ast, IxCode.ObjectTypeRef type, String name, IxCode.Expression[] params) { IxCode.MethodRef[] methods = type.findMethod(name, params); if(methods.length == 0){ report(METHOD_NOT_FOUND, ast, type, name, types(params)); return null; } return methods[0]; } public Object visit(CurrentInstance ast, LocalContext context) { if(context.isStatic()) { return null; }else { return new IxCode.This(contextClass); } } boolean hasSamePackage(IxCode.ClassTypeRef a, IxCode.ClassTypeRef b) { String name1 = a.name(); String name2 = b.name(); int index; index = name1.lastIndexOf("."); if(index >= 0){ name1 = name1.substring(0, index); }else{ name1 = ""; } index = name2.lastIndexOf("."); if(index >= 0){ name2 = name2.substring(0, index); }else{ name2 = ""; } return name1.equals(name2); } boolean isAccessible(IxCode.ClassTypeRef target, IxCode.ClassTypeRef context) { if(hasSamePackage(target, context)){ return true; }else{ if(Modifier.isInternal(target.modifier())){ return false; }else{ return true; } } } boolean isAccessible(IxCode.MemberRef member, IxCode.ClassTypeRef context) { IxCode.ClassTypeRef targetType = member.affiliation(); if(targetType == context) return true; int modifier = member.modifier(); if(IxCode.TypeRules.isSuperType(targetType, context)){ if(Modifier.isProtected(modifier) || Modifier.isPublic(modifier)){ return true; }else{ return false; } }else{ if(Modifier.isPublic(modifier)){ return true; }else{ return false; } } } private IxCode.FieldRef findField(IxCode.ObjectTypeRef target, String name) { if(target == null) return null; IxCode.FieldRef[] fields = target.fields(); for (int i = 0; i < fields.length; i++) { if(fields[i].name().equals(name)){ return fields[i]; } } IxCode.FieldRef field = findField(target.getSuperClass(), name); if(field != null) return field; IxCode.ClassTypeRef[] interfaces = target.getInterfaces(); for(int i = 0; i < interfaces.length; i++){ field = findField(interfaces[i], name); if(field != null) return field; } return null; } private boolean isAccessible( AstNode ast, IxCode.ObjectTypeRef target, IxCode.ClassTypeRef context ) { if(target.isArrayType()){ IxCode.TypeRef component = ((IxCode.ArrayTypeRef)target).getComponent(); if(!component.isBasicType()){ if(!isAccessible((IxCode.ClassTypeRef)component, contextClass)){ report(CLASS_NOT_ACCESSIBLE, ast, target, context); return false; } } }else{ if(!isAccessible((IxCode.ClassTypeRef)target, context)){ report(CLASS_NOT_ACCESSIBLE, ast, target, context); return false; } } return true; } public Object visit(FieldOrMethodRef ast, LocalContext context) { IxCode.ClassDefinition contextClass = CodeAnalysis.this.contextClass; IxCode.Expression target = typeCheck(ast.getTarget(), context); if(target == null) return null; if(target.type().isBasicType() || target.type().isNullType()){ report(INCOMPATIBLE_TYPE, ast.getTarget(), rootClass(), target.type()); return null; } IxCode.ObjectTypeRef targetType = (IxCode.ObjectTypeRef) target.type(); if(!isAccessible(ast, targetType, contextClass)) return null; String name = ast.getName(); if(target.type().isArrayType()){ if(name.equals("length") || name.equals("size")){ return new IxCode.ArrayLength(target); }else{ return null; } } IxCode.FieldRef field = findField(targetType, name); if(field != null && isAccessible(field, CodeAnalysis.this.contextClass)){ return new IxCode.RefField(target, field); } Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, targetType, name, new IxCode.Expression[0]); if(result._2 != null){ return new IxCode.Call(target, result._2, new IxCode.Expression[0]); } boolean continuable = result._1; if(!continuable) return null; String getterName; getterName = getter(name); result = tryFindMethod(ast, targetType, getterName, new IxCode.Expression[0]); if(result._2 != null){ return new IxCode.Call(target, result._2, new IxCode.Expression[0]); } continuable = result._1; if(!continuable) return null; getterName = getterBoolean(name); result = tryFindMethod(ast, targetType, getterName, new IxCode.Expression[0]); if(result._2 != null){ return new IxCode.Call(target, result._2, new IxCode.Expression[0]); } if(field == null){ report(FIELD_NOT_FOUND, ast, targetType, ast.getName()); }else{ report(FIELD_NOT_ACCESSIBLE, ast, targetType, ast.getName(), CodeAnalysis.this.contextClass); } return null; } private Pair<Boolean, IxCode.MethodRef> tryFindMethod( AstNode ast, IxCode.ObjectTypeRef target, String name, IxCode.Expression[] params ) { IxCode.MethodRef[] methods; methods = target.findMethod(name, params); if(methods.length > 0){ if(methods.length > 1){ report(AMBIGUOUS_METHOD, ast, new Object[]{methods[0].affiliation(), name, methods[0].arguments()}, new Object[]{methods[1].affiliation(), name, methods[1].arguments()}); return Pair.make(false, null); } if(!isAccessible(methods[0], contextClass)){ report(METHOD_NOT_ACCESSIBLE, ast, methods[0].affiliation(), name, methods[0].arguments(), contextClass); return Pair.make(false, null); } return Pair.make(false, methods[0]); } return Pair.make(true, null); } private String getter(String name) { return "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1); } private String getterBoolean(String name) { return "is" + Character.toUpperCase(name.charAt(0)) + name.substring(1); } private String setter(String name) { return "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); } public Object visit(Argument ast, LocalContext context) { String name = ast.getName(); ClosureLocalBinding binding = context.lookupOnlyCurrentScope(name); if(binding != null){ report(DUPLICATE_LOCAL_VARIABLE, ast, name); return null; } IxCode.TypeRef type = resolve(ast.getType(), solver); if(type == null) return null; context.add(name, type); return type; } public Object visit(onion.lang.syntax.NewArray ast, LocalContext context) { IxCode.TypeRef type = resolve(ast.getType(), solver); IxCode.Expression[] parameters = typeCheckExps(ast.getArguments(), context); if(type == null || parameters == null) return null; IxCode.ArrayTypeRef resultType = loadArray(type, parameters.length); return new IxCode.NewArray(resultType, parameters); } public Object visit(Cast ast, LocalContext context) { IxCode.Expression node = typeCheck(ast.getTarget(), context); if(node == null) return null; IxCode.TypeRef conversion = resolve(ast.getType(), solver); if(conversion == null) return null; node = new IxCode.AsInstanceOf(node, conversion); return node; } public boolean equals(IxCode.TypeRef[] types1, IxCode.TypeRef[] types2) { if(types1.length != types2.length) return false; for(int i = 0; i < types1.length; i++){ if(types1[i] != types2[i]) return false; } return true; } public Object visit(ClosureExpression ast, LocalContext context) { IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType()); Argument[] args = ast.getArguments(); IxCode.TypeRef[] argTypes = new IxCode.TypeRef[args.length]; String name = ast.getName(); try { context.openFrame(); boolean error = false; for(int i = 0; i < args.length; i++){ argTypes[i] = (IxCode.TypeRef)accept(args[i], context); if(argTypes[i] == null){ error = true; } } if(type == null) return null; if(!type.isInterface()){ report(INTERFACE_REQUIRED, ast.getType(), type); return null; } if(error) return null; IxCode.MethodRef[] methods = type.methods(); IxCode.MethodRef method = matches(argTypes, name, methods); if(method == null){ report(METHOD_NOT_FOUND, ast, type, name, argTypes); return null; } context.setMethod(method); context.getContextFrame().parent().setAllClosed(true); IxCode.ActionStatement block = translate(ast.getBlock(), context); block = addReturnNode(block, method.returnType()); IxCode.NewClosure node = new IxCode.NewClosure(type, method, block); node.setFrame(context.getContextFrame()); return node; }finally{ context.closeFrame(); } } private IxCode.MethodRef matches(IxCode.TypeRef[] argTypes, String name, IxCode.MethodRef[] methods) { for(int i = 0; i < methods.length; i++){ IxCode.TypeRef[] types = methods[i].arguments(); if(name.equals(methods[i].name()) && equals(argTypes, types)){ return methods[i]; } } return null; } public Object visit(Indexing ast, LocalContext context) { IxCode.Expression target = typeCheck(ast.getLeft(), context); IxCode.Expression index = typeCheck(ast.getRight(), context); if(target == null || index == null) return null; if(target.isArrayType()){ if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){ report(INCOMPATIBLE_TYPE, ast, IxCode.BasicTypeRef.INT, index.type()); return null; } return new IxCode.ArrayRef(target, index); } if(target.isBasicType()){ report(INCOMPATIBLE_TYPE, ast.getLeft(), rootClass(), target.type()); return null; } if(target.isArrayType()){ if(!(index.isBasicType() && ((IxCode.BasicTypeRef)index.type()).isInteger())){ report(INCOMPATIBLE_TYPE, ast.getRight(), IxCode.BasicTypeRef.INT, index.type()); return null; } return new IxCode.ArrayRef(target, index); } IxCode.Expression[] params = {index}; Pair<Boolean, IxCode.MethodRef> result = tryFindMethod(ast, (IxCode.ObjectTypeRef)target.type(), "get", new IxCode.Expression[]{index}); if(result._2 == null){ report(METHOD_NOT_FOUND, ast, target.type(), "get", types(params)); return null; } return new IxCode.Call(target, result._2, params); } public Object visit(SelfFieldReference ast, LocalContext context) { IxCode.ClassTypeRef selfClass = null; if(context.isStatic()) return null; selfClass = contextClass; IxCode.FieldRef field = findField(selfClass, ast.getName()); if(field == null){ report(FIELD_NOT_FOUND, ast, selfClass, ast.getName()); return null; } if(!isAccessible(field, selfClass)){ report(FIELD_NOT_ACCESSIBLE, ast, field.affiliation(), ast.getName(), selfClass); return null; } return new IxCode.RefField(new IxCode.This(selfClass), field); } public Object visit(onion.lang.syntax.NewObject ast, LocalContext context) { IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType()); IxCode.Expression[] parameters = typeCheckExps(ast.getArguments(), context); if(parameters == null || type == null) return null; IxCode.ConstructorRef[] constructors = type.findConstructor(parameters); if(constructors.length == 0){ report(CONSTRUCTOR_NOT_FOUND, ast, type, types(parameters)); return null; } if(constructors.length > 1){ report(AMBIGUOUS_CONSTRUCTOR, ast, new Object[]{constructors[0].affiliation(), constructors[0].getArgs()}, new Object[]{constructors[1].affiliation(), constructors[1].getArgs()}); return null; } return new IxCode.NewObject(constructors[0], parameters); } public Object visit(IsInstance ast, LocalContext context) { IxCode.Expression target = typeCheck(ast.getTarget(), context); IxCode.TypeRef checkType = resolve(ast.getType(), solver); if(target == null || checkType == null) return null; return new IxCode.InstanceOf(target, checkType); } private IxCode.TypeRef[] types(IxCode.Expression[] parameters){ IxCode.TypeRef[] types = new IxCode.TypeRef[parameters.length]; for(int i = 0; i < types.length; i++){ types[i] = parameters[i].type(); } return types; } public Object visit(SelfMethodCall ast, LocalContext context) { IxCode.Expression[] params = typeCheckExps(ast.getArguments(), context); if(params == null) return null; IxCode.ClassDefinition targetType = contextClass; IxCode.MethodRef[] methods = targetType.findMethod(ast.getName(), params); if(methods.length == 0){ report(METHOD_NOT_FOUND, ast, targetType, ast.getName(), types(params)); return null; }else if(methods.length > 1){ report(AMBIGUOUS_METHOD, ast, new Object[]{methods[0].affiliation(), ast.getName(), methods[0].arguments()}, new Object[]{methods[1].affiliation(), ast.getName(), methods[1].arguments()}); return null; }else { params = doCastInsertion(methods[0].arguments(), params); if((methods[0].modifier() & Modifier.STATIC) != 0){ return new IxCode.CallStatic(targetType, methods[0], params); }else { return new IxCode.Call(new IxCode.This(targetType), methods[0], params); } } } private IxCode.Expression[] doCastInsertion(IxCode.TypeRef[] arguments, IxCode.Expression[] params){ for(int i = 0; i < params.length; i++){ if(arguments[i] != params[i].type()){ params[i] = new IxCode.AsInstanceOf(params[i], arguments[i]); } } return params; } public Object visit(MethodCall ast, LocalContext context) { IxCode.Expression target = typeCheck(ast.getTarget(), context); if(target == null) return null; IxCode.Expression[] params = typeCheckExps(ast.getArguments(), context); if(params == null) return null; IxCode.ObjectTypeRef targetType = (IxCode.ObjectTypeRef) target.type(); final String name = ast.getName(); IxCode.MethodRef[] methods = targetType.findMethod(name, params); if(methods.length == 0){ report(METHOD_NOT_FOUND, ast, targetType, name, types(params)); return null; }else if(methods.length > 1){ report(AMBIGUOUS_METHOD, ast, new Object[]{methods[0].affiliation(), name, methods[0].arguments()}, new Object[]{methods[1].affiliation(), name, methods[1].arguments()}); return null; }else if((methods[0].modifier() & Modifier.STATIC) != 0){ report(ILLEGAL_METHOD_CALL, ast, methods[0].affiliation(), name, methods[0].arguments()); return null; }else { return new IxCode.Call(target, methods[0], doCastInsertion(methods[0].arguments(), params)); } } public Object visit(StaticIDExpression ast, LocalContext context) { IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getType()); if(type == null) return null; IxCode.FieldRef field = findField(type, ast.getName()); if(field == null){ report(FIELD_NOT_FOUND, ast, type, ast.getName()); return null; } return new IxCode.StaticFieldRef(type, field); } public Object visit(StaticMethodCall ast, LocalContext context) { IxCode.ClassTypeRef type = (IxCode.ClassTypeRef) CodeAnalysis.this.resolve(ast.getTarget()); IxCode.Expression[] params = typeCheckExps(ast.getArgs(), context); if(type == null || params == null) { return null; }else { IxCode.MethodRef[] methods = type.findMethod(ast.getName(), params); if(methods.length == 0){ report(METHOD_NOT_FOUND, ast, type, ast.getName(), types(params)); return null; }else if(methods.length > 1){ report(AMBIGUOUS_METHOD, ast, ast.getName(), typeNames(methods[0].arguments()), typeNames(methods[1].arguments())); return null; }else { return new IxCode.CallStatic(type, methods[0], doCastInsertion(methods[0].arguments(), params)); } } } private String[] typeNames(IxCode.TypeRef[] types) { String[] names = new String[types.length]; for(int i = 0; i < names.length; i++){ names[i] = types[i].name(); } return names; } private IxCode.Expression[] typeCheckExps(onion.lang.syntax.Expression[] ast, LocalContext context){ IxCode.Expression[] expressions = new IxCode.Expression[ast.length]; boolean success = true; for(int i = 0; i < ast.length; i++){ expressions[i] = typeCheck(ast[i], context); if(expressions[i] == null){ success = false; } } if(success){ return expressions; }else{ return null; } } public Object visit(ForeachStatement ast, LocalContext context) { onion.lang.syntax.Expression collectionAST = ast.getCollection(); try { context.openScope(); IxCode.Expression collection = typeCheck(collectionAST, context); Argument arg = ast.getDeclaration(); accept(arg, context); IxCode.ActionStatement block = translate(ast.getStatement(), context); if(collection.isBasicType()){ report(INCOMPATIBLE_TYPE, collectionAST, load("java.util.Collection"), collection.type()); return null; } ClosureLocalBinding elementVar = context.lookupOnlyCurrentScope(arg.getName()); ClosureLocalBinding collectionVar = new ClosureLocalBinding(0, context.add(context.newName(), collection.type()), collection.type()); IxCode.ActionStatement init; if(collection.isArrayType()){ ClosureLocalBinding counterVariable = new ClosureLocalBinding(0, context.add(context.newName(), IxCode.BasicTypeRef.INT), IxCode.BasicTypeRef.INT); init = new IxCode.StatementBlock( new IxCode.ExpressionStatement(new IxCode.SetLocal(collectionVar, collection)), new IxCode.ExpressionStatement(new IxCode.SetLocal(counterVariable, new IxCode.IntLiteral(0))) ); block = new IxCode.ConditionalLoop( new IxCode.BinaryExpression( LESS_THAN, IxCode.BasicTypeRef.BOOLEAN, ref(counterVariable), new IxCode.ArrayLength(ref(collectionVar)) ), new IxCode.StatementBlock( assign(elementVar, indexref(collectionVar, ref(counterVariable))), block, assign(counterVariable, new IxCode.BinaryExpression(ADD, IxCode.BasicTypeRef.INT, ref(counterVariable), new IxCode.IntLiteral(1))) ) ); return new IxCode.StatementBlock(init, block); }else{ IxCode.ObjectTypeRef iteratorType = load("java.util.Iterator"); ClosureLocalBinding iteratorVar = new ClosureLocalBinding(0, context.add(context.newName(), iteratorType), iteratorType); IxCode.MethodRef mIterator = findMethod(collectionAST, (IxCode.ObjectTypeRef) collection.type(), "iterator"); IxCode.MethodRef mNext = findMethod(ast.getCollection(), iteratorType, "next"); IxCode.MethodRef mHasNext = findMethod(ast.getCollection(), iteratorType, "hasNext"); init = new IxCode.StatementBlock( new IxCode.ExpressionStatement(new IxCode.SetLocal(collectionVar, collection)), assign(iteratorVar, new IxCode.Call(ref(collectionVar), mIterator, new IxCode.Expression[0])) ); IxCode.Expression next = new IxCode.Call(ref(iteratorVar), mNext, new IxCode.Expression[0]); if(elementVar.getType() != rootClass()){ next = new IxCode.AsInstanceOf(next, elementVar.getType()); } block = new IxCode.ConditionalLoop( new IxCode.Call(ref(iteratorVar), mHasNext, new IxCode.Expression[0]), new IxCode.StatementBlock(assign(elementVar, next), block) ); return new IxCode.StatementBlock(init, block); } }finally{ context.closeScope(); } } private IxCode.Expression indexref(ClosureLocalBinding bind, IxCode.Expression value) { return new IxCode.ArrayRef(new IxCode.RefLocal(bind), value); } private IxCode.ActionStatement assign(ClosureLocalBinding bind, IxCode.Expression value) { return new IxCode.ExpressionStatement(new IxCode.SetLocal(bind, value)); } private IxCode.Expression ref(ClosureLocalBinding bind) { return new IxCode.RefLocal(bind); } public Object visit(onion.lang.syntax.ExpressionStatement ast, LocalContext context) { IxCode.Expression expression = typeCheck(ast.getExpression(), context); return new IxCode.ExpressionStatement(expression); } public Object visit(CondStatement node, LocalContext context) { try { context.openScope(); int size = node.size(); Stack exprs = new Stack(); Stack stmts = new Stack(); for(int i = 0; i < size; i++){ onion.lang.syntax.Expression expr = node.getCondition(i); Statement stmt = node.getBlock(i); IxCode.Expression texpr = typeCheck(expr, context); if(texpr != null && texpr.type() != IxCode.BasicTypeRef.BOOLEAN){ IxCode.TypeRef expect = IxCode.BasicTypeRef.BOOLEAN; IxCode.TypeRef actual = texpr.type(); report(INCOMPATIBLE_TYPE, expr, expect, actual); } exprs.push(texpr); IxCode.ActionStatement tstmt = translate(stmt, context); stmts.push(tstmt); } Statement elseStmt = node.getElseBlock(); IxCode.ActionStatement result = null; if(elseStmt != null){ result = translate(elseStmt, context); } for(int i = 0; i < size; i++){ IxCode.Expression expr = (IxCode.Expression)exprs.pop(); IxCode.ActionStatement stmt = (IxCode.ActionStatement)stmts.pop(); result = new IxCode.IfStatement(expr, stmt, result); } return result; }finally{ context.closeScope(); } } public Object visit(ForStatement ast, LocalContext context) { try{ context.openScope(); IxCode.ActionStatement init = null; if(ast.getInit() != null){ init = translate(ast.getInit(), context); }else{ init = new IxCode.NOP(); } IxCode.Expression condition; onion.lang.syntax.Expression astCondition = ast.getCondition(); if(astCondition != null){ condition = typeCheck(ast.getCondition(), context); IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN; if(condition != null && condition.type() != expected){ IxCode.TypeRef appeared = condition.type(); report(INCOMPATIBLE_TYPE, astCondition, expected, appeared); } }else{ condition = new IxCode.BoolLiteral(true); } IxCode.Expression update = null; if(ast.getUpdate() != null){ update = typeCheck(ast.getUpdate(), context); } IxCode.ActionStatement loop = translate( ast.getBlock(), context); if(update != null){ loop = new IxCode.StatementBlock(loop, new IxCode.ExpressionStatement(update)); } IxCode.ActionStatement result = new IxCode.ConditionalLoop(condition, loop); result = new IxCode.StatementBlock(init, result); return result; }finally{ context.closeScope(); } } public Object visit(BlockStatement ast, LocalContext context) { Statement[] astStatements = ast.getStatements(); IxCode.ActionStatement[] statements = new IxCode.ActionStatement[astStatements.length]; try{ context.openScope(); for(int i = 0; i < astStatements.length; i++){ statements[i] = translate(astStatements[i], context); } return new IxCode.StatementBlock(statements); }finally{ context.closeScope(); } } public Object visit(onion.lang.syntax.IfStatement ast, LocalContext context) { try{ context.openScope(); IxCode.Expression condition = typeCheck(ast.getCondition(), context); IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN; if(condition != null && condition.type() != expected){ report(INCOMPATIBLE_TYPE, ast.getCondition(), expected, condition.type()); } IxCode.ActionStatement thenBlock = translate(ast.getThenBlock(), context); IxCode.ActionStatement elseBlock = ast.getElseBlock() == null ? null : translate(ast.getElseBlock(), context); return new IxCode.IfStatement(condition, thenBlock, elseBlock); }finally{ context.closeScope(); } } public Object visit(WhileStatement ast, LocalContext context) { try{ context.openScope(); IxCode.Expression condition = typeCheck(ast.getCondition(), context); IxCode.TypeRef expected = IxCode.BasicTypeRef.BOOLEAN; if(condition != null && condition.type() != expected){ IxCode.TypeRef actual = condition.type(); report(INCOMPATIBLE_TYPE, ast, expected, actual); } IxCode.ActionStatement thenBlock = translate(ast.getBlock(), context); return new IxCode.ConditionalLoop(condition, thenBlock); }finally{ context.closeScope(); } } public Object visit(ReturnStatement ast, LocalContext context) { IxCode.TypeRef returnType = ((LocalContext)context).returnType(); if(ast.getExpression() == null){ IxCode.TypeRef expected = IxCode.BasicTypeRef.VOID; if(returnType != expected){ report(CANNOT_RETURN_VALUE, ast); } return new IxCode.Return(null); }else{ IxCode.Expression returned = typeCheck(ast.getExpression(), context); if(returned == null) return new IxCode.Return(null); if(returned.type() == IxCode.BasicTypeRef.VOID){ report(CANNOT_RETURN_VALUE, ast); }else { returned = processAssignable(ast.getExpression(), returnType, returned); if(returned == null) return new IxCode.Return(null); } return new IxCode.Return(returned); } } IxCode.Expression processAssignable(AstNode ast, IxCode.TypeRef a, IxCode.Expression b){ if(b == null) return null; if(a == b.type()) return b; if(!IxCode.TypeRules.isAssignable(a, b.type())){ report(INCOMPATIBLE_TYPE, ast, a, b.type()); return null; } b = new IxCode.AsInstanceOf(b, a); return b; } public Object visit(SelectStatement ast, LocalContext context) { try{ context.openScope(); IxCode.Expression condition = typeCheck(ast.getCondition(), context); if(condition == null){ return new IxCode.NOP(); } String name = context.newName(); int index = context.add(name, condition.type()); IxCode.ActionStatement statement; if(ast.getCases().length == 0){ if(ast.getElseBlock() != null){ statement = translate(ast.getElseBlock(), context); }else{ statement = new IxCode.NOP(); } }else{ statement = processCases(ast, condition, name, context); } IxCode.StatementBlock block = new IxCode.StatementBlock( new IxCode.ExpressionStatement(new IxCode.SetLocal(0, index, condition.type(), condition)), statement ); return block; }finally{ context.closeScope(); } } IxCode.ActionStatement processCases( SelectStatement ast, IxCode.Expression cond, String var, LocalContext context ) { CaseBranch[] cases = ast.getCases(); List nodes = new ArrayList(); List thens = new ArrayList(); for(int i = 0; i < cases.length; i++){ onion.lang.syntax.Expression[] astExpressions = cases[i].getExpressions(); ClosureLocalBinding bind = context.lookup(var); nodes.add(processNodes(astExpressions, cond.type(), bind, context)); thens.add(translate(cases[i].getBlock(), context)); } IxCode.ActionStatement statement; if(ast.getElseBlock() != null){ statement = translate(ast.getElseBlock(), context); }else{ statement = null; } for(int i = cases.length - 1; i >= 0; i IxCode.Expression value = (IxCode.Expression) nodes.get(i); IxCode.ActionStatement then = (IxCode.ActionStatement) thens.get(i); statement = new IxCode.IfStatement(value, then, statement); } return statement; } IxCode.Expression processNodes(Expression[] asts, IxCode.TypeRef type, ClosureLocalBinding bind, LocalContext context) { IxCode.Expression[] nodes = new IxCode.Expression[asts.length]; boolean error = false; for(int i = 0; i < asts.length; i++){ nodes[i] = typeCheck(asts[i], context); if(nodes[i] == null){ error = true; }else if(!IxCode.TypeRules.isAssignable(type, nodes[i].type())){ report(INCOMPATIBLE_TYPE, asts[i], type, nodes[i].type()); error = true; }else { if(nodes[i].isBasicType() && nodes[i].type() != type) nodes[i] = new IxCode.AsInstanceOf(nodes[i], type); if(nodes[i].isReferenceType() && nodes[i].type() != rootClass()) nodes[i] = new IxCode.AsInstanceOf(nodes[i], rootClass()); } } if(!error){ IxCode.Expression node; if(nodes[0].isReferenceType()){ node = createEquals(IxCode.BinaryExpression.Constants.EQUAL, new IxCode.RefLocal(bind), nodes[0]); }else{ node = new IxCode.BinaryExpression(EQUAL, IxCode.BasicTypeRef.BOOLEAN, new IxCode.RefLocal(bind), nodes[0]); } for(int i = 1; i < nodes.length; i++){ node = new IxCode.BinaryExpression( LOGICAL_OR, IxCode.BasicTypeRef.BOOLEAN, node, new IxCode.BinaryExpression(EQUAL, IxCode.BasicTypeRef.BOOLEAN, new IxCode.RefLocal(bind), nodes[i]) ); } return node; }else{ return null; } } public Object visit(ThrowStatement ast, LocalContext context) { IxCode.Expression expression = typeCheck(ast.getExpression(), context); if(expression != null){ IxCode.TypeRef expected = load("java.lang.Throwable"); IxCode.TypeRef detected = expression.type(); if(!IxCode.TypeRules.isSuperType(expected, detected)){ report(INCOMPATIBLE_TYPE, ast.getExpression(), expected, detected); } } return new IxCode.Throw(expression); } public Object visit(LocalVariableDeclaration ast, LocalContext context) { onion.lang.syntax.Expression initializer = ast.getInit(); ClosureLocalBinding binding = context.lookupOnlyCurrentScope(ast.getName()); if(binding != null){ report(DUPLICATE_LOCAL_VARIABLE, ast, ast.getName()); return new IxCode.NOP(); } IxCode.TypeRef leftType = CodeAnalysis.this.resolve(ast.getType()); if(leftType == null) return new IxCode.NOP(); int index = context.add(ast.getName(), leftType); IxCode.SetLocal node; if(initializer != null){ IxCode.Expression valueNode = typeCheck(initializer, context); if(valueNode == null) return new IxCode.NOP(); valueNode = processAssignable(initializer, leftType, valueNode); if(valueNode == null) return new IxCode.NOP(); node = new IxCode.SetLocal(0, index, leftType, valueNode); }else{ node = new IxCode.SetLocal(0, index, leftType, defaultValue(leftType)); } return new IxCode.ExpressionStatement(node); } public IxCode.Expression defaultValue(IxCode.TypeRef type) { return IxCode.Expression.defaultValue(type); } public Object visit(EmptyStatement ast, LocalContext context) { return new IxCode.NOP(); } public Object visit(TryStatement ast, LocalContext context) { IxCode.ActionStatement tryStatement = translate(ast.getTryBlock(), context); ClosureLocalBinding[] binds = new ClosureLocalBinding[ast.getArguments().length]; IxCode.ActionStatement[] catchBlocks = new IxCode.ActionStatement[ast.getArguments().length]; for(int i = 0; i < ast.getArguments().length; i++){ context.openScope(); IxCode.TypeRef arg = (IxCode.TypeRef)accept(ast.getArguments()[i], context); IxCode.TypeRef expected = load("java.lang.Throwable"); if(!IxCode.TypeRules.isSuperType(expected, arg)){ report(INCOMPATIBLE_TYPE, ast.getArguments()[i], expected, arg); } binds[i] = context.lookupOnlyCurrentScope(ast.getArguments()[i].getName()); catchBlocks[i] = translate(ast.getRecBlocks()[i], context); context.closeScope(); } return new IxCode.Try(tryStatement, binds, catchBlocks); } public Object visit(SynchronizedStatement ast, LocalContext context) { IxCode.Expression lock = typeCheck(ast.getTarget(), context); IxCode.ActionStatement block = translate(ast.getBlock(), context); report(UNIMPLEMENTED_FEATURE, ast); return new IxCode.Synchronized(lock, block); } public Object visit(BreakStatement ast, LocalContext context) { report(UNIMPLEMENTED_FEATURE, ast); return new IxCode.Break(); } public Object visit(ContinueStatement ast, LocalContext context) { report(UNIMPLEMENTED_FEATURE, ast); return new IxCode.Continue(); } public Object visit(FunctionDeclaration ast, LocalContext local) { IxCode.MethodDefinition function = (IxCode.MethodDefinition) lookupKernelNode(ast); if(function == null) return null; LocalContext context = new LocalContext(); if(Modifier.isStatic(function.modifier())){ context.setStatic(true); } context.setMethod(function); IxCode.TypeRef[] arguments = function.arguments(); for(int i = 0; i < arguments.length; i++){ context.add(ast.getArguments()[i].getName(), arguments[i]); } IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBlock(), context); block = addReturnNode(block, function.returnType()); function.setBlock(block); function.setFrame(context.getContextFrame()); return null; } public IxCode.StatementBlock addReturnNode(IxCode.ActionStatement node, IxCode.TypeRef returnType) { return new IxCode.StatementBlock(node, new IxCode.Return(defaultValue(returnType))); } public Object visit(GlobalVariableDeclaration ast, LocalContext context) { return null; } public Object visit(FieldDeclaration ast, LocalContext context) { return null; } public Object visit(DelegationDeclaration ast, LocalContext context) { return null; } public Object visit(InterfaceMethodDeclaration ast, LocalContext context) { return null; } public Object visit(MethodDeclaration ast, LocalContext local) { IxCode.MethodDefinition method = (IxCode.MethodDefinition) lookupKernelNode(ast); if(method == null) return null; if(ast.getBlock() == null) return null; LocalContext context = new LocalContext(); if(Modifier.isStatic(method.modifier())){ context.setStatic(true); } context.setMethod(method); IxCode.TypeRef[] arguments = method.arguments(); for(int i = 0; i < arguments.length; i++){ context.add(ast.getArguments()[i].getName(), arguments[i]); } IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBlock(), context); block = addReturnNode(block, method.returnType()); method.setBlock(block); method.setFrame(context.getContextFrame()); return null; } public Object visit(ConstructorDeclaration ast, LocalContext local) { IxCode.ConstructorDefinition constructor = (IxCode.ConstructorDefinition) lookupKernelNode(ast); if(constructor == null) return null; LocalContext context = new LocalContext(); context.setConstructor(constructor); IxCode.TypeRef[] args = constructor.getArgs(); for(int i = 0; i < args.length; i++){ context.add(ast.getArguments()[i].getName(), args[i]); } IxCode.Expression[] params = typeCheckExps(ast.getInitializers(), context); IxCode.StatementBlock block = (IxCode.StatementBlock) accept(ast.getBody(), context); IxCode.ClassDefinition currentClass = contextClass; IxCode.ClassTypeRef superClass = currentClass.getSuperClass(); IxCode.ConstructorRef[] matched = superClass.findConstructor(params); if(matched.length == 0){ report(CONSTRUCTOR_NOT_FOUND, ast, superClass, types(params)); return null; } if(matched.length > 1){ report(AMBIGUOUS_CONSTRUCTOR, ast, new Object[]{superClass, types(params)}, new Object[]{superClass, types(params)}); return null; } IxCode.Super init = new IxCode.Super( superClass, matched[0].getArgs(), params ); constructor.setSuperInitializer(init); block = addReturnNode(block, IxCode.BasicTypeRef.VOID); constructor.setBlock(block); constructor.setFrame(context.getContextFrame()); return null; } public IxCode.TypeRef resolve(TypeSpec type, NameResolution resolver) { IxCode.TypeRef resolvedType = (IxCode.TypeRef) resolver.resolve(type); if(resolvedType == null){ report(CLASS_NOT_FOUND, type, type.getComponentName()); } return resolvedType; } IxCode.TypeRef promote(IxCode.TypeRef left, IxCode.TypeRef right) { if(!numeric(left) || !numeric(right)) return null; if(left == IxCode.BasicTypeRef.DOUBLE || right == IxCode.BasicTypeRef.DOUBLE){ return IxCode.BasicTypeRef.DOUBLE; } if(left == IxCode.BasicTypeRef.FLOAT || right == IxCode.BasicTypeRef.FLOAT){ return IxCode.BasicTypeRef.FLOAT; } if(left == IxCode.BasicTypeRef.LONG || right == IxCode.BasicTypeRef.LONG){ return IxCode.BasicTypeRef.LONG; } return IxCode.BasicTypeRef.INT; } boolean hasNumericType(IxCode.Expression expression){ return numeric(expression.type()); } boolean numeric(IxCode.TypeRef symbol){ return (symbol.isBasicType()) && (symbol == IxCode.BasicTypeRef.BYTE || symbol == IxCode.BasicTypeRef.SHORT || symbol == IxCode.BasicTypeRef.CHAR || symbol == IxCode.BasicTypeRef.INT || symbol == IxCode.BasicTypeRef.LONG || symbol == IxCode.BasicTypeRef.FLOAT || symbol == IxCode.BasicTypeRef.DOUBLE ); } IxCode.Expression typeCheck(onion.lang.syntax.Expression expression, LocalContext context){ return (IxCode.Expression) expression.accept(this, context); } IxCode.ActionStatement translate(Statement statement, LocalContext context){ return (IxCode.ActionStatement) statement.accept(this, context); } } public CodeAnalysis(CompilerConfig config) { this.config = config; this.table = new ClassTable(classpath(config.getClassPath())); this.irt2ast = new HashMap<IxCode.Node, AstNode>(); this.ast2irt = new HashMap<AstNode, IxCode.Node>(); this.solvers = new HashMap<String, NameResolution>(); this.reporter = new SemanticErrorReporter(this.config.getMaxErrorReports()); } public IxCode.ClassDefinition[] process(CompilationUnit[] units){ ClassTableBuilder builder = new ClassTableBuilder(); for(int i = 0; i < units.length; i++){ builder.process(units[i]); } TypeHeaderAnalysis analysis = new TypeHeaderAnalysis(); for(int i = 0; i < units.length; i++){ analysis.process(units[i]); } TypeChecker checker = new TypeChecker(); for(int i = 0; i < units.length; i++){ checker.process(units[i]); } DuplicationChecker duplicationChecker = new DuplicationChecker(); for(int i = 0; i < units.length; i++){ duplicationChecker.process(units[i]); } CompileError[] problems = getProblems(); if(problems.length > 0){ throw new CompilationException(Arrays.asList(problems)); } return getSourceClasses(); } public class NameResolution { private ImportList imports; public NameResolution(ImportList imports) { this.imports = imports; } public IxCode.TypeRef resolve(TypeSpec specifier) { RawTypeNode component = specifier.getComponent(); String name = component.name(); IxCode.TypeRef resolvedType; if(component.kind() == RawTypeNode.BASIC){ resolvedType = name.equals("char") ? IxCode.BasicTypeRef.CHAR : name.equals("byte") ? IxCode.BasicTypeRef.BYTE : name.equals("short") ? IxCode.BasicTypeRef.SHORT : name.equals("int") ? IxCode.BasicTypeRef.INT : name.equals("long") ? IxCode.BasicTypeRef.LONG : name.equals("float") ? IxCode.BasicTypeRef.FLOAT : name.equals("double") ? IxCode.BasicTypeRef.DOUBLE : name.equals("boolean") ? IxCode.BasicTypeRef.BOOLEAN : IxCode.BasicTypeRef.VOID; }else if(component.kind() == RawTypeNode.NOT_QUALIFIED){ resolvedType = forName(name, false); }else{ resolvedType = forName(name, true); } IxCode.TypeRef componentType = resolvedType; if(specifier.getDimension() > 0){ return table.loadArray(componentType, specifier.getDimension()); }else{ return componentType; } } private IxCode.ClassTypeRef forName(String name, boolean qualified) { if(qualified) { return table.load(name); }else { for(int i = 0; i < imports.size(); i++){ String qualifiedName = imports.get(i).match(name); if(qualifiedName != null){ IxCode.ClassTypeRef resolvedSymbol = forName(qualifiedName, true); if(resolvedSymbol != null) return resolvedSymbol; } } return null; } } } }
package org.bbs.apklauncher; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipFile; import org.bbs.apklauncher.api.ExportApi; import org.bbs.apkparser.ApkManifestParser; import org.bbs.apkparser.PackageInfoX; import org.bbs.apkparser.PackageInfoX.ActivityInfoX; import org.bbs.apkparser.PackageInfoX.ApplicationInfoX; import org.bbs.apkparser.PackageInfoX.ServiceInfoX; import android.app.Application; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.InstrumentationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageInstaller; import android.content.pm.PackageManager; import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.UserHandle; import android.text.TextUtils; import android.util.Log; import dalvik.system.DexClassLoader; public class ApkPackageManager extends PackageManager { private static final String PLUGIN_DIR_NAME = "plugin"; private static final String APK_FILE_SUFFIX = ".apk"; private static final String TAG = ApkPackageManager.class.getSimpleName(); private static ApkPackageManager sInstance; public static Map<String, Reference<ClassLoader>> sApk2ClassLoaderMap = new HashMap<String, Reference<ClassLoader>>(); public static Map<String, WeakReference<Application>> sApk2ApplicationtMap = new HashMap<String, WeakReference<Application>>(); public static Map<String, WeakReference<ResourcesMerger>> sApk2ResourceMap = new HashMap<String, WeakReference<ResourcesMerger>>(); private InstallApks mInfos; private Application mContext; private SerializableUtil mSerUtil; private UpdateUtil mUpdateU; private ApkPackageManager() {} /** * @return * * NOTE: <p> * you must init this before use by {@link #init(Application, File)}. */ @ExportApi public static ApkPackageManager getInstance() { if (null == sInstance) { sInstance = new ApkPackageManager(); } return sInstance; } /** * @param context * @param apkDir where apk file located. * */ @ExportApi public void init(Application context){ mContext = context; mInfos = new InstallApks(); mSerUtil = new SerializableUtil(context); mUpdateU = new UpdateUtil(UpdateUtil.PREF_KEY_VERSION_ID); if (mUpdateU.isAppUpdate(context) || mUpdateU.isFirstUsage(context)) { // re-build install apk info. scanApkDir(getAppDir(), false); // mSerUtil.put(mInfos); } else { scanApkDir(getAppDir(), false); // mInfos = mSerUtil.get(); } if (mUpdateU.isAppUpdate(context)){ mUpdateU.updateVersion(context); } File autoUpdateDir = getAutoUpdatePluginDir(); scanApkDir(autoUpdateDir, true); String[] files = autoUpdateDir.list(); if (files != null){ for (String fname: files){ new File(autoUpdateDir, fname).delete(); } } } public static ResourcesMerger makeTargetResource(String mTargetApkPath, Context context) { WeakReference<ResourcesMerger> rr = ApkPackageManager.sApk2ResourceMap.get(mTargetApkPath); Resources targetRes; ResourcesMerger resMerger; if (rr != null && rr.get() != null) { resMerger = rr.get(); targetRes = resMerger.mFirst; } else { targetRes = LoadedApk.loadApkResource(mTargetApkPath, context); resMerger = new ResourcesMerger(targetRes, context.getResources()); ApkPackageManager.sApk2ResourceMap.put(mTargetApkPath, new WeakReference<ResourcesMerger>(resMerger)); } return resMerger; } public ClassLoader createClassLoader(Context baseContext, String apkPath, String libPath, String targetPackageName) { ClassLoader cl = ApkPackageManager.getClassLoader(targetPackageName); if (null == cl) { String optPath = getOptDir().getPath(); cl = new DexClassLoader(apkPath, optPath, libPath, baseContext.getClassLoader()); cl = new TargetClassLoader(apkPath, optPath, libPath, baseContext.getClassLoader(), targetPackageName, mContext); ApkPackageManager.putClassLoader(targetPackageName, (cl)); } return cl; } public static ClassLoader getClassLoader(String packageName) { Reference<ClassLoader> reference = sApk2ClassLoaderMap.get(packageName); if (null != reference) { ClassLoader c = reference.get(); return c; } return null; } public static void putClassLoader(String packageName, ClassLoader classLoader) { sApk2ClassLoaderMap.put(packageName, new SoftReference<ClassLoader>(classLoader)); } @ExportApi public static Application getApplication(String packageName) { WeakReference<Application> weakReference = sApk2ApplicationtMap.get(packageName); if (null != weakReference) { return weakReference.get(); } return null; } public static void putApplication(String packageName, Application app) { sApk2ApplicationtMap.put(packageName, new WeakReference<Application>(app)); } @ExportApi public File getPluginDir() { return mContext.getDir(PLUGIN_DIR_NAME, 0); } @ExportApi public File getAutoUpdatePluginDir() { File dir = new File(getPluginDir(), "auto_update"); dir.mkdirs(); return dir; } @ExportApi public File getAppDir() { File dir = new File(getPluginDir(), "app"); dir.mkdirs(); return dir; } @ExportApi public File getOptDir() { File dir = new File(getPluginDir(), "opt"); dir.mkdirs(); return dir; } @ExportApi public void scanApkDir(File apkDir) { scanApkDir(apkDir, true); } private void scanApkDir(File apkDir, boolean copyFile) { Log.d(TAG, "parse dir: " + apkDir); if (null == apkDir || !apkDir.exists()) { return ; } String[] files = apkDir.list(); if (null == files) { return; } for (String f : files) { File file = new File(apkDir.getAbsolutePath() + "/" + f); parseApkFile(file, copyFile); } // mSerUtil.put(mInfos); } private void parseApkFile(File file, boolean copyFile) { Log.d(TAG, "parse file: " + file); if (file.exists() && file.getAbsolutePath().endsWith(APK_FILE_SUFFIX)){ PackageInfoX info = ApkManifestParser.parseAPk(mContext, file.getAbsolutePath()); try { File dest = file; if (copyFile) { dest = new File(getAppDir(), info.packageName + APK_FILE_SUFFIX); AndroidUtil.copyFile(file, dest); info = ApkManifestParser.parseAPk(mContext, dest.getAbsolutePath()); } Log.d(TAG, "apk info : " + appInfoStr(info)); File destLibDir = new File(getPluginDir(), info.packageName + "/lib"); //TODO native lib AndroidUtil.extractZipEntry(new ZipFile(info.applicationInfo.publicSourceDir), "lib/armeabi", destLibDir); AndroidUtil.extractZipEntry(new ZipFile(info.applicationInfo.publicSourceDir), "lib/armeabi-v7a", destLibDir); info.mLibPath = destLibDir.getPath(); // asume there is only one apk. ClassLoader cl = createClassLoader(mContext, info.applicationInfo.sourceDir, info.mLibPath, info.applicationInfo.packageName); mInfos.addOrUpdate(info); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Log.i(TAG, "ignre file: " + file); } } @ExportApi public ApplicationInfoX getApplicationInfo(String className) { ApplicationInfoX a = null; boolean has = false; for (PackageInfoX m : mInfos) { if (className.equals(m.applicationInfo.name)) { has = true; a = (ApplicationInfoX) m.applicationInfo; break; } } return a; } @ExportApi public PackageInfoX getPackageInfo(String packageName){ PackageInfoX p = null; for (PackageInfoX a : mInfos) { if (a.packageName.equals(packageName)){ p = a; break; } } return p; } @ExportApi public boolean hasApplicationInfo(String className) { boolean has = false; for (PackageInfoX m : mInfos) { if (className.equals(m.applicationInfo.packageName)) { has = true; break; } } return has; } @ExportApi public List<PackageInfoX> getAllApks(){ return mInfos; } @ExportApi public ActivityInfoX getActivityInfo(String className) { for (PackageInfoX m : mInfos) { if (m.activities != null) { for (ActivityInfo a : m.activities) { ActivityInfoX aX = (ActivityInfoX) a; if (className.equals(a.name)) { return aX; } } } } return null; } @ExportApi public ServiceInfoX getServiceInfo(String className) { for (PackageInfoX m : mInfos) { if (m.services != null && m.services.length > 0) { final int count = m.services.length; for (int i = 0 ; i < count; i++){ ServiceInfoX a = (ServiceInfoX) m.services[i]; if (className.equals(a.name)) { return a; } }} } return null; } @ExportApi public List<ResolveInfo> queryIntentActivities(Intent intent, int flag) { List<ResolveInfo> result = new ArrayList<>(); for (PackageInfoX p : mInfos){ queryIntentActivities(p.packageName, intent, flag, result); } return result; } @ExportApi public List<ResolveInfo> queryIntentActivities(String packageName, Intent intent, int flag) { List<ResolveInfo> result = new ArrayList<>(); queryIntentActivities(packageName, intent, flag, result); return result; } @ExportApi private void queryIntentActivities(String packageName, Intent intent, int flag, List<ResolveInfo> result){ if (TextUtils.isEmpty(packageName)) return; String action = intent.getAction(); Set<String> categories = intent.getCategories(); for (PackageInfoX p : mInfos){ if (packageName.equals(p.packageName)){ for (ActivityInfo a : p.activities){ ActivityInfoX aX = (ActivityInfoX) a; if (aX.mIntentFilters == null) { continue; } for( IntentFilter intentFilter: aX.mIntentFilters) { if (intentFilter.matchAction(action) && intentFilter.matchCategories(categories) == null) { ResolveInfo info = new ResolveInfo(); info.activityInfo = a; result.add(info); } } } } } } void notSupported() { throw new RuntimeException("not supported. you can impl it instead."); } @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public String[] currentToCanonicalPackageNames(String[] names) { notSupported(); return null; } @Override public String[] canonicalToCurrentPackageNames(String[] names) { notSupported(); return null; } @Override public Intent getLaunchIntentForPackage(String packageName) { notSupported(); return null; } @Override public Intent getLeanbackLaunchIntentForPackage(String packageName) { notSupported(); return null; } @Override public int[] getPackageGids(String packageName) throws NameNotFoundException { notSupported(); return null; } @Override public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { notSupported(); return null; } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public ActivityInfo getActivityInfo(ComponentName component, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public ActivityInfo getReceiverInfo(ComponentName component, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public ServiceInfo getServiceInfo(ComponentName component, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public ProviderInfo getProviderInfo(ComponentName component, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public List<PackageInfo> getInstalledPackages(int flags) { notSupported(); return null; } @Override public List<PackageInfo> getPackagesHoldingPermissions( String[] permissions, int flags) { notSupported(); return null; } @Override public int checkPermission(String permName, String pkgName) { notSupported(); return 0; } @Override public boolean addPermission(PermissionInfo info) { notSupported(); return false; } @Override public boolean addPermissionAsync(PermissionInfo info) { notSupported(); return false; } @Override public void removePermission(String name) { notSupported(); } @Override public int checkSignatures(String pkg1, String pkg2) { notSupported(); return 0; } @Override public int checkSignatures(int uid1, int uid2) { notSupported(); return 0; } @Override public String[] getPackagesForUid(int uid) { notSupported(); return null; } @Override public String getNameForUid(int uid) { notSupported(); return null; } @Override public List<ApplicationInfo> getInstalledApplications(int flags) { notSupported(); return null; } @Override public String[] getSystemSharedLibraryNames() { notSupported(); return null; } @Override public FeatureInfo[] getSystemAvailableFeatures() { notSupported(); return null; } @Override public boolean hasSystemFeature(String name) { notSupported(); return false; } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { notSupported(); return null; } @Override public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags) { notSupported(); return null; } @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { notSupported(); return null; } @Override public ResolveInfo resolveService(Intent intent, int flags) { notSupported(); return null; } @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { notSupported(); return null; } @Override public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) { notSupported(); return null; } @Override public ProviderInfo resolveContentProvider(String name, int flags) { notSupported(); return null; } @Override public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) { notSupported(); return null; } @Override public InstrumentationInfo getInstrumentationInfo(ComponentName className, int flags) throws NameNotFoundException { notSupported(); return null; } @Override public List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags) { notSupported(); return null; } @Override public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) { notSupported(); return null; } @Override public Drawable getActivityIcon(ComponentName activityName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getActivityIcon(Intent intent) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getActivityBanner(ComponentName activityName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getActivityBanner(Intent intent) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getDefaultActivityIcon() { notSupported(); return null; } @Override public Drawable getApplicationIcon(ApplicationInfo info) { notSupported(); return null; } @Override public Drawable getApplicationIcon(String packageName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getApplicationBanner(ApplicationInfo info) { notSupported(); return null; } @Override public Drawable getApplicationBanner(String packageName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getActivityLogo(ComponentName activityName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getActivityLogo(Intent intent) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getApplicationLogo(ApplicationInfo info) { notSupported(); return null; } @Override public Drawable getApplicationLogo(String packageName) throws NameNotFoundException { notSupported(); return null; } @Override public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) { notSupported(); return null; } @Override public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user, Rect badgeLocation, int badgeDensity) { notSupported(); return null; } @Override public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) { notSupported(); return null; } @Override public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) { notSupported(); return null; } @Override public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) { notSupported(); return null; } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { notSupported(); return null; } @Override public Resources getResourcesForActivity(ComponentName activityName) throws NameNotFoundException { notSupported(); return null; } @Override public Resources getResourcesForApplication(ApplicationInfo app) throws NameNotFoundException { notSupported(); return null; } @Override public Resources getResourcesForApplication(String appPackageName) throws NameNotFoundException { notSupported(); return null; } @Override public void verifyPendingInstall(int id, int verificationCode) { notSupported(); } @Override public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay) { notSupported(); } @Override public void setInstallerPackageName(String targetPackage, String installerPackageName) { notSupported(); } @Override public String getInstallerPackageName(String packageName) { notSupported(); return null; } @Override @Deprecated public void addPackageToPreferred(String packageName) { notSupported(); } @Override @Deprecated public void removePackageFromPreferred(String packageName) { notSupported(); } @Override public List<PackageInfo> getPreferredPackages(int flags) { notSupported(); return null; } @Override @Deprecated public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { notSupported(); } @Override public void clearPackagePreferredActivities(String packageName) { notSupported(); } @Override public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) { notSupported(); return 0; } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) { notSupported(); } @Override public int getComponentEnabledSetting(ComponentName componentName) { notSupported(); return 0; } @Override public void setApplicationEnabledSetting(String packageName, int newState, int flags) { notSupported(); } @Override public int getApplicationEnabledSetting(String packageName) { notSupported(); return 0; } @Override public boolean isSafeMode() { notSupported(); return false; } @Override public PackageInstaller getPackageInstaller() { notSupported(); return null; } static class InstallApks extends ArrayList<PackageInfoX> implements Serializable { public void addOrUpdate(PackageInfoX info){ int index = -1; final int SIZE = size(); for (int i = 0 ; i < SIZE ; i++){ if (get(i).packageName.equals(info.packageName)){ index = i; break; } } if (index >= 0) { PackageInfoX old = remove(index); Log.d(TAG, "old app: " + appInfoStr(old) ); Log.d(TAG, "new app: " + appInfoStr(info) ); } add(info); } } static String appInfoStr(PackageInfoX info) { return info.packageName + "|" + info.versionCode + "|" + info.versionName; } static class SerializableUtil { public Context mContext; private File mFile; SerializableUtil(Application context){ mContext = context; mFile = new File(context.getDir(PLUGIN_DIR_NAME, 0), "plugins.xml"); } void put(InstallApks apk) { try { ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream(mFile)); oop.writeObject(apk); oop.flush(); oop.close(); } catch (IOException e) { e.printStackTrace(); } } InstallApks get(){ Object o = null; try { ObjectInputStream oin = new ObjectInputStream(new FileInputStream(mFile)); o = oin.readObject(); oin.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return (InstallApks) o; } } public static class UpdateUtil { private static final String PREF_LATEST_VERSION_ID = "latest_version_id"; static final String PREF_KEY_VERSION_ID = "apk_internal_version_id"; private String mKey; public UpdateUtil(String perfVersionIdKey){ mKey = perfVersionIdKey; } public boolean isAppUpdate(Context context) { boolean update = false; try { String version = "" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; SharedPreferences sp = context.getSharedPreferences(PREF_LATEST_VERSION_ID, 0); String lastestVersionId = sp.getString(PREF_KEY_VERSION_ID, ""); if (!TextUtils.isEmpty(lastestVersionId) && !lastestVersionId.equals(version)) { update = true; } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return update; } public boolean updateVersion(Context context) { boolean update = false; try { String version = "" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; SharedPreferences sp = context.getSharedPreferences(PREF_LATEST_VERSION_ID, 0); sp.edit().putString(PREF_KEY_VERSION_ID, version).commit(); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return update; } public boolean isFirstUsage(Context context) { boolean update = false; SharedPreferences sp = context.getSharedPreferences(PREF_LATEST_VERSION_ID, 0); String lastestVersionId = sp.getString(PREF_KEY_VERSION_ID, ""); if (TextUtils.isEmpty(lastestVersionId)) { update = true; } return update; } } }
package org.nutz.mvc.view; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.segment.CharSegment; import org.nutz.lang.segment.Segment; import org.nutz.mvc.View; public class ServerRedirectView implements View { private Segment dest; public ServerRedirectView(String dest) { this.dest = new CharSegment(Strings.trim(dest)); } public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Exception { Mirror<?> mirror = Mirror.me(obj); // Fill path for (Iterator<String> it = dest.keys().iterator(); it.hasNext();) { String key = it.next(); Object value = null; if (null != mirror && key.startsWith("obj.") && key.length()>4) { value = mirror.getValue(obj, key.substring(4)); } else { value = req.getParameter(key); } if (null == value) value = obj; dest.set(key, value); } // Format the path ... String path = dest.toString(); // Absolute path, add the context path for it if (path.startsWith("/")) { path = req.getContextPath() + path; } // Relative path, add current URL path for it else { String myPath = req.getPathInfo(); int pos = myPath.lastIndexOf('/'); if (pos > 0) path = myPath.substring(0, pos) + "/" + path; else path = "/" + path; } resp.sendRedirect(path); resp.flushBuffer(); } }
package org.objectweb.asm.util; import org.objectweb.asm.Label; import org.objectweb.asm.Attribute; import org.objectweb.asm.attrs.Dumpable; import java.util.HashMap; /** * A {@link PrintCodeVisitor PrintCodeVisitor} that prints the ASM code that * generates the code it visits. */ public class DumpCodeVisitor extends PrintCodeVisitor { /** * The label names. This map associate String values to Label keys. */ private final HashMap labelNames; /** * Constructs a new {@link DumpCodeVisitor DumpCodeVisitor} object. */ public DumpCodeVisitor () { this.labelNames = new HashMap(); } public void printInsn (final int opcode) { buf.append("cv.visitInsn("). append(OPCODES[opcode]). append(");\n"); } public void printIntInsn (final int opcode, final int operand) { buf.append("cv.visitIntInsn("). append(OPCODES[opcode]). append(", "). append(operand). append(");\n"); } public void printVarInsn (final int opcode, final int var) { buf.append("cv.visitVarInsn("). append(OPCODES[opcode]). append(", "). append(var). append(");\n"); } public void printTypeInsn (final int opcode, final String desc) { buf.append("cv.visitTypeInsn("). append(OPCODES[opcode]). append(", "); DumpClassVisitor.appendConstant(buf, desc); buf.append(");\n"); } public void printFieldInsn ( final int opcode, final String owner, final String name, final String desc) { buf.append("cv.visitFieldInsn(") .append(OPCODES[opcode]) .append(", "); DumpClassVisitor.appendConstant(buf, owner); buf.append(", "); DumpClassVisitor.appendConstant(buf, name); buf.append(", "); DumpClassVisitor.appendConstant(buf, desc); buf.append(");\n"); } public void printMethodInsn ( final int opcode, final String owner, final String name, final String desc) { buf.append("cv.visitMethodInsn(") .append(OPCODES[opcode]) .append(", "); DumpClassVisitor.appendConstant(buf, owner); buf.append(", "); DumpClassVisitor.appendConstant(buf, name); buf.append(", "); DumpClassVisitor.appendConstant(buf, desc); buf.append(");\n"); } public void printJumpInsn (final int opcode, final Label label) { declareLabel(label); buf.append("cv.visitJumpInsn(") .append(OPCODES[opcode]) .append(", "); appendLabel(label); buf.append(");\n"); } public void printLabel (final Label label) { declareLabel(label); buf.append("cv.visitLabel("); appendLabel(label); buf.append(");\n"); } public void printLdcInsn (final Object cst) { buf.append("cv.visitLdcInsn("); DumpClassVisitor.appendConstant(buf, cst); buf.append(");\n"); } public void printIincInsn (final int var, final int increment) { buf.append("cv.visitIincInsn(") .append(var) .append(", ") .append(increment) .append(");\n"); } public void printTableSwitchInsn ( final int min, final int max, final Label dflt, final Label labels[]) { for (int i = 0; i < labels.length; ++i) { declareLabel(labels[i]); } declareLabel(dflt); buf.append("cv.visitTableSwitchInsn(") .append(min) .append(", ") .append(max) .append(", "); appendLabel(dflt); buf.append(", new Label[] {"); for (int i = 0; i < labels.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(labels[i]); } buf.append(" });\n"); } public void printLookupSwitchInsn ( final Label dflt, final int keys[], final Label labels[]) { for (int i = 0; i < labels.length; ++i) { declareLabel(labels[i]); } declareLabel(dflt); buf.append("cv.visitLookupSwitchInsn("); appendLabel(dflt); buf.append(", new int[] {"); for (int i = 0; i < keys.length; ++i) { buf.append(i == 0 ? " " : ", ").append(keys[i]); } buf.append(" }, new Label[] {"); for (int i = 0; i < labels.length; ++i) { buf.append(i == 0 ? " " : ", "); appendLabel(labels[i]); } buf.append(" });\n"); } public void printMultiANewArrayInsn (final String desc, final int dims) { buf.append("cv.visitMultiANewArrayInsn("); DumpClassVisitor.appendConstant(buf, desc); buf.append(", ") .append(dims) .append(");\n"); } public void printTryCatchBlock ( final Label start, final Label end, final Label handler, final String type) { buf.append("cv.visitTryCatchBlock("); appendLabel(start); buf.append(", "); appendLabel(end); buf.append(", "); appendLabel(handler); buf.append(", "); DumpClassVisitor.appendConstant(buf, type); buf.append(");\n"); } public void printMaxs (final int maxStack, final int maxLocals) { buf.append("cv.visitMaxs(") .append(maxStack) .append(", ") .append(maxLocals) .append(");\n"); } public void printLocalVariable ( final String name, final String desc, final Label start, final Label end, final int index) { buf.append("cv.visitLocalVariable("); DumpClassVisitor.appendConstant(buf, name); buf.append(", "); DumpClassVisitor.appendConstant(buf, desc); buf.append(", "); appendLabel(start); buf.append(", "); appendLabel(end); buf.append(", ").append(index).append(");\n"); } public void printLineNumber (final int line, final Label start) { buf.append("cv.visitLineNumber(") .append(line) .append(", "); appendLabel(start); buf.append(");\n"); } public void printAttribute (final Attribute attr) { if( attr instanceof Dumpable) { buf.append("// CODE ATTRIBUTE\n"); (( Dumpable) attr).dump( buf, "cv", labelNames); } else { buf.append("// WARNING! skipped a non standard code attribute of type \""); buf.append(attr.type).append("\"\n"); } } /** * Appends a declaration of the given label to {@link #buf buf}. This * declaration is of the form "Label lXXX = new Label();". Does nothing * if the given label has already been declared. * * @param l a label. */ private void declareLabel (final Label l) { String name = (String)labelNames.get(l); if (name == null) { name = "l" + labelNames.size(); labelNames.put(l, name); buf.append("Label ") .append(name) .append(" = new Label();\n"); } } /** * Appends the name of the given label to {@link #buf buf}. The given label * <i>must</i> already have a name. One way to ensure this is to always call * {@link #declareLabel declared} before calling this method. * * @param l a label. */ private void appendLabel (final Label l) { buf.append((String)labelNames.get(l)); } }
package org.onyxplatform.api.java; import clojure.lang.PersistentVector; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Serves as a base for any Onyx concept that is represented by a vector of * onyx maps, e.g. workflows. */ public class OnyxVector { protected PersistentVector vContents; /** * Constructs a new OnyxVector object with an empty contents vector. * @return new OnyxVector object with an empty content vector */ protected OnyxVector() { vContents = PersistentVector.EMPTY; } /** * Constructs a new OnyxVector object with an initial contents vector set * to an existing passed vector * @param PersistentVector pv existing vector to use as content vector * @return new OnyxVector object */ protected OnyxVector(PersistentVector pv) { vContents = pv; } /** * Creates a new ArrayList by converting the existing content * vector (does not alter the existing content vector). * @return newly created ArrayList representation of the content vector */ public List<Map<String, Object>> toList() { return new ArrayList(vContents); } /** * Adds an existing object to the content vector of the object, appending * it to the end of the content vector. The object should represent a map. * @param Object o object to be added to the existing content vector */ protected void addElement(Object o) { vContents = vContents.cons(o); } /** * Iterates over the existing content vector, ensuring each constituent * map is a Clojure PersistentHashMap in a new PersistentVector container. * @return new PersistentVector container containing guaranteed * PersistentHashMap entities */ protected PersistentVector toCljVector() { PersistentVector v = PersistentVector.EMPTY; for (Object e : vContents) { OnyxEntity oe = (OnyxEntity) e; v = v.cons(oe.toCljMap()); } return v; } /** * Produces a string representation of the * contents of the content vector without modifying the actual vector. * @return string representation of the content vector */ @Override public String toString() { return Arrays.toString(vContents.toArray()); } }
package org.springframework.richclient.table; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author peter.de.bruycker */ public class ListTableModelTest extends TestCase { /** * TestCase for bug #RCP-14 */ public void testConstructorThrowsNullPointerException() { try { ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class }; } protected String[] createColumnNames() { return new String[] { "column" }; } }; model.getColumnCount(); } catch (NullPointerException e) { fail("Should not throw NullPointerException"); } try { ListTableModel model = new ListTableModel(new ArrayList()) { protected Class[] createColumnClasses() { return new Class[] { String.class }; } protected String[] createColumnNames() { return new String[] { "col0" }; } }; model.getColumnCount(); } catch (NullPointerException e) { fail("Should not throw NullPointerException"); } } public void testGetValueAtInternalWithOneColumnNoArray() { ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class }; } protected String[] createColumnNames() { return new String[] { "col0" }; } }; model.setRowNumbers(false); String row = "col0"; assertEquals("col0", model.getValueAtInternal(row, 0)); } public void testGetValueAtInternalWithArray() { ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class, String.class }; } protected String[] createColumnNames() { return new String[] { "col0", "col1" }; } }; model.setRowNumbers(false); String[] row = new String[] { "col0", "col1" }; assertEquals("col0", model.getValueAtInternal(row, 0)); assertEquals("col1", model.getValueAtInternal(row, 1)); } public void testGetValueAtInternalWithInvalidObjectType() { // model with two columns, but no list or array as rows ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class, String.class }; } protected String[] createColumnNames() { return new String[] { "col0", "col1" }; } }; model.setRowNumbers(false); String row = "col0"; try { model.getValueAtInternal(row, 0); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException e) { pass(); } } private static void pass() { // test passes } public void testGetValueAtInternalWithList() { ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class, String.class }; } protected String[] createColumnNames() { return new String[] { "col0", "col1" }; } }; model.createColumnInfo(); List row = Arrays.asList(new String[] { "col0", "col1" }); assertEquals("col0", model.getValueAtInternal(row, 0)); assertEquals("col1", model.getValueAtInternal(row, 1)); } public void testGetValueAtInternalWithOneColumnAndArray() { ListTableModel model = new ListTableModel() { protected Class[] createColumnClasses() { return new Class[] { String.class }; } protected String[] createColumnNames() { return new String[] { "col0" }; } }; model.setRowNumbers(false); String[] row = new String[] { "col0", "col1" }; assertEquals("col0", model.getValueAtInternal(row, 0)); } }
package org.opencms.db.generic; import org.opencms.db.CmsDbUtil; import org.opencms.db.CmsDriverManager; import org.opencms.db.I_CmsBackupDriver; import org.opencms.db.I_CmsDriver; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsConstants; import org.opencms.main.OpenCms; import org.opencms.util.CmsUUID; import org.opencms.file.CmsBackupProject; import org.opencms.file.CmsBackupResource; import org.opencms.file.CmsFile; import org.opencms.file.CmsProject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertydefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.file.CmsUser; import java.io.ByteArrayInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; 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 java.util.Vector; import org.apache.commons.collections.ExtendedProperties; public class CmsBackupDriver extends Object implements I_CmsDriver, I_CmsBackupDriver { /** The driver manager instance. */ protected CmsDriverManager m_driverManager; /** The SQL manager instance. */ protected org.opencms.db.generic.CmsSqlManager m_sqlManager; /** * @see org.opencms.db.I_CmsBackupDriver#createBackupResource(java.sql.ResultSet, boolean) */ public CmsBackupResource createBackupResource(ResultSet res, boolean hasContent) throws SQLException { byte[] content = null; CmsUUID backupId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_BACKUP_ID"))); int versionId = res.getInt(m_sqlManager.readQuery("C_RESOURCES_VERSION_ID")); int tagId = res.getInt(m_sqlManager.readQuery("C_RESOURCES_PUBLISH_TAG")); CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_STRUCTURE_ID"))); CmsUUID resourceId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_RESOURCE_ID"))); String resourcePath = res.getString(m_sqlManager.readQuery("C_RESOURCES_RESOURCE_PATH")); int resourceType = res.getInt(m_sqlManager.readQuery("C_RESOURCES_RESOURCE_TYPE")); int resourceFlags = res.getInt(m_sqlManager.readQuery("C_RESOURCES_RESOURCE_FLAGS")); int projectLastModified = res.getInt(m_sqlManager.readQuery("C_RESOURCES_PROJECT_LASTMODIFIED")); int state = res.getInt(m_sqlManager.readQuery("C_RESOURCES_STATE")); long dateCreated = res.getLong(m_sqlManager.readQuery("C_RESOURCES_DATE_CREATED")); long dateLastModified = res.getLong(m_sqlManager.readQuery("C_RESOURCES_DATE_LASTMODIFIED")); long dateReleased = res.getLong(m_sqlManager.readQuery("C_RESOURCES_DATE_RELEASED")); long dateExpired = res.getLong(m_sqlManager.readQuery("C_RESOURCES_DATE_EXPIRED")); int resourceSize = res.getInt(m_sqlManager.readQuery("C_RESOURCES_SIZE")); CmsUUID userLastModified = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_USER_LASTMODIFIED"))); String userLastModifiedName = res.getString(m_sqlManager.readQuery("C_RESOURCES_LASTMODIFIED_BY_NAME")); CmsUUID userCreated = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_USER_CREATED"))); String userCreatedName = res.getString(m_sqlManager.readQuery("C_RESOURCES_USER_CREATED_NAME")); CmsUUID contentId; if (hasContent) { content = m_sqlManager.getBytes(res, m_sqlManager.readQuery("C_RESOURCES_FILE_CONTENT")); contentId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_RESOURCES_CONTENT_ID"))); } else { content = new byte[0]; contentId = CmsUUID.getNullUUID(); } return new CmsBackupResource( backupId, tagId, versionId, structureId, resourceId, contentId, resourcePath, resourceType, resourceFlags, projectLastModified, state, dateCreated, userCreated, userCreatedName, dateLastModified, userLastModified, userLastModifiedName, dateReleased, dateExpired, resourceSize, content); } /** * @see org.opencms.db.I_CmsBackupDriver#createBackupPropertyDefinition(java.lang.String, int) */ public CmsPropertydefinition createBackupPropertyDefinition(String name, int mappingtype) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { // create the backup property definition conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_CREATE_BACKUP"); stmt.setString(1, new CmsUUID().toString()); stmt.setString(2, name); stmt.setInt(3, mappingtype); stmt.executeUpdate(); } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, "PropertyDefinition="+name+"; ResourceType="+mappingtype, CmsException.C_SQL_ERROR, exc, true); } finally { m_sqlManager.closeAll(conn, stmt, null); } return readBackupPropertyDefinition(name, mappingtype); } /** * @see org.opencms.db.I_CmsBackupDriver#deleteBackups(java.util.List, int) */ public void deleteBackups(List existingBackups, int maxVersions) throws CmsException { PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; Connection conn = null; CmsBackupResource currentResource = null; int count = existingBackups.size() - maxVersions; try { conn = m_sqlManager.getConnectionForBackup(); stmt1 = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_DELETE_RESOURCE"); stmt2 = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_DELETEALL_BACKUP"); for (int i = 0; i < count; i++) { currentResource = (CmsBackupResource)existingBackups.get(i); // delete the resource stmt1.setString(1, currentResource.getStructureId().toString()); stmt1.setInt(2, currentResource.getTagId()); stmt1.addBatch(); // delete the properties stmt2.setString(1, currentResource.getBackupId().toString()); stmt2.setInt(2, currentResource.getTagId()); stmt2.setString(3, currentResource.getStructureId().toString()); stmt2.setInt(4, CmsProperty.C_STRUCTURE_RECORD_MAPPING); stmt2.setString(5, currentResource.getResourceId().toString()); stmt2.setInt(6, CmsProperty.C_RESOURCE_RECORD_MAPPING); stmt2.addBatch(); } if (count > 0) { stmt1.executeBatch(); stmt2.executeBatch(); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt1, null); m_sqlManager.closeAll(conn, stmt2, null); } } /** * @see org.opencms.db.I_CmsBackupDriver#deleteBackup(org.opencms.file.CmsBackupResource, int, int) */ public void deleteBackup(CmsBackupResource resource, int tag, int versions) throws CmsException { ResultSet res = null; PreparedStatement stmt = null; PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; PreparedStatement stmt3 = null; PreparedStatement stmt4 = null; Connection conn = null; List backupIds= new ArrayList(); // first get all backup ids of the entries which should be deleted try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_READ_BACKUPID_FOR_DELETION"); stmt.setString(1, resource.getStructureId().toString()); stmt.setString(2, resource.getResourceId().toString()); stmt.setInt(3, versions); stmt.setInt(4, tag); res = stmt.executeQuery(); // now collect all backupId's for deletion while (res.next()) { backupIds.add(res.getString(1)); } // we have all the nescessary information, so we can delete the old backups stmt1 = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_DELETE_STRUCTURE_BYBACKUPID"); stmt2 = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_DELETE_RESOURCES_BYBACKUPID"); stmt3 = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_DELETE_CONTENTS_BYBACKUPID"); stmt4 = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_DELETE_PROPERTIES_BYBACKUPID"); Iterator i=backupIds.iterator(); while (i.hasNext()) { String backupId=(String)i.next(); //delete the structure stmt1.setString(1, backupId); stmt1.addBatch(); //delete the resource stmt2.setString(1, backupId); stmt2.addBatch(); //delete the file stmt3.setString(1, backupId); stmt3.addBatch(); //delete the properties stmt4.setString(1, backupId); stmt4.addBatch(); } // excecute them stmt1.executeBatch(); stmt2.executeBatch(); stmt3.executeBatch(); stmt4.executeBatch(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); m_sqlManager.closeAll(conn, stmt1, null); m_sqlManager.closeAll(conn, stmt2, null); m_sqlManager.closeAll(conn, stmt3, null); m_sqlManager.closeAll(conn, stmt4, null); } } /** * @see org.opencms.db.I_CmsBackupDriver#destroy() */ public void destroy() throws Throwable { finalize(); if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Shutting down : " + this.getClass().getName() + " ... ok!"); } } /** * Releases any allocated resources during garbage collection.<p> * * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { try { m_sqlManager = null; m_driverManager = null; } catch (Throwable t) { // ignore } super.finalize(); } /** * @see org.opencms.db.I_CmsDriver#init(org.apache.commons.collections.ExtendedProperties, java.util.List, org.opencms.db.CmsDriverManager) */ public void init(ExtendedProperties configuration, List successiveDrivers, CmsDriverManager driverManager) { String poolUrl = configuration.getString("db.backup.pool"); m_sqlManager = this.initQueries(); m_sqlManager.setPoolUrlOffline(poolUrl); m_sqlManager.setPoolUrlOnline(poolUrl); m_sqlManager.setPoolUrlBackup(poolUrl); m_driverManager = driverManager; if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Assigned pool : " + poolUrl); } if (successiveDrivers != null && !successiveDrivers.isEmpty()) { if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isWarnEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).warn(this.getClass().toString() + " does not support successive drivers"); } } } /** * @see org.opencms.db.I_CmsBackupDriver#initQueries() */ public org.opencms.db.generic.CmsSqlManager initQueries() { return new org.opencms.db.generic.CmsSqlManager(); } /** * Gets the next version id for a given backup resource. <p> * * @param resource the resource to get the next version from * @return next version id */ private int internalReadNextVersionId(CmsResource resource) { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; int versionId = 1; try { // get the max version id conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_BACKUP_MAXVER"); //stmt.setString(1, resource.getStructureId().toString()); stmt.setString(1, resource.getResourceId().toString()); res = stmt.executeQuery(); if (res.next()) { versionId = res.getInt(1) + 1; } return versionId; } catch (SQLException exc) { return 1; } finally { m_sqlManager.closeAll(conn, stmt, res); } } /** * Tests is a backup resource does exisit.<p> * * @param resource the resource to test * @param tagId the tadId of the resource to test * @return true if the resource already exists, false otherweise * @throws CmsException if something goes wrong. */ private boolean internalValidateBackupResource(CmsResource resource, int tagId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; ResultSet res = null; boolean exists = false; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_EXISTS_RESOURCE"); stmt.setString(1, resource.getResourceId().toString()); stmt.setInt(2, tagId); res = stmt.executeQuery(); exists = res.next(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return exists; } /** * Internal method to write the backup content.<p> * * @param backupId the backup id * @param resource the resource to backup * @param tagId the tag revision * @param versionId the version revision * @throws CmsException if something goes wrong */ protected void internalWriteBackupFileContent(CmsUUID backupId, CmsResource resource, int tagId, int versionId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; CmsUUID contentId; byte[] fileContent; if (resource instanceof CmsFile) { contentId = ((CmsFile)resource).getContentId(); fileContent = ((CmsFile)resource).getContents(); } else { contentId = CmsUUID.getNullUUID(); fileContent = new byte[0]; } try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_CONTENTS_WRITE_BACKUP"); stmt.setString(1, contentId.toString()); stmt.setString(2, resource.getResourceId().toString()); if (fileContent.length < 2000) { stmt.setBytes(3, fileContent); } else { stmt.setBinaryStream(3, new ByteArrayInputStream(fileContent), fileContent.length); } stmt.setInt(4, tagId); stmt.setInt(5, versionId); stmt.setString(6, backupId.toString()); stmt.executeUpdate(); fileContent = null; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupFile(int, String) */ public CmsBackupResource readBackupFile(int tagId, String resourcePath) throws CmsException { CmsBackupResource file = null; PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_FILES_READ_BACKUP"); stmt.setString(1, resourcePath); stmt.setInt(2, tagId); res = stmt.executeQuery(); if (res.next()) { file = createBackupResource(res, true); while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } else { throw new CmsVfsResourceNotFoundException("[" + this.getClass().getName() + "] " + resourcePath.toString()); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (CmsException ex) { throw ex; } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return file; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupFileHeader(int, String) */ public CmsBackupResource readBackupFileHeader(int tagId, String resourcePath) throws CmsException { CmsBackupResource file = null; ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_READ_BACKUP"); stmt.setString(1, resourcePath); stmt.setInt(2, tagId); res = stmt.executeQuery(); if (res.next()) { file = createBackupResource(res, false); while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } else { throw new CmsVfsResourceNotFoundException("[" + this.getClass().getName() + "] " + resourcePath.toString()); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (CmsException ex) { throw ex; } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return file; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupFileHeaders() */ public List readBackupFileHeaders() throws CmsException { CmsBackupResource currentBackupResource = null; ResultSet res = null; List allHeaders = new ArrayList(); PreparedStatement stmt = null; Connection conn = null; Set storage = new HashSet(); try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_READ_ALL_BACKUP"); res = stmt.executeQuery(); while (res.next()) { currentBackupResource = createBackupResource(res, false); // only add each structureId x resourceId combination once String key = currentBackupResource.getStructureId().toString() + currentBackupResource.getResourceId().toString(); if (!storage.contains(key)) { // no entry found, so add it allHeaders.add(currentBackupResource); storage.add(key); } } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception exc) { throw new CmsException("readAllBackupFileHeaders " + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { m_sqlManager.closeAll(conn, stmt, res); storage = null; } return allHeaders; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupFileHeaders(String) */ public List readBackupFileHeaders(String resourcePath) throws CmsException { CmsBackupResource currentBackupResource = null; ResultSet res = null; List allHeaders = new ArrayList(); PreparedStatement stmt = null; Connection conn = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_READ_ALL_VERSIONS_BACKUP"); stmt.setString(1, resourcePath); res = stmt.executeQuery(); while (res.next()) { currentBackupResource = createBackupResource(res, false); allHeaders.add(currentBackupResource); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception exc) { throw new CmsException("readAllBackupFileHeaders " + exc.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, exc); } finally { m_sqlManager.closeAll(conn, stmt, res); } return allHeaders; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupMaxVersion(org.opencms.util.CmsUUID) */ public int readBackupMaxVersion(CmsUUID resourceId) throws CmsException { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; int maxBackupVersion = 0; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_HISTORY_RESOURCE_MAX_BACKUP_VERSION"); stmt.setString(1, resourceId.toString()); res = stmt.executeQuery(); if (res.next()) { maxBackupVersion = res.getInt(1); } else { maxBackupVersion = 0; } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return maxBackupVersion; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupProject(int) */ public CmsBackupProject readBackupProject(int tagId) throws CmsException { PreparedStatement stmt = null; CmsBackupProject project = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READBYVERSION_BACKUP"); stmt.setInt(1, tagId); res = stmt.executeQuery(); if (res.next()) { Vector projectresources = readBackupProjectResources(tagId); project = new CmsBackupProject( res.getInt("PUBLISH_TAG"), res.getInt(m_sqlManager.readQuery("C_PROJECTS_PROJECT_ID")), res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_NAME")), res.getString(m_sqlManager.readQuery("C_PROJECTS_PROJECT_DESCRIPTION")), res.getInt(m_sqlManager.readQuery("C_PROJECTS_TASK_ID")), new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_USER_ID"))), new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_GROUP_ID"))), new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROJECTS_MANAGERGROUP_ID"))), res.getLong(m_sqlManager.readQuery("C_PROJECTS_DATE_CREATED")), res.getInt(m_sqlManager.readQuery("C_PROJECTS_PROJECT_TYPE")), CmsDbUtil.getTimestamp(res, "PROJECT_PUBLISHDATE"), new CmsUUID(res.getString("PROJECT_PUBLISHED_BY")), res.getString("PROJECT_PUBLISHED_BY_NAME"), res.getString("USER_NAME"), res.getString("GROUP_NAME"), res.getString("MANAGERGROUP_NAME"), projectresources); } else { // project not found! throw new CmsException("[" + this.getClass().getName() + "] version " + tagId, CmsException.C_NOT_FOUND); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return project; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupProjectResources(int) */ public Vector readBackupProjectResources(int tagId) throws CmsException { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; Vector projectResources = new Vector(); try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_READ_BACKUP"); stmt.setInt(1, tagId); res = stmt.executeQuery(); while (res.next()) { projectResources.addElement(res.getString("RESOURCE_PATH")); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return projectResources; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupProjects() */ public Vector readBackupProjects() throws CmsException { Vector projects = new Vector(); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { // create the statement conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READLAST_BACKUP"); res = stmt.executeQuery(); int i = 0; int max = 300; while (res.next() && (i < max)) { Vector resources = readBackupProjectResources(res.getInt("PUBLISH_TAG")); projects.addElement( new CmsBackupProject( res.getInt("PUBLISH_TAG"), res.getInt("PROJECT_ID"), res.getString("PROJECT_NAME"), res.getString("PROJECT_DESCRIPTION"), res.getInt("TASK_ID"), new CmsUUID(res.getString("USER_ID")), new CmsUUID(res.getString("GROUP_ID")), new CmsUUID(res.getString("MANAGERGROUP_ID")), res.getLong("DATE_CREATED"), res.getInt("PROJECT_TYPE"), CmsDbUtil.getTimestamp(res, "PROJECT_PUBLISHDATE"), new CmsUUID(res.getString("PROJECT_PUBLISHED_BY")), res.getString("PROJECT_PUBLISHED_BY_NAME"), res.getString("USER_NAME"), res.getString("GROUP_NAME"), res.getString("MANAGERGROUP_NAME"), resources)); i++; } } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return (projects); } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupProjectTag(long) */ public int readBackupProjectTag(long maxdate) throws CmsException { ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; int maxVersion = 0; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_BACKUP_READ_MAXVERSION"); stmt.setTimestamp(1, new Timestamp(maxdate)); res = stmt.executeQuery(); if (res.next()) { maxVersion = res.getInt(1); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return maxVersion; } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupProperties(org.opencms.file.CmsBackupResource) */ public List readBackupProperties(CmsBackupResource resource) throws CmsException { ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; String propertyKey = null; String propertyValue = null; int mappingType = -1; Map propertyMap = new HashMap(); CmsProperty property = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_READALL_BACKUP"); stmt.setString(1, resource.getStructureId().toString()); stmt.setString(2, resource.getResourceId().toString()); stmt.setInt(3, I_CmsConstants.C_PROPERYDEFINITION_RESOURCE); stmt.setInt(4, resource.getTagId()); res = stmt.executeQuery(); while (res.next()) { propertyKey = res.getString(1); propertyValue = res.getString(2); mappingType = res.getInt(3); if ((property = (CmsProperty)propertyMap.get(propertyKey)) != null) { // there exists already a property for this key in the result if (mappingType == CmsProperty.C_STRUCTURE_RECORD_MAPPING) { // this property value is mapped to a structure record property.setStructureValue(propertyValue); } else if (mappingType == CmsProperty.C_RESOURCE_RECORD_MAPPING) { // this property value is mapped to a resource record property.setResourceValue(propertyValue); } else { throw new CmsException( "Unknown property value mapping type found: " + mappingType, CmsException.C_UNKNOWN_EXCEPTION); } } else { // there doesn't exist a property for this key yet property = new CmsProperty(); property.setKey(propertyKey); if (mappingType == CmsProperty.C_STRUCTURE_RECORD_MAPPING) { // this property value is mapped to a structure record property.setStructureValue(propertyValue); property.setResourceValue(null); } else if (mappingType == CmsProperty.C_RESOURCE_RECORD_MAPPING) { // this property value is mapped to a resource record property.setStructureValue(null); property.setResourceValue(propertyValue); } else { throw new CmsException( "Unknown property value mapping type found: " + mappingType, CmsException.C_UNKNOWN_EXCEPTION); } propertyMap.put(propertyKey, property); } } } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return new ArrayList(propertyMap.values()); } /** * @see org.opencms.db.I_CmsBackupDriver#readBackupPropertyDefinition(java.lang.String, int) */ public CmsPropertydefinition readBackupPropertyDefinition(String name, int mappingtype) throws CmsException { CmsPropertydefinition propDef = null; ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTYDEF_READ_BACKUP"); stmt.setString(1, name); stmt.setInt(2, mappingtype); res = stmt.executeQuery(); if (res.next()) { propDef = new CmsPropertydefinition(new CmsUUID(res.getString(m_sqlManager.readQuery("C_PROPERTYDEF_ID"))), res.getString(m_sqlManager.readQuery("C_PROPERTYDEF_NAME")), res.getInt(m_sqlManager.readQuery("C_PROPERTYDEF_PROPERTYDEF_MAPPING_TYPE"))); } else { throw new CmsException("[" + this.getClass().getName() + ".readBackupPropertyDefinition] " + name, CmsException.C_NOT_FOUND); } } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return propDef; } /** * @see org.opencms.db.I_CmsBackupDriver#readNextBackupTagId() */ public int readNextBackupTagId() { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; int versionId = 1; int resVersionId = 1; try { // get the max version id conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_BACKUP_MAXTAG"); res = stmt.executeQuery(); if (res.next()) { versionId = res.getInt(1) + 1; } m_sqlManager.closeAll(null, stmt, res); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_BACKUP_MAXTAG_RESOURCE"); res = stmt.executeQuery(); if (res.next()) { resVersionId = res.getInt(1) + 1; } if (resVersionId > versionId) { versionId = resVersionId; } return versionId; } catch (SQLException exc) { return 1; } finally { m_sqlManager.closeAll(conn, stmt, res); } } /** * @see org.opencms.db.I_CmsBackupDriver#writeBackupProject(org.opencms.file.CmsProject, int, long, org.opencms.file.CmsUser) */ public void writeBackupProject(CmsProject currentProject, int tagId, long publishDate, CmsUser currentUser) throws CmsException { Connection conn = null; PreparedStatement stmt = null; String ownerName = new String(); String group = new String(); String managerGroup = new String(); CmsUser owner = m_driverManager.readUser(currentProject.getOwnerId()); ownerName = owner.getName() + " " + owner.getFirstname() + " " + owner.getLastname(); try { group = m_driverManager.getUserDriver().readGroup(currentProject.getGroupId()).getName(); } catch (CmsException e) { // the group could not be read group = ""; } try { managerGroup = m_driverManager.getUserDriver().readGroup(currentProject.getManagerGroupId()).getName(); } catch (CmsException e) { // the group could not be read managerGroup = ""; } List projectresources = m_driverManager.getProjectDriver().readProjectResources(currentProject); // write backup project to the database try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_CREATE_BACKUP"); // first write the project stmt.setInt(1, tagId); stmt.setInt(2, currentProject.getId()); stmt.setString(3, currentProject.getName()); stmt.setTimestamp(4, new Timestamp(publishDate)); stmt.setString(5, currentUser.getId().toString()); stmt.setString(6, currentUser.getName() + " " + currentUser.getFirstname() + " " + currentUser.getLastname()); stmt.setString(7, currentProject.getOwnerId().toString()); stmt.setString(8, ownerName); stmt.setString(9, currentProject.getGroupId().toString()); stmt.setString(10, group); stmt.setString(11, currentProject.getManagerGroupId().toString()); stmt.setString(12, managerGroup); stmt.setString(13, currentProject.getDescription()); stmt.setLong(14, currentProject.getCreateDate()); stmt.setInt(15, currentProject.getType()); stmt.setInt(16, currentProject.getTaskId()); stmt.executeUpdate(); m_sqlManager.closeAll(null, stmt, null); // now write the projectresources stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_CREATE_BACKUP"); Iterator i = projectresources.iterator(); while (i.hasNext()) { stmt.setInt(1, tagId); stmt.setInt(2, currentProject.getId()); stmt.setString(3, (String)i.next()); stmt.executeUpdate(); stmt.clearParameters(); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * @see org.opencms.db.I_CmsBackupDriver#writeBackupProperties(org.opencms.file.CmsProject, org.opencms.file.CmsResource, java.util.List, org.opencms.util.CmsUUID, int, int) */ public void writeBackupProperties(CmsProject publishProject, CmsResource resource, List properties, CmsUUID backupId, int tagId, int versionId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; String key = null; CmsProperty property = null; int mappingType = -1; String value = null; CmsUUID id = null; CmsPropertydefinition propdef = null; try { conn = m_sqlManager.getConnectionForBackup(); Iterator dummy = properties.iterator(); while (dummy.hasNext()) { property = (CmsProperty) dummy.next(); key = property.getKey(); propdef = readBackupPropertyDefinition(key, I_CmsConstants.C_PROPERYDEFINITION_RESOURCE); if (propdef == null) { throw new CmsException("[" + this.getClass().getName() + "] " + key, CmsException.C_NOT_FOUND); } else { for (int i = 0; i < 2; i++) { mappingType = -1; value = null; id = null; if (i == 0) { // write the structure value on the first cycle value = property.getStructureValue(); mappingType = CmsProperty.C_STRUCTURE_RECORD_MAPPING; id = resource.getStructureId(); if (value == null || "".equals(value)) { continue; } } else { // write the resource value on the second cycle value = property.getResourceValue(); mappingType = CmsProperty.C_RESOURCE_RECORD_MAPPING; id = resource.getResourceId(); if (value == null || "".equals(value)) { break; } } stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_CREATE_BACKUP"); stmt.setString(1, backupId.toString()); stmt.setString(2, new CmsUUID().toString()); stmt.setString(3, propdef.getId().toString()); stmt.setString(4, id.toString()); stmt.setInt(5, mappingType); stmt.setString(6, m_sqlManager.validateEmpty(value)); stmt.setInt(7, tagId); stmt.setInt(8, versionId); stmt.executeUpdate(); m_sqlManager.closeAll(null, stmt, null); } } } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * @see org.opencms.db.I_CmsBackupDriver#writeBackupResource(org.opencms.file.CmsUser, org.opencms.file.CmsProject, org.opencms.file.CmsResource, java.util.List, int, long, int) */ public void writeBackupResource(CmsUser currentUser, CmsProject publishProject, CmsResource resource, List properties, int tagId, long publishDate, int maxVersions) throws CmsException { Connection conn = null; PreparedStatement stmt = null; CmsUUID backupPkId = new CmsUUID(); int versionId; String lastModifiedName = ""; String createdName = ""; try { CmsUser lastModified = m_driverManager.getUserDriver().readUser(resource.getUserLastModified()); lastModifiedName = lastModified.getName(); CmsUser created = m_driverManager.getUserDriver().readUser(resource.getUserCreated()); createdName = created.getName(); } catch (CmsException e) { lastModifiedName = resource.getUserCreated().toString(); createdName = resource.getUserLastModified().toString(); } try { conn = m_sqlManager.getConnectionForBackup(); // now get the new version id for this resource versionId = internalReadNextVersionId(resource); if (resource.isFile()) { if (!this.internalValidateBackupResource(resource, tagId)) { // write the file content if any internalWriteBackupFileContent(backupPkId, resource, tagId, versionId); // write the resource stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_WRITE_BACKUP"); stmt.setString(1, resource.getResourceId().toString()); stmt.setInt(2, resource.getTypeId()); stmt.setInt(3, resource.getFlags()); stmt.setLong(4, publishDate); stmt.setString(5, resource.getUserCreated().toString()); stmt.setLong(6, resource.getDateLastModified()); stmt.setString(7, resource.getUserLastModified().toString()); stmt.setInt(8, resource.getState()); stmt.setInt(9, resource.getLength()); stmt.setInt(10, publishProject.getId()); stmt.setInt(11, 1); stmt.setInt(12, tagId); stmt.setInt(13, versionId); stmt.setString(14, backupPkId.toString()); stmt.setString(15, createdName); stmt.setString(16, lastModifiedName); stmt.executeUpdate(); m_sqlManager.closeAll(null, stmt, null); } } // write the structure stmt = m_sqlManager.getPreparedStatement(conn, "C_STRUCTURE_WRITE_BACKUP"); stmt.setString(1, resource.getStructureId().toString()); stmt.setString(2, resource.getResourceId().toString()); stmt.setString(3, resource.getRootPath()); stmt.setInt(4, resource.getState()); stmt.setLong(5, resource.getDateReleased()); stmt.setLong(6, resource.getDateExpired()); stmt.setInt(7, tagId); stmt.setInt(8, versionId); stmt.setString(9, backupPkId.toString()); stmt.executeUpdate(); writeBackupProperties(publishProject, resource, properties, backupPkId, tagId, versionId); // now check if there are old backup versions to delete List existingBackups = readBackupFileHeaders(resource.getRootPath()); if (existingBackups.size() > maxVersions) { // delete redundant backups deleteBackups(existingBackups, maxVersions); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } // TODO: use this in later versions //return this.readBackupFileHeader(tagId, resource.getResourceId()); } /** * @see org.opencms.db.I_CmsBackupDriver#writeBackupResourceContent(int, org.opencms.file.CmsResource, org.opencms.file.CmsBackupResource) */ public void writeBackupResourceContent(int projectId, CmsResource resource, CmsBackupResource backupResource) throws CmsException { if (!this.internalValidateBackupResource(resource, backupResource.getTagId())) { // internalWriteBackupFileContent(backupResource.getBackupId(), resource.getFileId(), offlineFile.getContents(), backupResource.getTagId(), backupResource.getVersionId()); internalWriteBackupFileContent(backupResource.getBackupId(), resource, backupResource.getTagId(), backupResource.getVersionId()); } } /** * @see org.opencms.db.I_CmsBackupDriver#readMaxTagId(org.opencms.file.CmsResource) */ public int readMaxTagId(CmsResource resource) throws CmsException { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; int result = 0; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_READ_MAX_PUBLISH_TAG"); stmt.setString(1, resource.getResourceId().toString()); res = stmt.executeQuery(); if (res.next()) { result = res.getInt(1); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw new CmsException("readMaxTagId " + e.getMessage(), CmsException.C_UNKNOWN_EXCEPTION, e); } finally { m_sqlManager.closeAll(conn, stmt, res); } return result; } }
package org.openid4java.server; import com.google.inject.Inject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.OpenIDException; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import org.openid4java.association.AssociationSessionType; import org.openid4java.association.DiffieHellmanSession; import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.message.*; import org.openid4java.util.HttpFetcherFactory; import java.net.MalformedURLException; import java.net.URL; /** * Manages OpenID communications with an OpenID Relying Party (Consumer). * * @author Marius Scurtescu, Johnny Bufu */ public class ServerManager { private static Log _log = LogFactory.getLog(ServerManager.class); private static final boolean DEBUG = _log.isDebugEnabled(); /** * Keeps track of the associations established with consumer sites. * * MUST be a different store than ServerAssociationStore#_privateAssociations, * otherwise openid responses can be forged and user accounts hijacked. */ private ServerAssociationStore _sharedAssociations = new InMemoryServerAssociationStore(); /** * Keeps track of private (internal) associations created for signing * authentication responses for stateless consumer sites. * * MUST be a different store than ServerAssociationStore#_sharedAssociations, * otherwise openid responses can be forged and user accounts hijacked. */ private ServerAssociationStore _privateAssociations = new InMemoryServerAssociationStore(); /** * Flag for checking that shared associations are not accepted as or mixed with * the private ones. * * Default true: check is performed at the expense of one extra association store query * to ensure that ServerManager#_sharedAssociations and ServerManager#_privateAssociations * are different store/instances. */ private boolean _checkPrivateSharedAssociations = true; /** * Nonce generator implementation. */ private NonceGenerator _nonceGenerator = new IncrementalNonceGenerator(); /** * The lowest encryption level session accepted for association sessions */ private AssociationSessionType _minAssocSessEnc = AssociationSessionType.NO_ENCRYPTION_SHA1MAC; /** * The preferred association session type; will be attempted first. */ private AssociationSessionType _prefAssocSessEnc = AssociationSessionType.DH_SHA256; /** * Expiration time (in seconds) for associations. */ private int _expireIn = 1800; /** * In OpenID 1.x compatibility mode, the URL at the OpenID Provider where * the user should be directed when a immediate authentication request * fails. * <p> * If not configured, the OP endpoint URL is used. */ private String _userSetupUrl = null; /** * List of coma-separated fields to be signed in authentication responses. */ private String _signFields; /** * Array of extension namespace URIs that the consumer manager will sign, * if present in auth responses. */ private String[] _signExtensions; /** * Used to perform verify realms against return_to URLs. */ private RealmVerifier _realmVerifier; /** * The OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ private String _opEndpointUrl; /** * Gets the store implementation used for keeping track of the generated * associations established with consumer sites. * * @see ServerAssociationStore */ public ServerAssociationStore getSharedAssociations() { return _sharedAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated associations established with consumer sites. * * @param sharedAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setSharedAssociations(ServerAssociationStore sharedAssociations) { _sharedAssociations = sharedAssociations; } /** * Gets the store implementation used for keeping track of the generated * private associations (used for signing responses to stateless consumer * sites). * * @see ServerAssociationStore */ public ServerAssociationStore getPrivateAssociations() { return _privateAssociations; } /** * Sets the store implementation that will be used for keeping track of * the generated private associations (used for signing responses to * stateless consumer sites). * * @param privateAssociations ServerAssociationStore implementation * @see ServerAssociationStore */ public void setPrivateAssociations(ServerAssociationStore privateAssociations) { _privateAssociations = privateAssociations; } /** * Gets the _checkPrivateSharedAssociations flag. * * @see ServerManager#_checkPrivateSharedAssociations */ public boolean isCheckPrivateSharedAssociations() { return _checkPrivateSharedAssociations; } /** * Sets the _checkPrivateSharedAssociations flag. * * @see ServerManager#_checkPrivateSharedAssociations */ public void setCheckPrivateSharedAssociations(boolean _checkPrivateSharedAssociations) { this._checkPrivateSharedAssociations = _checkPrivateSharedAssociations; } /** * Gets the minimum level of encryption configured for association sessions. * <p> * Default: no-encryption session, SHA1 MAC association */ public AssociationSessionType getMinAssocSessEnc() { return _minAssocSessEnc; } /** * Gets the NonceGenerator used for generating nonce tokens to uniquely * identify authentication responses. * * @see NonceGenerator */ public NonceGenerator getNonceGenerator() { return _nonceGenerator; } /** * Sets the NonceGenerator implementation that will be used to generate * nonce tokens to uniquely identify authentication responses. * * @see NonceGenerator */ public void setNonceGenerator(NonceGenerator nonceGenerator) { _nonceGenerator = nonceGenerator; } /** * Configures the minimum level of encryption accepted for association * sessions. * <p> * Default: no-encryption session, SHA1 MAC association */ public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc) { this._minAssocSessEnc = minAssocSessEnc; } /** * Gets the preferred association / session type. */ public AssociationSessionType getPrefAssocSessEnc() { return _prefAssocSessEnc; } /** * Sets the preferred association / session type. * * @see AssociationSessionType */ public void setPrefAssocSessEnc(AssociationSessionType type) throws ServerException { if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) ) throw new ServerException("Unsupported association / session type: " + type.getSessionType() + " : " + type.getAssociationType()); if (_minAssocSessEnc.isBetter(type) ) throw new ServerException( "Minimum encryption settings cannot be better than the preferred"); this._prefAssocSessEnc = type; } /** * Gets the expiration time (in seconds) for the generated associations */ public int getExpireIn() { return _expireIn; } /** * Sets the expiration time (in seconds) for the generated associations */ public void setExpireIn(int _expireIn) { this._expireIn = _expireIn; } /** * Gets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public String getUserSetupUrl() { return _userSetupUrl; } /** * Sets the URL at the OpenID Provider where the user should be directed * when a immediate authentication request fails. */ public void setUserSetupUrl(String userSetupUrl) { this._userSetupUrl = userSetupUrl; } /** * Sets the list of parameters that the OpenID Provider will sign when * generating authentication responses. * <p> * The fields in the list must be coma-separated and must not include the * 'openid.' prefix. Fields that are required to be signed are automatically * added by the underlying logic, so that a valid message is generated, * regardles if they are included in the user-supplied list or not. */ public void setSignFields(String signFields) { this._signFields = signFields; } /** * Gets the list of parameters that the OpenID Provider will sign when * generating authentication responses. * <p> * Coma-separated list. */ public String getSignFields() { return _signFields; } public void setSignExtensions(String[] extensins) { _signExtensions = extensins; } public String[] getSignExtensions() { return _signExtensions; } /** * Gets the RealmVerifier used to verify realms against return_to URLs. */ public RealmVerifier getRealmVerifier() { return _realmVerifier; } /** * Sets the RealmVerifier used to verify realms against return_to URLs. */ public void setRealmVerifier(RealmVerifier realmVerifier) { this._realmVerifier = realmVerifier; } /** * Gets the flag that instructs the realm verifier to enforce validation * of the return URL agains the endpoints discovered from the RP's realm. */ public boolean getEnforceRpId() { return _realmVerifier.getEnforceRpId(); } /** * Sets the flag that instructs the realm verifier to enforce validation * of the return URL agains the endpoints discovered from the RP's realm. */ public void setEnforceRpId(boolean enforceRpId) { _realmVerifier.setEnforceRpId(enforceRpId); } /** * Gets OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public String getOPEndpointUrl() { return _opEndpointUrl; } /** * Sets the OpenID Provider's endpoint URL, where it accepts OpenID * authentication requests. * <p> * This is a global setting for the ServerManager; can also be set on a * per message basis. * * @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String) */ public void setOPEndpointUrl(String opEndpointUrl) { this._opEndpointUrl = opEndpointUrl; } /** * Constructs a ServerManager with default settings. */ public ServerManager() { this(new RealmVerifierFactory(new YadisResolver(new HttpFetcherFactory()))); } @Inject public ServerManager(RealmVerifierFactory factory) { // initialize a default realm verifier _realmVerifier = factory.getRealmVerifierForServer(); _realmVerifier.setEnforceRpId(false); } /** * Processes a Association Request and returns a Association Response * message, according to the request parameters and the preferences * configured for the OpenID Provider * * @return AssociationResponse upon successfull association, * or AssociationError if no association * was established * */ public Message associationResponse(ParameterList requestParams) { boolean isVersion2 = requestParams.hasParameter("openid.ns"); _log.info("Processing association request..."); try { // build request message from response params (+ integrity check) AssociationRequest assocReq = AssociationRequest.createAssociationRequest(requestParams); isVersion2 = assocReq.isVersion2(); AssociationSessionType type = assocReq.getType(); // is supported / allowed ? if (! Association.isHmacSupported(type.getAssociationType()) || ! DiffieHellmanSession.isDhSupported(type) || _minAssocSessEnc.isBetter(type)) { throw new AssociationException("Unable create association for: " + type.getSessionType() + " / " + type.getAssociationType() ); } else // all ok, go ahead { Association assoc = _sharedAssociations.generate( type.getAssociationType(), _expireIn); _log.info("Returning shared association; handle: " + assoc.getHandle()); return AssociationResponse.createAssociationResponse(assocReq, assoc); } } catch (OpenIDException e) { // association failed, respond accordingly if (isVersion2) { _log.warn("Cannot establish association, " + "responding with an OpenID2 association error.", e); return AssociationError.createAssociationError( e.getMessage(), _prefAssocSessEnc); } else { _log.warn("Error processing an OpenID1 association request: " + e.getMessage() + " Responding with a dummy association.", e); try { // generate dummy association & no-encryption response // for compatibility mode Association dummyAssoc = _sharedAssociations.generate( Association.TYPE_HMAC_SHA1, 0); AssociationRequest dummyRequest = AssociationRequest.createAssociationRequest( AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC); return AssociationResponse.createAssociationResponse( dummyRequest, dummyAssoc); } catch (OpenIDException ee) { _log.error("Error creating negative OpenID1 association response.", e); return null; } } } } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return An signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, true); } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved) { return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, true); } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return A positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, boolean signNow) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, signNow); } /** * Processes a Authentication Request received from a consumer site. * <p> * Uses ServerManager's global OpenID Provider endpoint URL. * * @return A positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, boolean signNow) { return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, _opEndpointUrl, signNow); } /** * Processes a Authentication Request received from a consumer site. * <p> * * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.ParameterList, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint) { return authResponse(requestParams, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, true); } /** * Processes a Authentication Request received from a consumer site. * <p> * * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(AuthRequest auhtReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint) { return authResponse(auhtReq, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, true); } /** * Processes a Authentication Request received from a consumer site, * after parsing the request parameters into a valid AuthRequest. * <p> * * @return A signed positive Authentication Response if successfull, * or an IndirectError / DirectError message. * @see #authResponse(org.openid4java.message.AuthRequest, String, String, * boolean, String, boolean) */ public Message authResponse(ParameterList requestParams, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint, boolean signNow) { _log.info("Parsing authentication request..."); AuthRequest authReq; boolean isVersion2 = Message.OPENID2_NS.equals( requestParams.getParameterValue("openid.ns")); try { // build request message from response params (+ integrity check) authReq = AuthRequest.createAuthRequest( requestParams, _realmVerifier); return authResponse(authReq, userSelId, userSelClaimed, authenticatedAndApproved, opEndpoint, signNow); } catch (MessageException e) { if (requestParams.hasParameter("openid.return_to")) { _log.error("Invalid authentication request; " + "responding with an indirect error message.", e); return IndirectError.createIndirectError(e, requestParams.getParameterValue("openid.return_to"), ! isVersion2 ); } else { _log.error("Invalid authentication request; " + "responding with a direct error message.", e); return DirectError.createDirectError( e, ! isVersion2 ); } } } /** * Processes a Authentication Request received from a consumer site. * * @param opEndpoint The endpoint URL where the OP accepts OpenID * authentication requests. * @param authReq A valid authentication request. * @param userSelId OP-specific Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param userSelClaimed Claimed Identifier selected by the user at * the OpenID Provider; if present it will override * the one received in the authentication request. * @param authenticatedAndApproved Flag indicating that the OP has * authenticated the user and the user * has approved the authentication * transaction * @param signNow If true, the returned AuthSuccess will be signed. * If false, the signature will not be computed and * set - this will have to be performed later, * using #sign(org.openid4java.message.Message). * * @return <ul><li> AuthSuccess, if authenticatedAndApproved * <li> AuthFailure (negative response) if either * of authenticatedAndApproved is false; * <li> A IndirectError or DirectError message * if the authentication could not be performed, or * <li> Null if there was no return_to parameter * specified in the AuthRequest.</ul> */ public Message authResponse(AuthRequest authReq, String userSelId, String userSelClaimed, boolean authenticatedAndApproved, String opEndpoint, boolean signNow) { _log.info("Processing authentication request..."); boolean isVersion2 = authReq.isVersion2(); if (authReq.getReturnTo() == null) { _log.error("No return_to in the received (valid) auth request; " + "returning null auth response."); return null; } try { if (authenticatedAndApproved) // positive response { try { new URL(opEndpoint); } catch (MalformedURLException e) { String errMsg = "Invalid OP-endpoint configured; " + "cannot issue authentication responses." + opEndpoint; _log.error(errMsg, e); return DirectError.createDirectError( new ServerException(errMsg, e), isVersion2); } String id; String claimed; if (AuthRequest.SELECT_ID.equals(authReq.getIdentity())) { id = userSelId; claimed = userSelClaimed; } else { id = userSelId != null ? userSelId : authReq.getIdentity(); claimed = userSelClaimed != null ? userSelClaimed : authReq.getClaimed(); } if (id == null) throw new ServerException( "No identifier provided by the authentication request " + "or by the OpenID Provider"); if (DEBUG) _log.debug("Using ClaimedID: " + claimed + " OP-specific ID: " + id); Association assoc = null; String handle = authReq.getHandle(); String invalidateHandle = null; if (handle != null) { assoc = _sharedAssociations.load(handle); if (assoc == null) { _log.info("Invalidating handle: " + handle); invalidateHandle = handle; } else _log.info("Loaded shared association; handle: " + handle); } if (assoc == null) { assoc = _privateAssociations.generate( _prefAssocSessEnc.getAssociationType(), _expireIn); _log.info("Generated private association; handle: " + assoc.getHandle()); } AuthSuccess response = AuthSuccess.createAuthSuccess( opEndpoint, claimed, id, !isVersion2, authReq.getReturnTo(), isVersion2 ? _nonceGenerator.next() : null, invalidateHandle, assoc, false); if (_signFields != null) response.setSignFields(_signFields); if (_signExtensions != null) response.setSignExtensions(_signExtensions); if (signNow) response.setSignature(assoc.sign(response.getSignedText())); _log.info("Returning positive assertion for " + response.getReturnTo()); return response; } else // negative response { if (authReq.isImmediate()) { _log.error("Responding with immediate authentication " + "failure to " + authReq.getReturnTo()); authReq.setImmediate(false); String userSetupUrl = _userSetupUrl == null ? opEndpoint : _userSetupUrl; userSetupUrl += (userSetupUrl.contains("?") ? "&" : "?") + authReq.wwwFormEncoding(); return AuthImmediateFailure.createAuthImmediateFailure( userSetupUrl, authReq.getReturnTo(), ! isVersion2); } else { _log.error("Responding with authentication failure to " + authReq.getReturnTo()); return new AuthFailure(! isVersion2, authReq.getReturnTo()); } } } catch (OpenIDException e) { if (authReq.hasParameter("openid.return_to")) { _log.error("Error processing authentication request; " + "responding with an indirect error message.", e); return IndirectError.createIndirectError(e, authReq.getReturnTo(), ! isVersion2 ); } else { _log.error("Error processing authentication request; " + "responding with a direct error message.", e); return DirectError.createDirectError( e, ! isVersion2 ); } } } /** * Signs an AuthSuccess message, using the association identified by the * handle specified within the message. * * @param authSuccess The Authentication Success message to be signed. * * @throws ServerException If the Association corresponding to the handle * in the @authSuccess cannot be retrieved from * the store. * @throws AssociationException If the signature cannot be computed. * */ public void sign(AuthSuccess authSuccess) throws ServerException, AssociationException { String handle = authSuccess.getHandle(); // try shared associations first, then private Association assoc = _sharedAssociations.load(handle); if (assoc == null) assoc = _privateAssociations.load(handle); if (assoc == null) throw new ServerException( "No association found for handle: " + handle); authSuccess.setSignature(assoc.sign(authSuccess.getSignedText())); } /** * Responds to a verification request from the consumer. * * @param requestParams ParameterList containing the parameters received * in a verification request from a consumer site. * @return VerificationResponse to be sent back to the * consumer site. */ public Message verify(ParameterList requestParams) { _log.info("Processing verification request..."); boolean isVersion2 = true; try { // build request message from response params (+ ntegrity check) VerifyRequest vrfyReq = VerifyRequest.createVerifyRequest(requestParams); isVersion2 = vrfyReq.isVersion2(); String handle = vrfyReq.getHandle(); boolean verified = false; Association assoc = _privateAssociations.load(handle); if (_checkPrivateSharedAssociations && _sharedAssociations.load(handle) != null) { _log.warn("association for handle: " + handle + " expected to be private " + "but was found in shared association store, denying direct verification request; " + "please configure different association store/instances for private vs shared associations"); } else if (assoc != null) { // verify the signature _log.info("Loaded private association; handle: " + handle); verified = assoc.verifySignature( vrfyReq.getSignedText(), vrfyReq.getSignature()); // remove the association so that the request // cannot be verified more than once _privateAssociations.remove(handle); } VerifyResponse vrfyResp = VerifyResponse.createVerifyResponse(! vrfyReq.isVersion2()); vrfyResp.setSignatureVerified(verified); if (verified) { String invalidateHandle = vrfyReq.getInvalidateHandle(); if (invalidateHandle != null && _sharedAssociations.load(invalidateHandle) == null) { _log.info("Confirming shared association invalidate handle: " + invalidateHandle); vrfyResp.setInvalidateHandle(invalidateHandle); } } else _log.error("Signature verification failed, handle: " + handle); _log.info("Responding with " + (verified? "positive" : "negative") + " verification response"); return vrfyResp; } catch (OpenIDException e) { _log.error("Error processing verification request; " + "responding with verification error.", e); return DirectError.createDirectError(e, ! isVersion2); } } }
package org.pentaho.di.trans.steps.sql; import java.util.ArrayList; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Execute one or more SQL statements in a script, one time or parameterised * (for every row) * * @author Matt * @since 10-sep-2005 */ public class ExecSQL extends BaseStep implements StepInterface { private ExecSQLMeta meta; private ExecSQLData data; public ExecSQL(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public static final RowMetaAndData getResultRow(Result result, String upd, String ins, String del, String read) { RowMetaAndData resultRow = new RowMetaAndData(); if (upd != null && upd.length() > 0) { ValueMeta meta = new ValueMeta(upd, ValueMetaInterface.TYPE_INTEGER); meta.setLength(9); resultRow.addValue(meta, new Long(result.getNrLinesUpdated())); } if (ins != null && ins.length() > 0) { ValueMeta meta = new ValueMeta(ins, ValueMetaInterface.TYPE_INTEGER); meta.setLength(9); resultRow.addValue(meta, new Long(result.getNrLinesOutput())); } if (del != null && del.length() > 0) { ValueMeta meta = new ValueMeta(del, ValueMetaInterface.TYPE_INTEGER); meta.setLength(9); resultRow.addValue(meta, new Long(result.getNrLinesDeleted())); } if (read != null && read.length() > 0) { ValueMeta meta = new ValueMeta(read, ValueMetaInterface.TYPE_INTEGER); meta.setLength(9); resultRow.addValue(meta, new Long(result.getNrLinesRead())); } return resultRow; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (ExecSQLMeta) smi; data = (ExecSQLData) sdi; if (!meta.isExecutedEachInputRow()) { RowMetaAndData resultRow = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); putRow(resultRow.getRowMeta(), resultRow.getData()); setOutputDone(); // Stop processing, this is all we do! return false; } Object[] row = getRow(); if (row == null) // no more input to be expected... { setOutputDone(); return false; } if (first) // we just got started { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // Find the indexes of the arguments data.argumentIndexes = new int[meta.getArguments().length]; for (int i = 0; i < meta.getArguments().length; i++) { data.argumentIndexes[i] = this.getInputRowMeta().indexOfValue(meta.getArguments()[i]); if (data.argumentIndexes[i] < 0) { logError(Messages.getString("ExecSQL.Log.ErrorFindingField") + meta.getArguments()[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(Messages.getString("ExecSQL.Exception.CouldNotFindField", meta.getArguments()[i])); //$NON-NLS-1$ //$NON-NLS-2$ } } // Find the locations of the question marks in the String... // We replace the question marks with the values... // We ignore quotes etc. to make inserts easier... data.markerPositions = new ArrayList<Integer>(); int len = data.sql.length(); int pos = len - 1; while (pos >= 0) { if (data.sql.charAt(pos) == '?') data.markerPositions.add(new Integer(pos)); // save the // marker // position pos } } String sql; int numMarkers = data.markerPositions.size(); if (numMarkers > 0) { StringBuffer buf = new StringBuffer(data.sql); // Replace the values in the SQL string... for (int i=0;i<numMarkers;i++) { // Get the appropriate value from the input row... int index = data.argumentIndexes[data.markerPositions.size() - i - 1]; ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta( index ); Object valueData = row[ index ]; // replace the '?' with the String in the row. int pos = data.markerPositions.get(i); buf.replace(pos, pos + 1, valueMeta.getString(valueData)); } sql = buf.toString(); } else { sql = data.sql; } if (log.isRowLevel()) logRowlevel(Messages.getString("ExecSQL.Log.ExecutingSQLScript") + Const.CR + data.sql); //$NON-NLS-1$ data.result = data.db.execStatements(sql.toString()); RowMetaAndData add = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); row = RowDataUtil.addRowData(row, getInputRowMeta().size(), add.getData()); if (!data.db.isAutoCommit()) { data.db.commit(); } putRow(data.outputRowMeta,row); // send it out! if (checkFeedback(linesWritten)) logBasic(Messages.getString("ExecSQL.Log.LineNumber") + linesWritten); //$NON-NLS-1$ return true; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExecSQLMeta) smi; data = (ExecSQLData) sdi; logBasic(Messages.getString("ExecSQL.Log.FinishingReadingQuery")); //$NON-NLS-1$ data.db.disconnect(); super.dispose(smi, sdi); } /** Stop the running query */ public void stopRunning(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (ExecSQLMeta) smi; data = (ExecSQLData) sdi; if (data.db != null) data.db.cancelQuery(); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExecSQLMeta) smi; data = (ExecSQLData) sdi; if (super.init(smi, sdi)) { data.db = new Database(meta.getDatabaseMeta()); data.db.shareVariablesWith(this); // Connect to the database try { if (getTransMeta().isUsingUniqueConnections()) { synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); } } else { data.db.connect(getPartitionID()); } if (log.isDetailed()) logDetailed(Messages.getString("ExecSQL.Log.ConnectedToDB")); //$NON-NLS-1$ if (meta.isReplaceVariables()) { data.sql = environmentSubstitute(meta.getSql()); } else { data.sql = meta.getSql(); } // If the SQL needs to be executed once, this is a starting step // somewhere. if (!meta.isExecutedEachInputRow()) { data.result = data.db.execStatements(data.sql); if (!data.db.isAutoCommit()) data.db.commit(); } return true; } catch (KettleException e) { logError(Messages.getString("ExecSQL.Log.ErrorOccurred") + e.getMessage()); //$NON-NLS-1$ setErrors(1); stopAll(); } } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package org.languagetool.rules.patterns; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.FakeLanguage; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import org.languagetool.MultiThreadedJLanguageTool; import org.languagetool.TestTools; import org.languagetool.XMLValidator; import org.languagetool.rules.Category; import org.languagetool.rules.CorrectExample; import org.languagetool.rules.ErrorTriggeringExample; import org.languagetool.rules.IncorrectExample; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule; /** * @author Daniel Naber */ public class PatternRuleTest extends AbstractPatternRuleTest { // A test sentence should only be a single sentence - if that's not the case it can // happen that rules are checked as being correct that in reality will never match. // This check prints a warning for affected rules, but it's disabled by default because // it makes the tests very slow: private static final boolean CHECK_WITH_SENTENCE_SPLITTING = false; private static final Pattern PATTERN_MARKER_START = Pattern.compile(".*<pattern[^>]*>\\s*<marker>.*", Pattern.DOTALL); private static final Pattern PATTERN_MARKER_END = Pattern.compile(".*</marker>\\s*</pattern>.*", Pattern.DOTALL); private static final Comparator<Match> MATCH_COMPARATOR = (m1, m2) -> Integer.compare( m1.getTokenRef(), m2.getTokenRef()); public void testFake() { // there's no test here - the languages are supposed to extend this class and call runGrammarRulesFromXmlTest() } @Test public void testSupportsLanguage() { FakeLanguage fakeLanguage1 = new FakeLanguage("yy"); FakeLanguage fakeLanguage2 = new FakeLanguage("zz"); PatternRule patternRule1 = new PatternRule("ID", fakeLanguage1, Collections.<PatternToken>emptyList(), "", "", ""); assertTrue(patternRule1.supportsLanguage(fakeLanguage1)); assertFalse(patternRule1.supportsLanguage(fakeLanguage2)); FakeLanguage fakeLanguage1WithVariant1 = new FakeLanguage("zz", "VAR1"); FakeLanguage fakeLanguage1WithVariant2 = new FakeLanguage("zz", "VAR2"); PatternRule patternRuleVariant1 = new PatternRule("ID", fakeLanguage1WithVariant1, Collections.<PatternToken>emptyList(), "", "", ""); assertTrue(patternRuleVariant1.supportsLanguage(fakeLanguage1WithVariant1)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage1)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage2)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage1WithVariant2)); } /** * To be called from language modules. Languages.get() knows only the languages that's in the classpath. * @param ignoredLanguage ignore this language - useful to speed up tests from languages that * have another language as a dependency */ protected void runGrammarRulesFromXmlTest(Language ignoredLanguage) throws IOException { int count = 0; for (Language lang : Languages.get()) { if (ignoredLanguage.getShortCodeWithCountryAndVariant().equals(lang.getShortCodeWithCountryAndVariant())) { continue; } runGrammarRuleForLanguage(lang); count++; } if (count == 0) { System.err.println("Warning: no languages found in classpath - cannot run any grammar rule tests"); } } /** * To be called from language modules. Languages.get() only knows the languages that are in the classpath, * and that's only the demo language for languagetool-core. */ protected void runGrammarRulesFromXmlTest() throws IOException { for (Language lang : Languages.get()) { runGrammarRuleForLanguage(lang); } if (Languages.get().isEmpty()) { System.err.println("Warning: no languages found in classpath - cannot run any grammar rule tests"); } } protected void runGrammarRuleForLanguage(Language lang) throws IOException { if (skipCountryVariant(lang)) { System.out.println("Skipping " + lang + " because there are no specific rules for that variant"); return; } runTestForLanguage(lang); } private void runGrammarRulesFromXmlTestIgnoringLanguages(Set<Language> ignoredLanguages) throws IOException { System.out.println("Known languages: " + Languages.getWithDemoLanguage()); for (Language lang : Languages.getWithDemoLanguage()) { if (ignoredLanguages != null && ignoredLanguages.contains(lang)) { continue; } runTestForLanguage(lang); } } public void runTestForLanguage(Language lang) throws IOException { validatePatternFile(lang); System.out.println("Running pattern rule tests for " + lang.getName() + "... "); MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(lang); if (CHECK_WITH_SENTENCE_SPLITTING) { disableSpellingRules(lt); } MultiThreadedJLanguageTool allRulesLt = new MultiThreadedJLanguageTool(lang); validateRuleIds(lang, allRulesLt); validateSentenceStartNotInMarker(allRulesLt); List<AbstractPatternRule> rules = getAllPatternRules(lang, lt); System.out.println("Checking regexp syntax of " + rules.size() + " rules for " + lang + "..."); for (AbstractPatternRule rule : rules) { // Test the rule pattern. /* check for useless 'marker' elements commented out - too slow to always run: PatternRuleXmlCreator creator = new PatternRuleXmlCreator(); String xml = creator.toXML(rule.getPatternRuleId(), lang); if (PATTERN_MARKER_START.matcher(xml).matches() && PATTERN_MARKER_END.matcher(xml).matches()) { System.err.println("WARNING " + lang + ": useless <marker>: " + rule.getFullId()); }*/ // too aggressive for now: //PatternTestTools.failIfWhitespaceInToken(rule.getPatternTokens(), rule, lang); PatternTestTools.warnIfRegexpSyntaxNotKosher(rule.getPatternTokens(), rule.getId(), rule.getSubId(), lang); // Test the rule antipatterns. List<DisambiguationPatternRule> antiPatterns = rule.getAntiPatterns(); for (DisambiguationPatternRule antiPattern : antiPatterns) { PatternTestTools.warnIfRegexpSyntaxNotKosher(antiPattern.getPatternTokens(), antiPattern.getId(), antiPattern.getSubId(), lang); } if (rule.getCorrectExamples().isEmpty()) { boolean correctionExists = false; for (IncorrectExample incorrectExample : rule.getIncorrectExamples()) { if (incorrectExample.getCorrections().size() > 0) { correctionExists = true; break; } } if (!correctionExists) { fail("Rule " + rule.getFullId() + " in language " + lang + " needs at least one <example> with a 'correction' attribute" + " or one <example> of type='correct'."); } } } testGrammarRulesFromXML(rules, lt, allRulesLt, lang); System.out.println(rules.size() + " rules tested."); allRulesLt.shutdown(); lt.shutdown(); } private void validatePatternFile(Language lang) throws IOException { validatePatternFile(getGrammarFileNames(lang)); } protected void validatePatternFile(List<String> grammarFiles) throws IOException { XMLValidator validator = new XMLValidator(); for (String grammarFile : grammarFiles) { System.out.println("Running XML validation for " + grammarFile + "..."); String rulesDir = JLanguageTool.getDataBroker().getRulesDir(); String ruleFilePath = rulesDir + "/" + grammarFile; try (InputStream xmlStream = this.getClass().getResourceAsStream(ruleFilePath)) { if (xmlStream == null) { System.out.println("No rule file found at " + ruleFilePath + " in classpath"); continue; } // if there are multiple xml grammar files we'll prepend all unification elements // from the first file to the rest of them if (grammarFiles.size() > 1 && !grammarFiles.get(0).equals(grammarFile)) { validator.validateWithXmlSchema(rulesDir + "/" + grammarFiles.get(0), ruleFilePath, rulesDir + "/rules.xsd"); } else { validator.validateWithXmlSchema(ruleFilePath, rulesDir + "/rules.xsd"); } } } } private void validateRuleIds(Language lang, JLanguageTool lt) { List<Rule> allRules = lt.getAllRules(); Set<String> categoryIds = new HashSet<>(); new RuleIdValidator(lang).validateUniqueness(); for (Rule rule : allRules) { if (rule.getId().equalsIgnoreCase("ID")) { System.err.println("WARNING: " + lang.getShortCodeWithCountryAndVariant() + " has a rule with id 'ID', this should probably be changed"); } Category category = rule.getCategory(); if (category != null && category.getId() != null) { String catId = category.getId().toString(); if (!catId.matches("[A-Z0-9_-]+") && !categoryIds.contains(catId)) { System.err.println("WARNING: category id '" + catId + "' doesn't match expected regexp [A-Z0-9_-]+"); categoryIds.add(catId); } } } } /* * A <marker> that covers the SENT_START can lead to obscure offset issues, so warn about that. */ private void validateSentenceStartNotInMarker(JLanguageTool lt) { System.out.println("Check that sentence start tag is not included in <marker>...."); List<Rule> rules = lt.getAllRules(); for (Rule rule : rules) { if (rule instanceof AbstractPatternRule) { List<PatternToken> patternTokens = ((AbstractPatternRule) rule).getPatternTokens(); if (patternTokens != null) { boolean hasExplicitMarker = patternTokens.stream().anyMatch(PatternToken::isInsideMarker); for (PatternToken patternToken : patternTokens) { if ((patternToken.isInsideMarker() || !hasExplicitMarker) && patternToken.isSentenceStart()) { System.out.println("WARNING: Sentence start in <marker>: " + ((AbstractPatternRule) rule).getFullId() + " (hasExplicitMarker: " + hasExplicitMarker + ") - please move the <marker> so the SENT_START is not covered"); } } } } } } private void disableSpellingRules(JLanguageTool languageTool) { List<Rule> allRules = languageTool.getAllRules(); for (Rule rule : allRules) { if (rule instanceof SpellingCheckRule) { languageTool.disableRule(rule.getId()); } } } public void testGrammarRulesFromXML(List<AbstractPatternRule> rules, JLanguageTool languageTool, JLanguageTool allRulesLanguageTool, Language lang) throws IOException { System.out.println("Checking example sentences of " + rules.size() + " rules for " + lang + "..."); Map<String, AbstractPatternRule> complexRules = new HashMap<>(); int skipCount = 0; for (AbstractPatternRule rule : rules) { String sourceFile = rule.getSourceFile(); if (lang.isVariant() && sourceFile != null && sourceFile.matches("/org/languagetool/rules/" + lang.getShortCode() + "/grammar.*\\.xml")) { //System.out.println("Skipping " + rule.getFullId() + " in " + sourceFile + " because we're checking a variant"); skipCount++; continue; } testCorrectSentences(languageTool, allRulesLanguageTool, lang, rule); testBadSentences(languageTool, allRulesLanguageTool, lang, complexRules, rule); testErrorTriggeringSentences(languageTool, lang, rule); } System.out.println("Skipped " + skipCount + " rules for variant language to avoid checking rules more than once"); if (!complexRules.isEmpty()) { Set<String> set = complexRules.keySet(); List<AbstractPatternRule> badRules = new ArrayList<>(); for (String aSet : set) { AbstractPatternRule badRule = complexRules.get(aSet); if (badRule instanceof PatternRule) { ((PatternRule)badRule).notComplexPhrase(); badRule.setMessage("The rule contains a phrase that never matched any incorrect example.\n" + ((PatternRule) badRule).toPatternString()); badRules.add(badRule); } } if (!badRules.isEmpty()) { testGrammarRulesFromXML(badRules, languageTool, allRulesLanguageTool, lang); } } } private void testBadSentences(JLanguageTool languageTool, JLanguageTool allRulesLanguageTool, Language lang, Map<String, AbstractPatternRule> complexRules, AbstractPatternRule rule) throws IOException { List<IncorrectExample> badSentences = rule.getIncorrectExamples(); if (badSentences.isEmpty()) { fail("No incorrect examples found for rule " + rule.getFullId()); } // necessary for XML Pattern rules containing <or> List<AbstractPatternRule> rules = allRulesLanguageTool.getPatternRulesByIdAndSubId(rule.getId(), rule.getSubId()); for (IncorrectExample origBadExample : badSentences) { // enable indentation use String origBadSentence = origBadExample.getExample().replaceAll("[\\n\\t]+", ""); List<String> expectedCorrections = origBadExample.getCorrections(); int expectedMatchStart = origBadSentence.indexOf("<marker>"); int expectedMatchEnd = origBadSentence.indexOf("</marker>") - "<marker>".length(); if (expectedMatchStart == -1 || expectedMatchEnd == -1) { fail(lang + ": No error position markup ('<marker>...</marker>') in bad example in rule " + rule.getFullId()); } String badSentence = cleanXML(origBadSentence); assertTrue(badSentence.trim().length() > 0); // necessary for XML Pattern rules containing <or> List<RuleMatch> matches = new ArrayList<>(); for (Rule auxRule : rules) { matches.addAll(getMatches(auxRule, badSentence, languageTool)); } if (rule instanceof RegexPatternRule || rule instanceof PatternRule && !((PatternRule)rule).isWithComplexPhrase()) { if (matches.size() != 1) { AnalyzedSentence analyzedSentence = languageTool.getAnalyzedSentence(badSentence); StringBuilder sb = new StringBuilder("Analyzed token readings:"); for (AnalyzedTokenReadings atr : analyzedSentence.getTokens()) { sb.append(" ").append(atr); } String info = ""; if (rule instanceof RegexPatternRule) { info = "\nRegexp: " + ((RegexPatternRule) rule).getPattern().toString(); } fail(lang + " rule " + rule.getFullId() + ":\n\"" + badSentence + "\"\n" + "Errors expected: 1\n" + "Errors found : " + matches.size() + "\n" + "Message: " + rule.getMessage() + "\n" + sb + "\nMatches: " + matches + info); } int maxReference = 0; if (rule.getSuggestionMatches() != null) { Optional<Match> opt = rule.getSuggestionMatches().stream().max(MATCH_COMPARATOR); maxReference = opt.isPresent() ? opt.get().getTokenRef() : 0; } maxReference = Math.max( rule.getMessage() != null ? findLargestReference(rule.getMessage()) : 0, maxReference); if (rule.getPatternTokens() != null && maxReference > rule.getPatternTokens().size()) { System.err.println("Warning: Rule "+rule.getFullId()+" refers to token \\"+(maxReference)+" but has only "+rule.getPatternTokens().size()+" tokens."); } assertEquals(lang + ": Incorrect match position markup (start) for rule " + rule.getFullId() + ", sentence: " + badSentence, expectedMatchStart, matches.get(0).getFromPos()); assertEquals(lang + ": Incorrect match position markup (end) for rule " + rule.getFullId() + ", sentence: " + badSentence, expectedMatchEnd, matches.get(0).getToPos()); // make sure suggestion is what we expect it to be assertSuggestions(badSentence, lang, expectedCorrections, rule, matches); // make sure the suggested correction doesn't produce an error: if (matches.get(0).getSuggestedReplacements().size() > 0) { int fromPos = matches.get(0).getFromPos(); int toPos = matches.get(0).getToPos(); for (String replacement : matches.get(0).getSuggestedReplacements()) { String fixedSentence = badSentence.substring(0, fromPos) + replacement + badSentence.substring(toPos); matches = getMatches(rule, fixedSentence, languageTool); if (matches.size() > 0) { fail("Incorrect input:\n" + " " + badSentence + "\nCorrected sentence:\n" + " " + fixedSentence + "\nBy Rule:\n" + " " + rule.getFullId() + "\nThe correction triggered an error itself:\n" + " " + matches.get(0) + "\n"); } } } } else { // for multiple rules created with complex phrases matches = getMatches(rule, badSentence, languageTool); if (matches.isEmpty() && !complexRules.containsKey(rule.getId() + badSentence)) { complexRules.put(rule.getId() + badSentence, rule); } if (matches.size() != 0) { complexRules.put(rule.getId() + badSentence, null); assertTrue(lang + ": Did expect one error in: \"" + badSentence + "\" (Rule: " + rule.getFullId() + "), got " + matches.size(), matches.size() == 1); assertEquals(lang + ": Incorrect match position markup (start) for rule " + rule.getFullId(), expectedMatchStart, matches.get(0).getFromPos()); assertEquals(lang + ": Incorrect match position markup (end) for rule " + rule.getFullId(), expectedMatchEnd, matches.get(0).getToPos()); assertSuggestions(badSentence, lang, expectedCorrections, rule, matches); assertSuggestionsDoNotCreateErrors(badSentence, languageTool, rule, matches); } } // check for overlapping rules /*matches = getMatches(rule, badSentence, languageTool); List<RuleMatch> matchesAllRules = allRulesLanguageTool.check(badSentence); for (RuleMatch match : matchesAllRules) { if (!match.getRule().getId().equals(rule.getId()) && !matches.isEmpty() && rangeIsOverlapping(matches.get(0).getFromPos(), matches.get(0).getToPos(), match.getFromPos(), match.getToPos())) System.err.println("WARN: " + lang.getShortCode() + ": '" + badSentence + "' in " + rule.getId() + " also matched " + match.getRule().getId()); }*/ } } private int findLargestReference (String message) { Pattern pattern = Pattern.compile("\\\\[0-9]+"); Matcher matcher = pattern.matcher(message); int max = 0; while (matcher.find()) { max = Math.max(max, Integer.parseInt(matcher.group().replace("\\", ""))); } return max; } private void testErrorTriggeringSentences(JLanguageTool languageTool, Language lang, AbstractPatternRule rule) throws IOException { for (ErrorTriggeringExample example : rule.getErrorTriggeringExamples()) { String sentence = cleanXML(example.getExample()); List<RuleMatch> matches = getMatches(rule, sentence, languageTool); if (matches.isEmpty()) { fail(lang + ": " + rule.getFullId() + ": Example sentence marked with 'triggers_error' didn't actually trigger an error: '" + sentence + "'"); } } } /** * returns true if [a, b] has at least one number in common with [x, y] */ private boolean rangeIsOverlapping(int a, int b, int x, int y) { if (a < x) { return x <= b; } else { return a <= y; } } private void assertSuggestions(String sentence, Language lang, List<String> expectedCorrections, AbstractPatternRule rule, List<RuleMatch> matches) { if (!expectedCorrections.isEmpty()) { boolean expectedNonEmptyCorrection = expectedCorrections.get(0).length() > 0; if (expectedNonEmptyCorrection) { assertTrue("You specified a correction but your message has no suggestions in rule " + rule.getFullId(), rule.getMessage().contains("<suggestion>") || rule.getSuggestionsOutMsg().contains("<suggestion>")); } List<String> realSuggestions = matches.get(0).getSuggestedReplacements(); if (realSuggestions.isEmpty()) { boolean expectedEmptyCorrection = expectedCorrections.size() == 1 && expectedCorrections.get(0).length() == 0; assertTrue(lang + ": Incorrect suggestions: " + expectedCorrections + " != " + " <no suggestion> for rule " + rule.getFullId() + " on input: " + sentence, expectedEmptyCorrection); } else { assertEquals(lang + ": Incorrect suggestions: " + expectedCorrections + " != " + realSuggestions + " for rule " + rule.getFullId() + " on input: " + sentence, expectedCorrections, realSuggestions); } } } private void assertSuggestionsDoNotCreateErrors(String badSentence, JLanguageTool languageTool, AbstractPatternRule rule, List<RuleMatch> matches) throws IOException { if (matches.get(0).getSuggestedReplacements().size() > 0) { int fromPos = matches.get(0).getFromPos(); int toPos = matches.get(0).getToPos(); for (String replacement : matches.get(0).getSuggestedReplacements()) { String fixedSentence = badSentence.substring(0, fromPos) + replacement + badSentence.substring(toPos); List<RuleMatch> tempMatches = getMatches(rule, fixedSentence, languageTool); assertEquals("Corrected sentence for rule " + rule.getFullId() + " triggered error: " + fixedSentence, 0, tempMatches.size()); } } } private void testCorrectSentences(JLanguageTool languageTool, JLanguageTool allRulesLanguageTool, Language lang, AbstractPatternRule rule) throws IOException { List<CorrectExample> goodSentences = rule.getCorrectExamples(); // necessary for XML Pattern rules containing <or> List<AbstractPatternRule> rules = allRulesLanguageTool.getPatternRulesByIdAndSubId(rule.getId(), rule.getSubId()); for (CorrectExample goodSentenceObj : goodSentences) { // enable indentation use String goodSentence = goodSentenceObj.getExample().replaceAll("[\\n\\t]+", ""); goodSentence = cleanXML(goodSentence); assertTrue(lang + ": Empty correct example in rule " + rule.getFullId(), goodSentence.trim().length() > 0); boolean isMatched = false; // necessary for XML Pattern rules containing <or> for (Rule auxRule : rules) { isMatched = isMatched || match(auxRule, goodSentence, languageTool); } if (isMatched) { AnalyzedSentence analyzedSentence = languageTool.getAnalyzedSentence(goodSentence); StringBuilder sb = new StringBuilder("Analyzed token readings:"); for (AnalyzedTokenReadings atr : analyzedSentence.getTokens()) { sb.append(" ").append(atr); } fail(lang + ": Did not expect error in:\n" + " " + goodSentence + "\n" + " " + sb + "\n" + "Matching Rule: " + rule.getFullId() + " from " + rule.getSourceFile()); } // avoid matches with all the *other* rules: /* List<RuleMatch> matches = allRulesLanguageTool.check(goodSentence); for (RuleMatch match : matches) { System.err.println("WARN: " + lang.getShortCode() + ": '" + goodSentence + "' did not match " + rule.getId() + " but matched " + match.getRule().getId()); } */ } } protected String cleanXML(String str) { return str.replaceAll("<([^<].*?)>", ""); } private boolean match(Rule rule, String sentence, JLanguageTool languageTool) throws IOException { AnalyzedSentence analyzedSentence = languageTool.getAnalyzedSentence(sentence); RuleMatch[] matches = rule.match(analyzedSentence); return matches.length > 0; } private List<RuleMatch> getMatches(Rule rule, String sentence, JLanguageTool languageTool) throws IOException { AnalyzedSentence analyzedSentence = languageTool.getAnalyzedSentence(sentence); RuleMatch[] matches = rule.match(analyzedSentence); if (CHECK_WITH_SENTENCE_SPLITTING) { // "real check" with sentence splitting: for (Rule r : languageTool.getAllActiveRules()) { languageTool.disableRule(r.getId()); } languageTool.enableRule(rule.getId()); List<RuleMatch> realMatches = languageTool.check(sentence); List<String> realMatchRuleIds = new ArrayList<>(); for (RuleMatch realMatch : realMatches) { realMatchRuleIds.add(realMatch.getRule().getId()); } for (RuleMatch match : matches) { String ruleId = match.getRule().getId(); if (!match.getRule().isDefaultOff() && !realMatchRuleIds.contains(ruleId)) { System.err.println("WARNING: " + languageTool.getLanguage().getName() + ": missing rule match " + ruleId + " when splitting sentences for test sentence '" + sentence + "'"); } } } return Arrays.asList(matches); } protected PatternRule makePatternRule(String s, boolean caseSensitive, boolean regex) { List<PatternToken> patternTokens = new ArrayList<>(); String[] parts = s.split(" "); boolean pos = false; PatternToken pToken; for (String element : parts) { if (element.equals(JLanguageTool.SENTENCE_START_TAGNAME)) { pos = true; } if (!pos) { pToken = new PatternToken(element, caseSensitive, regex, false); } else { pToken = new PatternToken("", caseSensitive, regex, false); } if (pos) { pToken.setPosToken(new PatternToken.PosToken(element, false, false)); } patternTokens.add(pToken); pos = false; } PatternRule rule = new PatternRule("ID1", TestTools.getDemoLanguage(), patternTokens, "test rule", "user visible message", "short comment"); return rule; } /** * Test XML patterns, as a help for people developing rules that are not * programmers. */ public static void main(String[] args) throws IOException { PatternRuleTest test = new PatternRuleTest(); System.out.println("Running XML pattern tests..."); if (args.length == 0) { test.runGrammarRulesFromXmlTestIgnoringLanguages(null); } else { Set<Language> ignoredLanguages = TestTools.getLanguagesExcept(args); test.runGrammarRulesFromXmlTestIgnoringLanguages(ignoredLanguages); } System.out.println("Tests finished!"); } }
package org.pikater.core.options; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.pikater.core.CoreConstants; import org.pikater.core.ontology.subtrees.batchDescription.durarion.LongTermDuration; import org.pikater.core.ontology.subtrees.batchDescription.durarion.ShortTimeDuration; import org.pikater.core.ontology.subtrees.newOption.base.NewOption; import org.pikater.core.ontology.subtrees.newOption.base.Value; import org.pikater.core.ontology.subtrees.newOption.base.ValueType; import org.pikater.core.ontology.subtrees.newOption.restrictions.SetRestriction; import org.pikater.core.ontology.subtrees.newOption.values.IntegerValue; import org.pikater.core.ontology.subtrees.newOption.values.NullValue; import org.pikater.core.ontology.subtrees.newOption.values.StringValue; import org.pikater.core.ontology.subtrees.newOption.values.interfaces.IValueData; public class OptionsHelper { public static List<NewOption> getCAOptions() { List<NewOption> options = OptionsHelper.getNotSpecifiedCAOptions(); Value defaultValue = new Value(new NullValue()); NewOption optModel = new NewOption(CoreConstants.MODEL, defaultValue, defaultValue.getType(), new ValueType(new IntegerValue(0))); options.add(optModel); return options; } public static List<NewOption> getNotSpecifiedCAOptions() { List<IValueData> durationValues = new ArrayList<IValueData>(); durationValues.add(new StringValue(ShortTimeDuration.class.getSimpleName())); durationValues.add(new StringValue(LongTermDuration.class.getSimpleName())); NewOption optDuration = new NewOption( CoreConstants.DURATION, new StringValue(LongTermDuration.class.getSimpleName()), new SetRestriction(false, durationValues)); List<IValueData> modeValues = new ArrayList<IValueData>(); modeValues.add(new StringValue(CoreConstants.MODE_TRAIN_ONLY)); modeValues.add(new StringValue(CoreConstants.MODE_TEST_ONLY)); modeValues.add(new StringValue(CoreConstants.MODE_TRAIN_TEST)); NewOption optMode = new NewOption( CoreConstants.MODE, new StringValue(CoreConstants.MODE_TRAIN_ONLY), new SetRestriction(false, modeValues)); List<IValueData> outputValues = new ArrayList<IValueData>(); outputValues.add(new StringValue(CoreConstants.OUTPUT_EVALUATION_ONLY)); outputValues.add(new StringValue(CoreConstants.OUTPUT_PREDICTION)); NewOption optOutput = new NewOption( CoreConstants.OUTPUT, new StringValue(CoreConstants.OUTPUT_PREDICTION), new SetRestriction(false, outputValues)); List<NewOption> options = new ArrayList<NewOption>(); options.add(optDuration); options.add(optMode); options.add(optOutput); return options; } }
package org.apache.fop.apps; // SAX import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.SAXException; // Java import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.ParserConfigurationException; import java.net.URL; import java.io.File; public abstract class InputHandler { public abstract InputSource getInputSource(); public abstract XMLReader getParser() throws FOPException; public static InputSource urlInputSource(URL url) { return new InputSource(url.toString()); } /** * Creates an <code>InputSource</code> from a <code>File</code> * @param file the <code>File</code> * @return the <code>InputSource</code> created */ public static InputSource fileInputSource(File file) { /* this code adapted from James Clark's in XT */ String path = file.getAbsolutePath(); String fSep = System.getProperty("file.separator"); if (fSep != null && fSep.length() == 1) { path = path.replace(fSep.charAt(0), '/'); } if (path.length() > 0 && path.charAt(0) != '/') { path = '/' + path; } try { return new InputSource(new URL("file", null, path).toString()); } catch (java.net.MalformedURLException e) { throw new Error("unexpected MalformedURLException"); } } /** * Creates <code>XMLReader</code> object using default * <code>SAXParserFactory</code> * @return the created <code>XMLReader</code> */ protected static XMLReader createParser() throws FOPException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); return factory.newSAXParser().getXMLReader(); } catch (SAXException se) { throw new FOPException("Coudn't create XMLReader", se); } catch (ParserConfigurationException pce) { throw new FOPException("Coudn't create XMLReader", pce); } } }
package org.languagetool.language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.*; import org.languagetool.rules.fr.*; import org.languagetool.synthesis.FrenchSynthesizer; import org.languagetool.synthesis.Synthesizer; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.fr.FrenchHybridDisambiguator; import org.languagetool.tagging.fr.FrenchTagger; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.Tokenizer; import org.languagetool.tokenizers.fr.FrenchWordTokenizer; import java.io.File; import java.io.IOException; import java.util.*; public class French extends Language implements AutoCloseable { private LanguageModel languageModel; @Override public SentenceTokenizer createDefaultSentenceTokenizer() { return new SRXSentenceTokenizer(this); } @Override public String getName() { return "French"; } @Override public String getShortCode() { return "fr"; } @Override public String[] getCountries() { return new String[]{"FR", "", "BE", "CH", "CA", "LU", "MC", "CM", "CI", "HT", "ML", "SN", "CD", "MA", "RE"}; } @NotNull @Override public Tagger createDefaultTagger() { return new FrenchTagger(); } @Nullable @Override public Synthesizer createDefaultSynthesizer() { return new FrenchSynthesizer(this); } @Override public Tokenizer createDefaultWordTokenizer() { return new FrenchWordTokenizer(); } @Override public Disambiguator createDefaultDisambiguator() { return new FrenchHybridDisambiguator(); } @Override public Contributor[] getMaintainers() { return new Contributor[] { Contributors.DOMINIQUE_PELLE }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, false), new DoublePunctuationRule(messages), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{" ), Arrays.asList("]", ")", "}" )), new MorfologikFrenchSpellerRule(messages, this, userConfig, altLanguages), new UppercaseSentenceStartRule(messages, this), new MultipleWhitespaceRule(messages, this), new SentenceWhitespaceRule(messages), new LongSentenceRule(messages, userConfig, 40, true, true), new LongParagraphRule(messages, this, userConfig), // specific to French: new CompoundRule(messages), new QuestionWhitespaceStrictRule(messages, this), new QuestionWhitespaceRule(messages, this), new SimpleReplaceRule(messages), new AnglicismReplaceRule(messages) ); } @Override public List<Rule> getRelevantRulesGlobalConfig(ResourceBundle messages, GlobalConfig globalConfig, UserConfig userConfig, Language motherTongue, List<Language> altLanguages) throws IOException { List<Rule> rules = new ArrayList<>(); if (globalConfig != null && globalConfig.getGrammalecteServer() != null) { rules.add(new GrammalecteRule(messages, globalConfig)); } return rules; } /** @since 3.1 */ @Override public List<Rule> getRelevantLanguageModelRules(ResourceBundle messages, LanguageModel languageModel, UserConfig userConfig) throws IOException { return Arrays.asList( new FrenchConfusionProbabilityRule(messages, languageModel, this) ); } /** @since 3.1 */ @Override public synchronized LanguageModel getLanguageModel(File indexDir) throws IOException { languageModel = initLanguageModel(indexDir, languageModel); return languageModel; } /** @since 5.1 */ @Override public String getOpeningDoubleQuote() { return "«"; } /** @since 5.1 */ @Override public String getClosingDoubleQuote() { return "»"; } /** @since 5.1 */ @Override public String getOpeningSingleQuote() { return "‘"; } /** @since 5.1 */ @Override public String getClosingSingleQuote() { return "’"; } /** @since 5.1 */ @Override public boolean isAdvancedTypographyEnabled() { return true; } @Override public String toAdvancedTypography (String input) { String output = super.toAdvancedTypography(input); // special cases: apostrophe + quotation marks String beforeApostrophe = "([cjnmtsldCJNMTSLD]|qu|jusqu|lorsqu|puisqu|quoiqu|Qu|Jusqu|Lorsqu|Puisqu|Quoiqu|QU|JUSQU|LORSQU|PUISQU|QUOIQU)"; output = output.replaceAll("(\\b"+beforeApostrophe+")'", "$1’"); output = output.replaceAll("(\\b"+beforeApostrophe+")’\"", "$1’" + getOpeningDoubleQuote()); output = output.replaceAll("(\\b"+beforeApostrophe+")’'", "$1’" + getOpeningSingleQuote()); // non-breaking (thin) space // according to https://fr.wikipedia.org/wiki/Espace_ins%C3%A9cable#En_France output = output.replaceAll("\u00a0;", "\u202f;"); output = output.replaceAll("\u00a0!", "\u202f!"); output = output.replaceAll("\u00a0\\?", "\u202f?"); output = output.replaceAll(";", "\u202f;"); output = output.replaceAll("!", "\u202f!"); output = output.replaceAll("\\?", "\u202f?"); output = output.replaceAll(":", "\u00a0:"); output = output.replaceAll("»", "\u00a0»"); output = output.replaceAll("«", "«\u00a0"); //remove duplicate spaces output = output.replaceAll("\u00a0\u00a0", "\u00a0"); output = output.replaceAll("\u202f\u202f", "\u202f"); output = output.replaceAll(" ", " "); output = output.replaceAll("\u00a0 ", "\u00a0"); output = output.replaceAll(" \u00a0", "\u00a0"); output = output.replaceAll(" \u202f", "\u202f"); output = output.replaceAll("\u202f ", "\u202f"); return output; } /** * Closes the language model, if any. * @since 3.1 */ @Override public void close() throws Exception { if (languageModel != null) { languageModel.close(); } } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override protected int getPriorityForId(String id) { switch (id) { case "FR_COMPOUNDS": return 500; // greater than agreement rules case "AGREEMENT_EXCEPTIONS": return 100; // greater than D_N case "EXPRESSIONS_VU": return 100; // greater than A_ACCENT_A case "SA_CA_SE": return 100; // greater than D_N case "MA": return 100; // greater than D_J case "SON_SONT": return 100; // greater than D_J case "JE_TES": return 100; // greater than D_J case "A_INFINITIF": return 100; case "ON_ONT": return 100; // greater than PRONSUJ_NONVERBE case "LEURS_LEUR": return 100; // greater than N_V case "DU_DU": return 100; // greater than DU_LE case "ACCORD_CHAQUE": return 100; // greater than ACCORD_NOMBRE case "CEST_A_DIRE": return 100; // greater than A_A_ACCENT case "FAIRE_VPPA": return 100; // greater than A_ACCENT_A case "A_VERBE_INFINITIF": return 20; // greater than PRONSUJ_NONVERBE case "CONFUSION_PARLEZ_PARLER": return 10; // greater than N_V case "ESPACE_UNITES": return 10; // needs to have higher priority than spell checker case "BYTES": return 10; // needs to be higher than spell checker for 10MB style matches case "Y_A": return 10; // needs to be higher than spell checker for style suggestion case "A_A_ACCENT": return 10; case "A_ACCENT_A": return 10; // greater than PRONSUJ_NONVERBE case "JE_M_APPEL": return 10; // override NON_V case "ACCORD_R_PERS_VERBE": return 10; // match before POSER_UNE_QUESTION case "JE_SUI": return 10; // needs higher priority than spell checker //case "D_N": return 1; // needs to have higher priority than agreement postponed adj | Commented out because many other rules should be higher //case "ACCORD_COULEUR": return 1; // needs to have higher priority than agreement postponed adj case "CONFUSION_PAR_PART": return -1; // turn off completely when PART_OU_PAR is activated case "FR_SIMPLE_REPLACE": return -10; case "IMP_PRON": return -10; // less than D_N case "PREP_VERBECONJUGUE": return -20; case "PAS_DE_VERBE_APRES_POSSESSIF_DEMONSTRATIF": return -20; case "TOO_LONG_PARAGRAPH": return -15; case "VERB_PRONOUN": return -50; // greater than FR_SPELLING_RULE; less than ACCORD_V_QUESTION case "AGREEMENT_POSTPONED_ADJ": return -50; case "FR_SPELLING_RULE": return -100; case "ET_SENT_START": return -151; // lower than grammalecte rules case "MAIS_SENT_START": return -151; // lower than grammalecte rules case "ELISION": return -200; // should be lower in priority than spell checker case "UPPERCASE_SENTENCE_START": return -300; case "FRENCH_WHITESPACE_STRICT": return -350; // picky; if on, it should overwrite FRENCH_WHITESPACE case "FRENCH_WHITESPACE": return -400; // lesser than UPPERCASE_SENTENCE_START and FR_SPELLING_RULE case "R_VAVOIR_VINF": return 10; // needs higher priority than A_INFINITIF } if (id.startsWith("grammalecte_")) { return -150; } return super.getPriorityForId(id); } }
package hudson.util; import hudson.cli.CLI; import hudson.diagnosis.OldDataMonitor; import hudson.model.AbstractDescribableImpl; import hudson.model.Items; import hudson.model.JobProperty; import hudson.model.JobPropertyDescriptor; import hudson.model.Descriptor; import hudson.model.FreeStyleProject; import hudson.model.Job; import hudson.model.Saveable; import hudson.security.ACL; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Collections; import java.util.Map; import jenkins.model.Jenkins; import static org.junit.Assert.*; import net.sf.json.JSONObject; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.TestExtension; import org.jvnet.hudson.test.recipes.LocalData; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.WebRequestSettings; public class RobustReflectionConverterTest { @Rule public JenkinsRule r = new JenkinsRule(); @Issue("JENKINS-21024") @LocalData @Test public void randomExceptionsReported() throws Exception { FreeStyleProject p = r.jenkins.getItemByFullName("j", FreeStyleProject.class); assertNotNull(p); assertEquals(Collections.emptyMap(), p.getTriggers()); OldDataMonitor odm = (OldDataMonitor) r.jenkins.getAdministrativeMonitor("OldData"); Map<Saveable,OldDataMonitor.VersionRange> data = odm.getData(); assertEquals(Collections.singleton(p), data.keySet()); String text = data.values().iterator().next().extra; assertTrue(text, text.contains("Could not call hudson.triggers.TimerTrigger.readResolve")); } // Testing describable object to demonstrate what is expected with RobustReflectionConverter#addCriticalField // This should be configured with a specific keyword, // and should reject configurations with other keywords. // GUI related implementations (@DataBoundConstructor and newInstance) aren't used actually // (no jelly files are provides and they don't work actually), // but written to clarify a use case. public static class AcceptOnlySpecificKeyword extends AbstractDescribableImpl<AcceptOnlySpecificKeyword>{ public static final String ACCEPT_KEYWORD = "accept"; private final String keyword; @DataBoundConstructor public AcceptOnlySpecificKeyword(String keyword) { this.keyword = keyword; } public String getKeyword() { return keyword; } public boolean isAcceptable() { return ACCEPT_KEYWORD.equals(keyword); } public Object readResolve() throws Exception { if (!ACL.SYSTEM.equals(Jenkins.getAuthentication())) { // called via REST / CLI with authentication if (!isAcceptable()) { // Reject invalid configuration via REST / CLI. throw new Exception(String.format("Bad keyword: %s", getKeyword())); } } return this; } @TestExtension public static class DescriptorImpl extends Descriptor<AcceptOnlySpecificKeyword> { @Override public String getDisplayName() { return "AcceptOnlySpecificKeyword"; } @Override public AcceptOnlySpecificKeyword newInstance(StaplerRequest req, JSONObject formData) throws FormException { AcceptOnlySpecificKeyword instance = super.newInstance(req, formData); if (!instance.isAcceptable()) { throw new FormException(String.format("Bad keyword: %s", instance.getKeyword()), "keyword"); } return instance; } } } public static class KeywordProperty extends JobProperty<Job<?,?>> { private final AcceptOnlySpecificKeyword nonCriticalField; private final AcceptOnlySpecificKeyword criticalField; public KeywordProperty(AcceptOnlySpecificKeyword nonCriticalField, AcceptOnlySpecificKeyword criticalField) { this.nonCriticalField = nonCriticalField; this.criticalField = criticalField; } public AcceptOnlySpecificKeyword getNonCriticalField() { return nonCriticalField; } public AcceptOnlySpecificKeyword getCriticalField() { return criticalField; } @TestExtension public static class DescriptorImpl extends JobPropertyDescriptor { @Override public String getDisplayName() { return "KeywordProperty"; } @Override public JobProperty<?> newInstance(StaplerRequest req, JSONObject formData) throws FormException { // unfortunately, default newInstance bypasses newInstances for members. formData = formData.getJSONObject("keywordProperty"); @SuppressWarnings("unchecked") Descriptor<AcceptOnlySpecificKeyword> d = Jenkins.getInstance().getDescriptor(AcceptOnlySpecificKeyword.class); return new KeywordProperty( d.newInstance(req, formData.getJSONObject("nonCriticalField")), d.newInstance(req, formData.getJSONObject("criticalField")) ); } } } private static final String CONFIGURATION_TEMPLATE = "<?xml version='1.0' encoding='UTF-8'?>" + "<project>" + "<properties>" + "<hudson.util.RobustReflectionConverterTest_-KeywordProperty>" + "<nonCriticalField>" + "<keyword>%s</keyword>" + "</nonCriticalField>" + "<criticalField>" + "<keyword>%s</keyword>" + "</criticalField>" + "</hudson.util.RobustReflectionConverterTest_-KeywordProperty>" + "</properties>" + "</project>"; @Test public void testRestInterfaceFailure() throws Exception { Items.XSTREAM2.addCriticalField(KeywordProperty.class, "criticalField"); // without addCriticalField. This is accepted. { FreeStyleProject p = r.createFreeStyleProject(); p.addProperty(new KeywordProperty( new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD), new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD) )); p.save(); // Configure a bad keyword via REST. r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WebClient wc = r.createWebClient(); wc.login("test", "test"); WebRequestSettings req = new WebRequestSettings( wc.createCrumbedUrl(String.format("%s/config.xml", p.getUrl())), HttpMethod.POST ); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD)); wc.getPage(req); // AcceptOnlySpecificKeyword with bad value is not instantiated for rejected with readResolve, assertNull(p.getProperty(KeywordProperty.class).getNonCriticalField()); assertEquals(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); // but save to the disk. r.jenkins.reload(); p = r.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class); assertEquals("badvalue", p.getProperty(KeywordProperty.class).getNonCriticalField().getKeyword()); assertEquals(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); } // with addCriticalField. This is not accepted. { FreeStyleProject p = r.createFreeStyleProject(); p.addProperty(new KeywordProperty( new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD), new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD) )); p.save(); // Configure a bad keyword via REST. r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WebClient wc = r.createWebClient(); wc.login("test", "test"); WebRequestSettings req = new WebRequestSettings( wc.createCrumbedUrl(String.format("%s/config.xml", p.getUrl())), HttpMethod.POST ); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue")); try { wc.getPage(req); // TODO: fail("Submitting unacceptable configuration via REST should fail."); } catch (FailingHttpStatusCodeException e) { // pass } // Configuration should not be updated for a failure of the critical field, // TODO: assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); r.jenkins.reload(); // rejected configuration is not saved p = r.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class); assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); } } @Test public void testCliFailure() throws Exception { Items.XSTREAM2.addCriticalField(KeywordProperty.class, "criticalField"); // without addCriticalField. This is accepted. { FreeStyleProject p = r.createFreeStyleProject(); p.addProperty(new KeywordProperty( new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD), new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD) )); p.save(); // Configure a bad keyword via CLI. r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); CLI cli = new CLI(r.getURL()); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); int ret = cli.execute( Arrays.asList( "update-job", p.getFullName(), "--username", "test", "--password", "test" ), new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD).getBytes()), stdout, stderr ); assertEquals(0, ret); // AcceptOnlySpecificKeyword with bad value is not instantiated for rejected with readResolve, assertNull(p.getProperty(KeywordProperty.class).getNonCriticalField()); assertEquals(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); // but save to the disk. r.jenkins.reload(); p = r.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class); assertEquals("badvalue", p.getProperty(KeywordProperty.class).getNonCriticalField().getKeyword()); } // with addCriticalField. This is not accepted. { FreeStyleProject p = r.createFreeStyleProject(); p.addProperty(new KeywordProperty( new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD), new AcceptOnlySpecificKeyword(AcceptOnlySpecificKeyword.ACCEPT_KEYWORD) )); p.save(); // Configure a bad keyword via CLI. r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); CLI cli = new CLI(r.getURL()); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); int ret = cli.execute( Arrays.asList( "update-job", p.getFullName(), "--username", "test", "--password", "test" ), new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue").getBytes()), stdout, stderr ); // TODO: assertNotEquals(0, ret); // Configuration should not be updated for a failure of the critical field, // TODO: assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); r.jenkins.reload(); // rejected configuration is not saved p = r.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class); assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); } } }
package org.processmining.openslex; import java.io.File; public class SLEXFactory { private String path = null; public SLEXFactory(String path) { this.path = path; if (path == null) { this.path = SLEXStorage.PATH; } } private synchronized static File generateNameFile(String path, String ext) { File f = null; try { String millis = String.valueOf(System.currentTimeMillis()); f = new File(path+File.separator+millis+ext); while (f.exists()) { millis = String.valueOf(System.currentTimeMillis()); f = new File(path+File.separator+millis+ext); } f.createNewFile(); } catch (Exception e) { e.printStackTrace(); } return f; } public SLEXStorageCollection createStorageCollection() { File f = generateNameFile(SLEXStorage.PATH, SLEXStorage.COLLECTION_FILE_EXTENSION); SLEXStorageCollection st = null; try { st = new SLEXStorageImpl(f.getParent(), f.getName(), SLEXStorage.TYPE_COLLECTION); } catch (Exception e) { e.printStackTrace(); } return st; } public SLEXStoragePerspective createStoragePerspective() { File f = generateNameFile(SLEXStorage.PATH, SLEXStorage.PERSPECTIVE_FILE_EXTENSION); SLEXStoragePerspective st = null; try { st = new SLEXStorageImpl(f.getParent(), f.getName(), SLEXStorage.TYPE_PERSPECTIVE); } catch (Exception e) { e.printStackTrace(); } return st; } public SLEXStorageDataModel createStorageDataModel() { File f = generateNameFile(SLEXStorage.PATH, SLEXStorage.DATAMODEL_FILE_EXTENSION); SLEXStorageDataModel st = null; try { st = new SLEXStorageImpl(f.getParent(), f.getName(), SLEXStorage.TYPE_DATAMODEL); } catch (Exception e) { e.printStackTrace(); } return st; } public SLEXEventCollection createEventCollection(String name) { SLEXStorageCollection st = createStorageCollection(); SLEXEventCollection ec = null; if (st != null) { ec = st.createEventCollection(name); } return ec; } public SLEXPerspective createPerspective(SLEXEventCollection ec, String name) { SLEXStoragePerspective st = createStoragePerspective(); SLEXPerspective p = null; if (st != null) { p = st.createPerspective(ec, name); } return p; } }
package mil.nga.geopackage.test; import junit.framework.TestCase; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.GeoPackage; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.GeoPackageManager; import mil.nga.geopackage.core.srs.SpatialReferenceSystem; import mil.nga.geopackage.core.srs.SpatialReferenceSystemDao; import mil.nga.geopackage.extension.elevation.ElevationTiles; import mil.nga.geopackage.extension.elevation.GriddedCoverage; import mil.nga.geopackage.extension.elevation.GriddedCoverageDao; import mil.nga.geopackage.extension.elevation.GriddedCoverageDataType; import mil.nga.geopackage.extension.elevation.GriddedTile; import mil.nga.geopackage.extension.elevation.GriddedTileDao; import mil.nga.geopackage.factory.GeoPackageFactory; import mil.nga.geopackage.projection.ProjectionConstants; import mil.nga.geopackage.test.geom.GeoPackageGeometryDataUtils; import mil.nga.geopackage.tiles.matrix.TileMatrix; import mil.nga.geopackage.tiles.matrix.TileMatrixDao; import mil.nga.geopackage.tiles.matrixset.TileMatrixSet; import mil.nga.geopackage.tiles.user.TileDao; import mil.nga.geopackage.tiles.user.TileRow; /** * Abstract Test Case for Imported Elevation Tiles GeoPackages * * @author osbornb */ public abstract class CreateElevationTilesGeoPackageTestCase extends GeoPackageTestCase { public class ElevationTileValues { public short[][] tilePixels; public int[][] tileUnsignedPixels; public Double[][] tileElevations; public short[] tilePixelsFlat; public int[] tileUnsignedPixelsFlat; public Double[] tileElevationsFlat; } protected ElevationTileValues elevationTileValues = new ElevationTileValues(); protected final boolean allowNulls; /** * Constructor * * @param allowNulls true to allow null elevations */ public CreateElevationTilesGeoPackageTestCase(boolean allowNulls) { this.allowNulls = allowNulls; } @Override protected GeoPackage getGeoPackage() throws Exception { GeoPackageManager manager = GeoPackageFactory.getManager(activity); // Delete manager.delete(TestConstants.CREATE_ELEVATION_TILES_DB_NAME); // Create manager.create(TestConstants.CREATE_ELEVATION_TILES_DB_NAME); // Open GeoPackage geoPackage = manager.open(TestConstants.CREATE_ELEVATION_TILES_DB_NAME); if (geoPackage == null) { throw new GeoPackageException("Failed to open database"); } double minLongitude = -180.0 + (360.0 * Math.random()); double maxLongitude = minLongitude + ((180.0 - minLongitude) * Math.random()); double minLatitude = ProjectionConstants.WEB_MERCATOR_MIN_LAT_RANGE + ((ProjectionConstants.WEB_MERCATOR_MAX_LAT_RANGE - ProjectionConstants.WEB_MERCATOR_MIN_LAT_RANGE) * Math .random()); double maxLatitude = minLatitude + ((ProjectionConstants.WEB_MERCATOR_MAX_LAT_RANGE - minLatitude) * Math .random()); BoundingBox bbox = new BoundingBox(minLongitude, maxLongitude, minLatitude, maxLatitude); SpatialReferenceSystemDao srsDao = geoPackage .getSpatialReferenceSystemDao(); SpatialReferenceSystem contentsSrs = srsDao .getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM_GEOGRAPHICAL_3D); SpatialReferenceSystem tileMatrixSrs = srsDao .getOrCreateFromEpsg(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM); ElevationTiles elevationTiles = ElevationTiles .createTileTableWithMetadata(geoPackage, TestConstants.CREATE_ELEVATION_TILES_DB_TABLE_NAME, bbox, contentsSrs.getId(), bbox, tileMatrixSrs.getId()); TileDao tileDao = elevationTiles.getTileDao(); TileMatrixSet tileMatrixSet = elevationTiles.getTileMatrixSet(); GriddedCoverageDao griddedCoverageDao = elevationTiles .getGriddedCoverageDao(); GriddedCoverage griddedCoverage = new GriddedCoverage(); griddedCoverage.setTileMatrixSet(tileMatrixSet); griddedCoverage.setDataType(GriddedCoverageDataType.INTEGER); boolean defaultScale = true; if (Math.random() < .5) { griddedCoverage.setScale(100.0 * Math.random()); defaultScale = false; } boolean defaultOffset = true; if (Math.random() < .5) { griddedCoverage.setOffset(100.0 * Math.random()); defaultOffset = false; } boolean defaultPrecision = true; if (Math.random() < .5) { griddedCoverage.setPrecision(10.0 * Math.random()); defaultPrecision = false; } griddedCoverage.setDataNull(new Double(Short.MAX_VALUE - Short.MIN_VALUE)); griddedCoverage.setDataMissing(new Double(Short.MAX_VALUE - Short.MIN_VALUE - 1)); TestCase.assertEquals(1, griddedCoverageDao.create(griddedCoverage)); long gcId = griddedCoverage.getId(); griddedCoverage = griddedCoverageDao.queryForId(gcId); TestCase.assertNotNull(griddedCoverage); if (defaultScale) { TestCase.assertEquals(1.0, griddedCoverage.getScale()); } else { TestCase.assertTrue(griddedCoverage.getScale() >= 0.0 && griddedCoverage.getScale() <= 100.0); } if (defaultOffset) { TestCase.assertEquals(0.0, griddedCoverage.getOffset()); } else { TestCase.assertTrue(griddedCoverage.getOffset() >= 0.0 && griddedCoverage.getOffset() <= 100.0); } if (defaultPrecision) { TestCase.assertEquals(1.0, griddedCoverage.getPrecision()); } else { TestCase.assertTrue(griddedCoverage.getPrecision() >= 0.0 && griddedCoverage.getPrecision() <= 10.0); } GriddedTile commonGriddedTile = new GriddedTile(); commonGriddedTile.setContents(tileMatrixSet.getContents()); boolean defaultGTScale = true; if (Math.random() < .5) { commonGriddedTile.setScale(100.0 * Math.random()); defaultGTScale = false; } boolean defaultGTOffset = true; if (Math.random() < .5) { commonGriddedTile.setOffset(100.0 * Math.random()); defaultGTOffset = false; } // The min, max, mean, and sd are just for testing and have // no association on the test tile created boolean defaultGTMin = true; if (Math.random() < .5) { commonGriddedTile.setMin(1000.0 * Math.random()); defaultGTMin = false; } boolean defaultGTMax = true; if (Math.random() < .5) { commonGriddedTile.setMax(1000.0 * Math.random() + (commonGriddedTile.getMin() == null ? 0 : commonGriddedTile.getMin())); defaultGTMax = false; } boolean defaultGTMean = true; if (Math.random() < .5) { double min = commonGriddedTile.getMin() != null ? commonGriddedTile .getMin() : 0; double max = commonGriddedTile.getMax() != null ? commonGriddedTile .getMax() : 2000.0; commonGriddedTile.setMean(((max - min) * Math.random()) + min); defaultGTMean = false; } boolean defaultGTStandardDeviation = true; if (Math.random() < .5) { double min = commonGriddedTile.getMin() != null ? commonGriddedTile .getMin() : 0; double max = commonGriddedTile.getMax() != null ? commonGriddedTile .getMax() : 2000.0; commonGriddedTile.setStandardDeviation((max - min) * Math.random()); defaultGTStandardDeviation = false; } GriddedTileDao griddedTileDao = elevationTiles.getGriddedTileDao(); int width = 1 + (int) Math.floor((Math.random() * 4.0)); int height = 1 + (int) Math.floor((Math.random() * 4.0)); int tileWidth = 3 + (int) Math.floor((Math.random() * 126.0)); int tileHeight = 3 + (int) Math.floor((Math.random() * 126.0)); int minZoomLevel = (int) Math.floor(Math.random() * 22.0); int maxZoomLevel = minZoomLevel + (int) Math.floor(Math.random() * 4.0); // Just draw one image and re-use elevationTiles = new ElevationTiles(geoPackage, tileDao); byte[] imageBytes = drawTile(elevationTiles, tileWidth, tileHeight, griddedCoverage, commonGriddedTile); TileMatrixDao tileMatrixDao = geoPackage.getTileMatrixDao(); for (int zoomLevel = minZoomLevel; zoomLevel <= maxZoomLevel; zoomLevel++) { TileMatrix tileMatrix = new TileMatrix(); tileMatrix.setContents(tileMatrixSet.getContents()); tileMatrix.setMatrixHeight(height); tileMatrix.setMatrixWidth(width); tileMatrix.setTileHeight(tileHeight); tileMatrix.setTileWidth(tileWidth); tileMatrix.setPixelXSize((bbox.getMaxLongitude() - bbox .getMinLongitude()) / width / tileWidth); tileMatrix.setPixelYSize((bbox.getMaxLatitude() - bbox .getMinLatitude()) / height / tileHeight); tileMatrix.setZoomLevel(zoomLevel); TestCase.assertEquals(1, tileMatrixDao.create(tileMatrix)); for (int row = 0; row < height; row++) { for (int column = 0; column < width; column++) { TileRow tileRow = tileDao.newRow(); tileRow.setTileColumn(column); tileRow.setTileRow(row); tileRow.setZoomLevel(zoomLevel); tileRow.setTileData(imageBytes); long tileId = tileDao.create(tileRow); TestCase.assertTrue(tileId >= 0); GriddedTile griddedTile = new GriddedTile(); griddedTile.setContents(tileMatrixSet.getContents()); griddedTile.setTableId(tileId); griddedTile.setScale(commonGriddedTile.getScale()); griddedTile.setOffset(commonGriddedTile.getOffset()); griddedTile.setMin(commonGriddedTile.getMin()); griddedTile.setMax(commonGriddedTile.getMax()); griddedTile.setMean(commonGriddedTile.getMean()); griddedTile.setStandardDeviation(commonGriddedTile .getStandardDeviation()); TestCase.assertEquals(1, griddedTileDao.create(griddedTile)); long gtId = griddedTile.getId(); TestCase.assertTrue(gtId >= 0); griddedTile = griddedTileDao.queryForId(gtId); TestCase.assertNotNull(griddedTile); if (defaultGTScale) { TestCase.assertEquals(1.0, griddedTile.getScale()); } else { TestCase.assertTrue(griddedTile.getScale() >= 0.0 && griddedTile.getScale() <= 100.0); } if (defaultGTOffset) { TestCase.assertEquals(0.0, griddedTile.getOffset()); } else { TestCase.assertTrue(griddedTile.getOffset() >= 0.0 && griddedTile.getOffset() <= 100.0); } if (defaultGTMin) { TestCase.assertNull(griddedTile.getMin()); } else { TestCase.assertTrue(griddedTile.getMin() >= 0.0 && griddedTile.getMin() <= 1000.0); } if (defaultGTMax) { TestCase.assertNull(griddedTile.getMax()); } else { TestCase.assertTrue(griddedTile.getMax() >= 0.0 && griddedTile.getMax() <= 2000.0); } if (defaultGTMean) { TestCase.assertNull(griddedTile.getMean()); } else { TestCase.assertTrue(griddedTile.getMean() >= 0.0 && griddedTile.getMean() <= 2000.0); } if (defaultGTStandardDeviation) { TestCase.assertNull(griddedTile.getStandardDeviation()); } else { TestCase.assertTrue(griddedTile.getStandardDeviation() >= 0.0 && griddedTile.getStandardDeviation() <= 2000.0); } } } height *= 2; width *= 2; } return geoPackage; } /** * {@inheritDoc} */ @Override protected void tearDown() throws Exception { // Close if (geoPackage != null) { geoPackage.close(); } super.tearDown(); } /** * Draw an elevation tile with random values * * @param elevationTiles * @param tileWidth * @param tileHeight * @param griddedCoverage * @param commonGriddedTile * @return */ private byte[] drawTile(ElevationTiles elevationTiles, int tileWidth, int tileHeight, GriddedCoverage griddedCoverage, GriddedTile commonGriddedTile) { elevationTileValues.tilePixels = new short[tileHeight][tileWidth]; elevationTileValues.tileUnsignedPixels = new int[tileHeight][tileWidth]; elevationTileValues.tileElevations = new Double[tileHeight][tileWidth]; elevationTileValues.tilePixelsFlat = new short[tileHeight * tileWidth]; elevationTileValues.tileUnsignedPixelsFlat = new int[tileHeight * tileWidth]; elevationTileValues.tileElevationsFlat = new Double[tileHeight * tileWidth]; GriddedTile griddedTile = new GriddedTile(); griddedTile.setScale(commonGriddedTile.getScale()); griddedTile.setOffset(commonGriddedTile.getOffset()); griddedTile.setMin(commonGriddedTile.getMin()); griddedTile.setMax(commonGriddedTile.getMax()); griddedTile.setMean(commonGriddedTile.getMean()); griddedTile.setStandardDeviation(commonGriddedTile .getStandardDeviation()); // Create the image and graphics for (int x = 0; x < tileWidth; x++) { for (int y = 0; y < tileHeight; y++) { int unsignedValue; if (allowNulls && Math.random() < .05) { unsignedValue = griddedCoverage.getDataNull().intValue(); } else { unsignedValue = Short.MAX_VALUE - Short.MIN_VALUE - 1; unsignedValue = (int) Math.floor(Math.random() * unsignedValue); } short value = (short) unsignedValue; elevationTileValues.tilePixels[y][x] = value; elevationTileValues.tileUnsignedPixels[y][x] = unsignedValue; elevationTileValues.tileElevations[y][x] = elevationTiles .getElevationValue(griddedTile, value); elevationTileValues.tilePixelsFlat[(y * tileWidth) + x] = elevationTileValues.tilePixels[y][x]; elevationTileValues.tileUnsignedPixelsFlat[(y * tileWidth) + x] = elevationTileValues.tileUnsignedPixels[y][x]; elevationTileValues.tileElevationsFlat[(y * tileWidth) + x] = elevationTileValues.tileElevations[y][x]; } } byte[] imageData = elevationTiles .drawTileData(elevationTileValues.tilePixels); GeoPackageGeometryDataUtils.compareByteArrays(imageData, elevationTiles .drawTileData(elevationTileValues.tileUnsignedPixels)); GeoPackageGeometryDataUtils.compareByteArrays(imageData, elevationTiles .drawTileData(griddedTile, elevationTileValues.tileElevations)); GeoPackageGeometryDataUtils.compareByteArrays(imageData, elevationTiles .drawTileData(elevationTileValues.tilePixelsFlat, tileWidth, tileHeight)); GeoPackageGeometryDataUtils.compareByteArrays(imageData, elevationTiles .drawTileData(elevationTileValues.tileUnsignedPixelsFlat, tileWidth, tileHeight)); GeoPackageGeometryDataUtils.compareByteArrays(imageData, elevationTiles .drawTileData(griddedTile, elevationTileValues.tileElevationsFlat, tileWidth, tileHeight)); return imageData; } }
package cgeo.geocaching.connector.gc; import org.eclipse.jdt.annotation.NonNull; import java.util.Locale; import java.util.regex.Pattern; public final class GCConstants { static final String GC_URL = "http: static final String GC_TILE_URL = "http://tiles.geocaching.com/"; /** Live Map */ public final static @NonNull String URL_LIVE_MAP = GC_URL + "map/default.aspx"; /** Live Map pop-up */ public final static @NonNull String URL_LIVE_MAP_DETAILS = GC_TILE_URL + "map.details"; /** Caches in a tile */ public final static @NonNull String URL_MAP_INFO = GC_TILE_URL + "map.info"; /** Tile itself */ public final static @NonNull String URL_MAP_TILE = GC_TILE_URL + "map.png"; /** * Patterns for parsing the result of a (detailed) search */ public final static Pattern PATTERN_HINT = Pattern.compile("<div id=\"div_hint\"[^>]*>(.*?)</div>", Pattern.DOTALL); public final static Pattern PATTERN_DESC = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\">(.*?)</span>\\s*</div>\\s*<p>\\s*</p>\\s*<p id=\"ctl00_ContentBody_hints\">", Pattern.DOTALL); public final static Pattern PATTERN_SHORTDESC = Pattern.compile("<span id=\"ctl00_ContentBody_ShortDescription\">(.*?)</span>\\s*</div>", Pattern.DOTALL); public final static Pattern PATTERN_GEOCODE = Pattern.compile("class=\"CoordInfoCode\">(GC[0-9A-Z]+)</span>"); public final static Pattern PATTERN_CACHEID = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)"); public final static Pattern PATTERN_GUID = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&")); public final static Pattern PATTERN_SIZE = Pattern.compile("<div id=\"ctl00_ContentBody_size\" class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"\\w+: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>"); public final static Pattern PATTERN_LATLON = Pattern.compile("<span id=\"uxLatLon\"[^>]*>(.*?)</span>"); public final static Pattern PATTERN_LATLON_ORIG = Pattern.compile("\\{\"isUserDefined\":true[^}]+?\"oldLatLngDisplay\":\"([^\"]+)\"\\}"); public final static Pattern PATTERN_LOCATION = Pattern.compile(Pattern.quote("<span id=\"ctl00_ContentBody_Location\">In ") + "(?:<a href=[^>]*>)?(.*?)<"); public final static Pattern PATTERN_PERSONALNOTE = Pattern.compile("<span id=\"cache_note\"[^>]*>(.*?)</span>", Pattern.DOTALL); public final static Pattern PATTERN_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_CacheName\">(.*?)</span>"); public final static Pattern PATTERN_DIFFICULTY = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_TERRAIN = Pattern.compile("<span id=\"ctl00_ContentBody_Localize[\\d]+\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\""); public final static Pattern PATTERN_OWNER_USERID = Pattern.compile("other caches <a href=\"/seek/nearest\\.aspx\\?u=(.*?)\">hidden</a> or"); public final static Pattern PATTERN_FOUND = Pattern.compile("ctl00_ContentBody_GeoNav_logText\">(Found It|Attended)"); public final static Pattern PATTERN_FOUND_ALTERNATIVE = Pattern.compile("<div class=\"StatusInformationWidget FavoriteWidget\""); public final static Pattern PATTERN_FOUND_DATE = Pattern.compile(">Logged on: ([^<]+?)<"); public final static Pattern PATTERN_OWNER_DISPLAYNAME = Pattern.compile("<div id=\"ctl00_ContentBody_mcd1\">[^<]+<a href=\"[^\"]+\">([^<]+)</a>"); public final static Pattern PATTERN_TYPE = Pattern.compile("<a href=\"/seek/nearest.aspx\\?tx=([0-9a-f-]+)"); public final static Pattern PATTERN_HIDDEN = Pattern.compile("<div id=\"ctl00_ContentBody_mcd2\">\\W*Hidden[\\s:]*([^<]+?)</div>"); public final static Pattern PATTERN_HIDDENEVENT = Pattern.compile("Event\\s*Date\\s*:\\s*([^<]+)<div id=\"calLinks\">", Pattern.DOTALL); public final static Pattern PATTERN_FAVORITE = Pattern.compile("<div id=\"pnlFavoriteCache\">"); // without 'class="hideMe"' inside the tag ! public final static Pattern PATTERN_FAVORITECOUNT = Pattern.compile("<span class=\"favorite-value\">\\D*([0-9]+?)\\D*</span>"); public final static Pattern PATTERN_COUNTLOGS = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p(.+?)</p></span>"); public final static Pattern PATTERN_LOGBOOK = Pattern.compile("initalLogs = (\\{.+\\});"); // The "inital" typo really comes from gc.com site /** Two groups ! */ public final static Pattern PATTERN_COUNTLOG = Pattern.compile("<img src=\"/images/logtypes/([0-9]+)\\.png\"[^>]+> (\\d*[,.]?\\d+)"); public static final Pattern PATTERN_PREMIUMMEMBERS = Pattern.compile("<p class=\"Warning NoBottomSpacing\">This is a Premium Member Only cache.</p>"); public final static Pattern PATTERN_ATTRIBUTES = Pattern.compile("Attributes\\s*</h3>[^<]*<div class=\"WidgetBody\">((?:[^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+?)[^<]*<p"); /** Two groups ! */ public final static Pattern PATTERN_ATTRIBUTESINSIDE = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+?)\""); public final static Pattern PATTERN_SPOILER_IMAGE = Pattern.compile("<a href=\"(http://imgcdn\\.geocaching\\.com[^.]+\\.(jpg|jpeg|png|gif))\"[^>]+>([^<]+)</a>(?:<br />([^<]+)<br /><br />)?"); public final static Pattern PATTERN_INVENTORY = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?"); public final static Pattern PATTERN_INVENTORYINSIDE = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>"); public final static Pattern PATTERN_WATCHLIST = Pattern.compile(Pattern.quote("watchlist.aspx") + ".{1,50}" + Pattern.quote("action=rem")); public final static Pattern PATTERN_RELATED_WEB_PAGE = Pattern.compile("id=\"ctl00_ContentBody_uxCacheUrl\" title=\"Related Web Page\" href=\"(.*?)\">"); // Info box top-right public static final Pattern PATTERN_LOGIN_NAME = Pattern.compile("\"SignedInProfileLink\">(.*?)</a>"); public static final Pattern PATTERN_MEMBER_STATUS = Pattern.compile("<span id=\"ctl00_litPMLevel\">([^<]+)</span>"); public static final String MEMBER_STATUS_RENEW = "<a id=\"ctl00_hlRenew"; public static final String MEMBER_STATUS_PM = "Premium Member"; /** Use replaceAll("[,.]","") on the resulting string before converting to an int */ public static final Pattern PATTERN_CACHES_FOUND = Pattern.compile("<strong[^>]*>.*?([\\d,.]+) Caches? Found", Pattern.DOTALL); public static final Pattern PATTERN_AVATAR_IMAGE_PROFILE_PAGE = Pattern.compile("src=\"(https?://(imgcdn\\.geocaching\\.com|[^>\"]+\\.cloudfront\\.net)/avatar/[0-9a-f-]+\\.jpg)\"[^>]*alt=\""); public static final Pattern PATTERN_LOGIN_NAME_LOGIN_PAGE = Pattern.compile("ctl00_ContentBody_lbUsername\">.*<strong>(.*)</strong>"); public static final Pattern PATTERN_CUSTOMDATE = Pattern.compile("<option selected=\"selected\" value=\"([ /Mdy-]+)\">"); public static final Pattern PATTERN_MAP_LOGGED_IN = Pattern.compile("<a href=\"https?: /** * Patterns for parsing trackables */ public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item."); // multiple error codes, depending on the search term for the trackable code public final static String ERROR_TB_DOES_NOT_EXIST = "does not exist in the system"; public final static String ERROR_TB_ELEMENT_EXCEPTION = "ElementNotFound Exception"; public final static String ERROR_TB_ARITHMETIC_OVERFLOW = "operation resulted in an overflow"; public final static String ERROR_TB_NOT_ACTIVATED = "hasn't been activated"; /** * some parts of the webpage don't correctly encode the name, therefore this pattern must be checked with a * trackable name that needs HTML encoding */ public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_lbHeading\">(.*?)</span>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<a id=\"ctl00_ContentBody_BugDetails_BugOwner\"[^>]+href=\"https?: public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_ORIGIN = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDCACHE = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>"); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_SPOTTEDUSER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDUNKNOWN = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_SPOTTEDOWNER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>", Pattern.DOTALL); /** Four groups */ public final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">"); public final static Pattern PATTERN_TRACKABLE_ICON = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_TYPE = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_TRACKABLE_DISTANCE = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)"); public final static Pattern PATTERN_TRACKABLE_LOG = Pattern.compile("<tr class=\"Data BorderTop .+?/images/logtypes/([^.]+)\\.png[^>]+>&nbsp;([^<]+)</td>.+?guid.+?>([^<]+)</a>.+?(?:guid=([^\"]+)\">(<span[^>]+>)?([^<]+)</.+?)?<td colspan=\"4\">\\s*<div>(.*?)</div>\\s*(?:<ul.+?ul>)?\\s*</td>\\s*</tr>"); public final static Pattern PATTERN_TRACKABLE_LOG_IMAGES = Pattern.compile("<li><a href=\"([^\"]+)\".+?LogImgTitle.+?>([^<]+)</"); /** * Patterns for parsing the result of a search (next) */ public final static Pattern PATTERN_SEARCH_TYPE = Pattern.compile("<td class=\"Merge\">.*?<img src=\"[^\"]*/images/wpttypes/[^.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>"); public final static Pattern PATTERN_SEARCH_GUIDANDDISABLED = Pattern.compile("SearchResultsWptType.*?<a href=\"[^\"]*\" class=\"lnk ([^\"]*)\"><span>([^<]*)</span>[^|]*[|][^|]*[|]([^<]*)<"); /** Two groups **/ public final static Pattern PATTERN_SEARCH_TRACKABLES = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>"); /** Second group used */ public final static Pattern PATTERN_SEARCH_TRACKABLESINSIDE = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)"); public final static Pattern PATTERN_SEARCH_DIRECTION_DISTANCE = Pattern.compile("<img src=\"/images/icons/compass/([^\\.]+)\\.gif\"[^>]*>[^<]*<br />([^<]+)</span>"); public final static Pattern PATTERN_SEARCH_DIFFICULTY_TERRAIN = Pattern.compile("<span class=\"small\">([0-5]([\\.,]5)?)/([0-5]([\\.,]5)?)</span><br />"); public final static Pattern PATTERN_SEARCH_CONTAINER = Pattern.compile("<img src=\"/images/icons/container/([^\\.]+)\\.gif\""); public final static Pattern PATTERN_SEARCH_GEOCODE = Pattern.compile("\\|\\W*(GC[0-9A-Z]+)[^\\|]*\\|"); public final static Pattern PATTERN_SEARCH_ID = Pattern.compile("name=\"CID\"[^v]*value=\"(\\d+)\""); public final static Pattern PATTERN_SEARCH_FAVORITE = Pattern.compile("favorite-rank\">([0-9,.]+)</span>"); public final static Pattern PATTERN_SEARCH_TOTALCOUNT = Pattern.compile("<span>Total Records\\D*(\\d+)<"); public final static Pattern PATTERN_SEARCH_RECAPTCHA = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>"); public final static Pattern PATTERN_SEARCH_RECAPTCHACHALLENGE = Pattern.compile("challenge : '([^']+)'"); public final static Pattern PATTERN_SEARCH_HIDDEN_DATE = Pattern.compile("<td style=\"width:70px\">[^<]+<span class=\"small\">([^<]+)</span>"); /** * Patterns for waypoints */ public final static Pattern PATTERN_WPTYPE = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg"); public final static Pattern PATTERN_WPPREFIXORLOOKUPORLATLON = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>"); public final static Pattern PATTERN_WPNAME = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>"); public final static Pattern PATTERN_WPNOTE = Pattern.compile("colspan=\"6\">(.*)" + Pattern.quote("</td>"), Pattern.DOTALL); /** * Patterns for different purposes */ /** replace line break and paragraph tags */ public final static Pattern PATTERN_LINEBREAK = Pattern.compile("<(br|p)[^>]*>"); public final static Pattern PATTERN_TYPEBOX = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>" + "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_TYPE2 = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE); // FIXME: pattern is over specified public final static Pattern PATTERN_TRACKABLE = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>" + "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>" + "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>" + "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+" + "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_MAINTENANCE = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_OK1 = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_OK2 = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE); public final static Pattern PATTERN_IMAGE_UPLOAD_URL = Pattern.compile("title=\"Click for Larger Image\"\\s*src=\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_VIEWSTATEFIELDCOUNT = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_VIEWSTATES = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); public final static Pattern PATTERN_USERTOKEN = Pattern.compile("userToken\\s*=\\s*'([^']+)'"); public final static Pattern PATTERN_LIST_PQ = Pattern.compile(Pattern.quote("(") + "(\\d+)" + Pattern.quote(")") + ".+?guid=(.+?)\".*?title=\"(.+?)\""); /** Live Map since 14.02.2012 */ public final static Pattern PATTERN_USERSESSION = Pattern.compile("UserSession\\('([^']+)'"); public final static Pattern PATTERN_SESSIONTOKEN = Pattern.compile("sessionToken:'([^']+)'"); public final static Pattern PATTERN_LOG_IMAGE_UPLOAD = Pattern.compile("/seek/upload\\.aspx\\?LID=(\\d+)", Pattern.CASE_INSENSITIVE); public final static String STRING_PREMIUMONLY_2 = "Sorry, the owner of this listing has made it viewable to Premium Members only."; public final static String STRING_PREMIUMONLY_1 = "has chosen to make this cache listing visible to Premium Members only."; public final static String STRING_UNPUBLISHED_OTHER = "you cannot view this cache listing until it has been published"; public final static String STRING_UNPUBLISHED_FROM_SEARCH = "class=\"UnpublishedCacheSearchWidge\""; public final static String STRING_UNKNOWN_ERROR = "An Error Has Occurred"; public final static String STRING_DISABLED = "<li>This cache is temporarily unavailable."; public final static String STRING_ARCHIVED = "<li>This cache has been archived,"; public final static String STRING_CACHEDETAILS = "id=\"cacheDetails\""; /** Number of logs to retrieve from GC.com */ public final static int NUMBER_OF_LOGS = 35; /** Maximum number of chars for personal note. **/ public final static int PERSONAL_NOTE_MAX_CHARS = 500; private final static String SEQUENCE_GCID = "0123456789ABCDEFGHJKMNPQRTVWXYZ"; private final static long GC_BASE31 = 31; private final static long GC_BASE16 = 16; public static long gccodeToGCId(final String gccode) { long base = GC_BASE31; final String geocodeWO = gccode.substring(2).toUpperCase(Locale.US); if ((geocodeWO.length() < 4) || (geocodeWO.length() == 4 && SEQUENCE_GCID.indexOf(geocodeWO.charAt(0)) < 16)) { base = GC_BASE16; } long gcid = 0; for (int p = 0; p < geocodeWO.length(); p++) { gcid = base * gcid + SEQUENCE_GCID.indexOf(geocodeWO.charAt(p)); } if (base == GC_BASE31) { gcid += Math.pow(16, 4) - 16 * Math.pow(31, 3); } return gcid; } private GCConstants() { // this class shall not have instances } }
package org.apache.fop.svg; import org.apache.fop.pdf.*; import org.apache.fop.layout.*; import org.apache.fop.fonts.*; import org.apache.fop.render.pdf.*; import org.apache.fop.image.*; import org.apache.fop.datatypes.ColorSpace; import org.apache.fop.render.pdf.CIDFont; import org.apache.fop.render.pdf.fonts.LazyFont; import org.apache.batik.ext.awt.g2d.*; import org.apache.batik.ext.awt.image.GraphicsUtil; import java.text.AttributedCharacterIterator; import java.text.CharacterIterator; import java.awt.*; import java.awt.Font; import java.awt.Image; import java.awt.image.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.image.renderable.*; import java.io.*; import java.util.Map; import java.util.Vector; import java.util.Hashtable; /** * This concrete implementation of <tt>AbstractGraphics2D</tt> is a * simple help to programmers to get started with their own * implementation of <tt>Graphics2D</tt>. * <tt>DefaultGraphics2D</tt> implements all the abstract methods * is <tt>AbstractGraphics2D</tt> and makes it easy to start * implementing a <tt>Graphic2D</tt> piece-meal. * * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a> * @version $Id$ * @see org.apache.batik.ext.awt.g2d.AbstractGraphics2D */ public class PDFGraphics2D extends AbstractGraphics2D { boolean standalone = false; /** * the PDF Document being created */ protected PDFDocument pdfDoc; /** * the current annotation list to add annotations to */ PDFAnnotList currentAnnotList = null; protected FontState fontState; protected FontState ovFontState = null; /** * the current stream to add PDF commands to */ StringWriter currentStream = new StringWriter(); /** * the current (internal) font name */ protected String currentFontName; /** * the current font size in millipoints */ protected int currentFontSize; /** * the current vertical position in millipoints from bottom */ protected int currentYPosition = 0; /** * the current horizontal position in millipoints from left */ protected int currentXPosition = 0; /** * the current colour for use in svg */ PDFColor currentColour = new PDFColor(0, 0, 0); /** * Create a new PDFGraphics2D with the given pdf document info. * This is used to create a Graphics object for use inside an already * existing document. */ public PDFGraphics2D(boolean textAsShapes, FontState fs, PDFDocument doc, String font, int size, int xpos, int ypos) { super(textAsShapes); pdfDoc = doc; currentFontName = font; currentFontSize = size; currentYPosition = ypos; currentXPosition = xpos; fontState = fs; } public PDFGraphics2D(boolean textAsShapes) { super(textAsShapes); } public String getString() { return currentStream.toString(); } public void setGraphicContext(GraphicContext c) { gc = c; } public void setOverrideFontState(FontState infont) { ovFontState = infont; } /** * This constructor supports the create method */ public PDFGraphics2D(PDFGraphics2D g) { super(g); } /** * Creates a new <code>Graphics</code> object that is * a copy of this <code>Graphics</code> object. * @return a new graphics context that is a copy of * this graphics context. */ public Graphics create() { return new PDFGraphics2D(this); } /** * This is a pdf specific method used to add a link to the * pdf document. */ public void addLink(Shape bounds, AffineTransform trans, String dest, int linkType) { if(currentAnnotList == null) { currentAnnotList = pdfDoc.makeAnnotList(); } AffineTransform at = getTransform(); Shape b = at.createTransformedShape(bounds); b = trans.createTransformedShape(b); Rectangle rect = b.getBounds(); // this handles the / 1000 in PDFLink rect.x = rect.x * 1000; rect.y = rect.y * 1000; rect.height = -rect.height * 1000; rect.width = rect.width * 1000; currentAnnotList.addLink(pdfDoc.makeLink(rect, dest, linkType)); } public PDFAnnotList getAnnotList() { return currentAnnotList; } /** * Draws as much of the specified image as is currently available. * The image is drawn with its top-left corner at * (<i>x</i>,&nbsp;<i>y</i>) in this graphics context's coordinate * space. Transparent pixels in the image do not affect whatever * pixels are already there. * <p> * This method returns immediately in all cases, even if the * complete image has not yet been loaded, and it has not been dithered * and converted for the current output device. * <p> * If the image has not yet been completely loaded, then * <code>drawImage</code> returns <code>false</code>. As more of * the image becomes available, the process that draws the image notifies * the specified image observer. * @param img the specified image to be drawn. * @param x the <i>x</i> coordinate. * @param y the <i>y</i> coordinate. * @param observer object to be notified as more of * the image is converted. * @see java.awt.Image * @see java.awt.image.ImageObserver * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) */ public boolean drawImage(Image img, int x, int y, ImageObserver observer) { // System.err.println("drawImage:x, y"); final int width = img.getWidth(observer); final int height = img.getHeight(observer); if (width == -1 || height == -1) { return false; } Dimension size = new Dimension(width, height); BufferedImage buf = buildBufferedImage(size); java.awt.Graphics2D g = buf.createGraphics(); g.setComposite(AlphaComposite.SrcOver); g.setBackground(new Color(1, 1, 1, 0)); g.setPaint(new Color(1, 1, 1, 0)); g.fillRect(0, 0, width, height); g.clip(new Rectangle(0, 0, buf.getWidth(), buf.getHeight())); if (!g.drawImage(img, 0, 0, observer)) { return false; } g.dispose(); final byte[] result = new byte[buf.getWidth() * buf.getHeight() * 3]; final byte[] mask = new byte[buf.getWidth() * buf.getHeight()]; Raster raster = buf.getData(); DataBuffer bd = raster.getDataBuffer(); int count = 0; int maskpos = 0; int[] iarray; int i, j, val, alpha, add, mult; switch (bd.getDataType()) { case DataBuffer.TYPE_INT: int[][] idata = ((DataBufferInt)bd).getBankData(); for (i = 0; i < idata.length; i++) { iarray = idata[i]; for (j = 0; j < iarray.length; j++) { val = iarray[j]; alpha = val >>> 24; // mask[maskpos++] = (byte)((idata[i][j] >> 24) & 0xFF); if (alpha != 255) { // System.out.println("Alpha: " + alpha); // Composite with opaque white... add = (255 - alpha); mult = (alpha << 16) / 255; result[count++] = (byte)(add + ((((val >> 16) & 0xFF) * mult) >> 16)); result[count++] = (byte)(add + ((((val >> 8) & 0xFF) * mult) >> 16)); result[count++] = (byte)(add + ((((val) & 0xFF) * mult) >> 16)); } else { result[count++] = (byte)((val >> 16) & 0xFF); result[count++] = (byte)((val >> 8) & 0xFF); result[count++] = (byte)((val) & 0xFF); } } } break; default: // error break; } try { FopImage fopimg = new TempImage(width, height, result, mask); int xObjectNum = this.pdfDoc.addImage(fopimg); AffineTransform at = getTransform(); double[] matrix = new double[6]; at.getMatrix(matrix); currentStream.write("q\n"); Shape imclip = getClip(); writeClip(imclip); currentStream.write("" + matrix[0] + " " + matrix[1] + " " + matrix[2] + " " + matrix[3] + " " + matrix[4] + " " + matrix[5] + " cm\n"); currentStream.write("" + width + " 0 0 " + (-height) + " " + x + " " + (y + height) + " cm\n" + "/Im" + xObjectNum + " Do\nQ\n"); } catch (Exception e) { e.printStackTrace(); } return true; } public BufferedImage buildBufferedImage(Dimension size) { return new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); } class TempImage implements FopImage { int m_height; int m_width; int m_bitsPerPixel; ColorSpace m_colorSpace; int m_bitmapSiye; byte[] m_bitmaps; byte[] m_mask; PDFColor transparent = new PDFColor(255, 255, 255); TempImage(int width, int height, byte[] result, byte[] mask) throws FopImageException { this.m_height = height; this.m_width = width; this.m_bitsPerPixel = 8; this.m_colorSpace = new ColorSpace(ColorSpace.DEVICE_RGB); // this.m_isTransparent = false; // this.m_bitmapsSize = this.m_width * this.m_height * 3; this.m_bitmaps = result; this.m_mask = mask; } public String getURL() { return "" + m_bitmaps; } // image size public int getWidth() throws FopImageException { return m_width; } public int getHeight() throws FopImageException { return m_height; } // DeviceGray, DeviceRGB, or DeviceCMYK public ColorSpace getColorSpace() throws FopImageException { return m_colorSpace; } // bits per pixel public int getBitsPerPixel() throws FopImageException { return m_bitsPerPixel; } // For transparent images public boolean isTransparent() throws FopImageException { return transparent != null; } public PDFColor getTransparentColor() throws FopImageException { return transparent; } public byte[] getMask() throws FopImageException { return m_mask; } // get the image bytes, and bytes properties // get uncompressed image bytes public byte[] getBitmaps() throws FopImageException { return m_bitmaps; } // width * (bitsPerPixel / 8) * height, no ? public int getBitmapsSize() throws FopImageException { return m_width * m_height * 3; } // get compressed image bytes // I don't know if we really need it, nor if it // should be changed... public byte[] getRessourceBytes() throws FopImageException { return null; } public int getRessourceBytesSize() throws FopImageException { return 0; } // return null if no corresponding PDFFilter public PDFFilter getPDFFilter() throws FopImageException { return null; } // release memory public void close() {} } /** * Draws as much of the specified image as has already been scaled * to fit inside the specified rectangle. * <p> * The image is drawn inside the specified rectangle of this * graphics context's coordinate space, and is scaled if * necessary. Transparent pixels do not affect whatever pixels * are already there. * <p> * This method returns immediately in all cases, even if the * entire image has not yet been scaled, dithered, and converted * for the current output device. * If the current output representation is not yet complete, then * <code>drawImage</code> returns <code>false</code>. As more of * the image becomes available, the process that draws the image notifies * the image observer by calling its <code>imageUpdate</code> method. * <p> * A scaled version of an image will not necessarily be * available immediately just because an unscaled version of the * image has been constructed for this output device. Each size of * the image may be cached separately and generated from the original * data in a separate image production sequence. * @param img the specified image to be drawn. * @param x the <i>x</i> coordinate. * @param y the <i>y</i> coordinate. * @param width the width of the rectangle. * @param height the height of the rectangle. * @param observer object to be notified as more of * the image is converted. * @see java.awt.Image * @see java.awt.image.ImageObserver * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) */ public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) { System.out.println("drawImage"); return true; } /** * Disposes of this graphics context and releases * any system resources that it is using. * A <code>Graphics</code> object cannot be used after * <code>dispose</code>has been called. * <p> * When a Java program runs, a large number of <code>Graphics</code> * objects can be created within a short time frame. * Although the finalization process of the garbage collector * also disposes of the same system resources, it is preferable * to manually free the associated resources by calling this * method rather than to rely on a finalization process which * may not run to completion for a long period of time. * <p> * Graphics objects which are provided as arguments to the * <code>paint</code> and <code>update</code> methods * of components are automatically released by the system when * those methods return. For efficiency, programmers should * call <code>dispose</code> when finished using * a <code>Graphics</code> object only if it was created * directly from a component or another <code>Graphics</code> object. * @see java.awt.Graphics#finalize * @see java.awt.Component#paint * @see java.awt.Component#update * @see java.awt.Component#getGraphics * @see java.awt.Graphics#create */ public void dispose() { // System.out.println("dispose"); pdfDoc = null; fontState = null; currentStream = null; currentFontName = null; currentColour = null; } /** * Strokes the outline of a <code>Shape</code> using the settings of the * current <code>Graphics2D</code> context. The rendering attributes * applied include the <code>Clip</code>, <code>Transform</code>, * <code>Paint</code>, <code>Composite</code> and * <code>Stroke</code> attributes. * @param s the <code>Shape</code> to be rendered * @see #setStroke * @see #setPaint * @see java.awt.Graphics#setColor * @see #transform * @see #setTransform * @see #clip * @see #setClip * @see #setComposite */ public void draw(Shape s) { // System.out.println("draw(Shape)"); currentStream.write("q\n"); Shape imclip = getClip(); writeClip(imclip); Color c = getColor(); applyColor(c, false); applyPaint(getPaint(), false); applyStroke(getStroke()); PathIterator iter = s.getPathIterator(getTransform()); while (!iter.isDone()) { double vals[] = new double[6]; int type = iter.currentSegment(vals); switch (type) { case PathIterator.SEG_CUBICTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4]) + " " + PDFNumber.doubleOut(vals[5]) + " c\n"); break; case PathIterator.SEG_LINETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " l\n"); break; case PathIterator.SEG_MOVETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " m\n"); break; case PathIterator.SEG_QUADTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " y\n"); break; case PathIterator.SEG_CLOSE: currentStream.write("h\n"); break; default: break; } iter.next(); } doDrawing(false, true, false); currentStream.write("Q\n"); } protected void writeClip(Shape s) { if (s == null) { return; } PathIterator iter = s.getPathIterator(getTransform()); while (!iter.isDone()) { double vals[] = new double[6]; int type = iter.currentSegment(vals); switch (type) { case PathIterator.SEG_CUBICTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4]) + " " + PDFNumber.doubleOut(vals[5]) + " c\n"); break; case PathIterator.SEG_LINETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " l\n"); break; case PathIterator.SEG_MOVETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " m\n"); break; case PathIterator.SEG_QUADTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " y\n"); break; case PathIterator.SEG_CLOSE: currentStream.write("h\n"); break; default: break; } iter.next(); } // clip area currentStream.write("W\n"); currentStream.write("n\n"); } protected void applyColor(Color col, boolean fill) { Color c = col; if (c.getColorSpace().getType() == java.awt.color.ColorSpace.TYPE_RGB) { currentColour = new PDFColor(c.getRed(), c.getGreen(), c.getBlue()); currentStream.write(currentColour.getColorSpaceOut(fill)); } else if (c.getColorSpace().getType() == java.awt.color.ColorSpace.TYPE_CMYK) { float[] cComps = c.getColorComponents(new float[3]); double[] cmyk = new double[3]; for (int i = 0; i < 3; i++) { // convert the float elements to doubles for pdf cmyk[i] = cComps[i]; } currentColour = new PDFColor(cmyk[0], cmyk[1], cmyk[2], cmyk[3]); currentStream.write(currentColour.getColorSpaceOut(fill)); } else if (c.getColorSpace().getType() == java.awt.color.ColorSpace.TYPE_2CLR) { // used for black/magenta float[] cComps = c.getColorComponents(new float[1]); double[] blackMagenta = new double[1]; for (int i = 0; i < 1; i++) { blackMagenta[i] = cComps[i]; } // currentColour = new PDFColor(blackMagenta[0], blackMagenta[1]); currentStream.write(currentColour.getColorSpaceOut(fill)); } else { System.err.println("Color Space not supported by PDFGraphics2D"); } } protected void applyPaint(Paint paint, boolean fill) { if (paint instanceof GradientPaint) { GradientPaint gp = (GradientPaint)paint; Color c1 = gp.getColor1(); Color c2 = gp.getColor2(); Point2D p1 = gp.getPoint1(); Point2D p2 = gp.getPoint2(); boolean cyclic = gp.isCyclic(); Vector theCoords = new Vector(); theCoords.addElement(new Double(p1.getX())); theCoords.addElement(new Double(p1.getY())); theCoords.addElement(new Double(p2.getX())); theCoords.addElement(new Double(p2.getY())); Vector theExtend = new Vector(); theExtend.addElement(new Boolean(true)); theExtend.addElement(new Boolean(true)); Vector theDomain = new Vector(); theDomain.addElement(new Double(0)); theDomain.addElement(new Double(1)); Vector theEncode = new Vector(); theEncode.addElement(new Double(0)); theEncode.addElement(new Double(1)); theEncode.addElement(new Double(0)); theEncode.addElement(new Double(1)); Vector theBounds = new Vector(); theBounds.addElement(new Double(0)); theBounds.addElement(new Double(1)); Vector theFunctions = new Vector(); Vector someColors = new Vector(); PDFColor color1 = new PDFColor(c1.getRed(), c1.getGreen(), c1.getBlue()); someColors.addElement(color1); PDFColor color2 = new PDFColor(c2.getRed(), c2.getGreen(), c2.getBlue()); someColors.addElement(color2); PDFFunction myfunc = this.pdfDoc.makeFunction(2, theDomain, null, color1.getVector(), color2.getVector(), 1.0); ColorSpace aColorSpace = new ColorSpace(ColorSpace.DEVICE_RGB); PDFPattern myPat = this.pdfDoc.createGradient(false, aColorSpace, someColors, null, theCoords); currentStream.write(myPat.getColorSpaceOut(fill)); } else if (paint instanceof TexturePaint) {} } protected void applyStroke(Stroke stroke) { if (stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke)stroke; float[] da = bs.getDashArray(); if (da != null) { currentStream.write("["); for (int count = 0; count < da.length; count++) { currentStream.write("" + ((int)da[count])); if (count < da.length - 1) { currentStream.write(" "); } } currentStream.write("] "); float offset = bs.getDashPhase(); currentStream.write(((int)offset) + " d\n"); } int ec = bs.getEndCap(); switch (ec) { case BasicStroke.CAP_BUTT: currentStream.write(0 + " J\n"); break; case BasicStroke.CAP_ROUND: currentStream.write(1 + " J\n"); break; case BasicStroke.CAP_SQUARE: currentStream.write(2 + " J\n"); break; } int lj = bs.getLineJoin(); switch (lj) { case BasicStroke.JOIN_MITER: currentStream.write(0 + " j\n"); break; case BasicStroke.JOIN_ROUND: currentStream.write(1 + " j\n"); break; case BasicStroke.JOIN_BEVEL: currentStream.write(2 + " j\n"); break; } float lw = bs.getLineWidth(); currentStream.write(PDFNumber.doubleOut(lw) + " w\n"); float ml = bs.getMiterLimit(); currentStream.write(PDFNumber.doubleOut(ml) + " M\n"); } } /** * Renders a {@link RenderedImage}, * applying a transform from image * space into user space before drawing. * The transformation from user space into device space is done with * the current <code>Transform</code> in the <code>Graphics2D</code>. * The specified transformation is applied to the image before the * transform attribute in the <code>Graphics2D</code> context is applied. * The rendering attributes applied include the <code>Clip</code>, * <code>Transform</code>, and <code>Composite</code> attributes. Note * that no rendering is done if the specified transform is * noninvertible. * @param img the image to be rendered * @param xform the transformation from image space into user space * @see #transform * @see #setTransform * @see #setComposite * @see #clip * @see #setClip */ public void drawRenderedImage(RenderedImage img, AffineTransform xform) { System.out.println("drawRenderedImage"); } /** * Renders a * {@link RenderableImage}, * applying a transform from image space into user space before drawing. * The transformation from user space into device space is done with * the current <code>Transform</code> in the <code>Graphics2D</code>. * The specified transformation is applied to the image before the * transform attribute in the <code>Graphics2D</code> context is applied. * The rendering attributes applied include the <code>Clip</code>, * <code>Transform</code>, and <code>Composite</code> attributes. Note * that no rendering is done if the specified transform is * noninvertible. * <p> * Rendering hints set on the <code>Graphics2D</code> object might * be used in rendering the <code>RenderableImage</code>. * If explicit control is required over specific hints recognized by a * specific <code>RenderableImage</code>, or if knowledge of which hints * are used is required, then a <code>RenderedImage</code> should be * obtained directly from the <code>RenderableImage</code> * and rendered using * {@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}. * @param img the image to be rendered * @param xform the transformation from image space into user space * @see #transform * @see #setTransform * @see #setComposite * @see #clip * @see #setClip * @see #drawRenderedImage */ public void drawRenderableImage(RenderableImage img, AffineTransform xform) { System.out.println("drawRenderableImage"); } /** * Renders the text specified by the specified <code>String</code>, * using the current <code>Font</code> and <code>Paint</code> attributes * in the <code>Graphics2D</code> context. * The baseline of the first character is at position * (<i>x</i>,&nbsp;<i>y</i>) in the User Space. * The rendering attributes applied include the <code>Clip</code>, * <code>Transform</code>, <code>Paint</code>, <code>Font</code> and * <code>Composite</code> attributes. For characters in script systems * such as Hebrew and Arabic, the glyphs can be rendered from right to * left, in which case the coordinate supplied is the location of the * leftmost character on the baseline. * @param s the <code>String</code> to be rendered * @param x,&nbsp;y the coordinates where the <code>String</code> * should be rendered * @see #setPaint * @see java.awt.Graphics#setColor * @see java.awt.Graphics#setFont * @see #setTransform * @see #setComposite * @see #setClip */ public void drawString(String s, float x, float y) { // System.out.println("drawString(String)"); if(ovFontState == null) { Font gFont = getFont(); String n = gFont.getFamily(); if (n.equals("sanserif")) { n = "sans-serif"; } int siz = gFont.getSize(); String style = gFont.isItalic() ? "italic" : "normal"; String weight = gFont.isBold() ? "bold" : "normal"; try { fontState = new FontState(fontState.getFontInfo(), n, style, weight, siz * 1000, 0); } catch (org.apache.fop.apps.FOPException fope) { fope.printStackTrace(); } } else { fontState = ovFontState; ovFontState = null; } String name; int size; name = fontState.getFontName(); size = fontState.getFontSize() / 1000; if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { this.currentFontName = name; this.currentFontSize = size; currentStream.write("/" + name + " " + size + " Tf\n"); } currentStream.write("q\n"); Shape imclip = getClip(); writeClip(imclip); Color c = getColor(); applyColor(c, true); c = getBackground(); applyColor(c, false); currentStream.write("BT\n"); Hashtable kerning = null; boolean kerningAvailable = false; kerning = fontState.getKerning(); if (kerning != null &&!kerning.isEmpty()) { kerningAvailable = true; } // This assumes that *all* CIDFonts use a /ToUnicode mapping boolean useMultiByte = false; org.apache.fop.render.pdf.Font f = (org.apache.fop.render.pdf.Font)fontState.getFontInfo().getFonts().get(name); if (f instanceof LazyFont){ if(((LazyFont) f).getRealFont() instanceof CIDFont){ useMultiByte = true; } } else if (f instanceof CIDFont){ useMultiByte = true; } // String startText = useMultiByte ? "<FEFF" : "("; String startText = useMultiByte ? "<" : "("; String endText = useMultiByte ? "> " : ") "; AffineTransform trans = getTransform(); trans.translate(x, y); double[] vals = new double[6]; trans.getMatrix(vals); currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4]) + " " + PDFNumber.doubleOut(vals[5]) + " cm\n"); currentStream.write("1 0 0 -1 0 0 Tm [" + startText); int l = s.length(); for (int i = 0; i < l; i++) { char ch = fontState.mapChar(s.charAt(i)); if (!useMultiByte) { if (ch > 127) { currentStream.write("\\"); currentStream.write(Integer.toOctalString((int)ch)); } else { switch (ch) { case '(': case ')': case '\\': currentStream.write("\\"); break; } currentStream.write(ch); } } else { currentStream.write(getUnicodeString(ch)); } if (kerningAvailable && (i + 1) < l) { addKerning(currentStream, (new Integer((int)ch)), (new Integer((int)fontState.mapChar(s.charAt(i + 1)))), kerning, startText, endText); } } currentStream.write(endText); currentStream.write("] TJ\n"); currentStream.write("ET\n"); currentStream.write("Q\n"); } private void addKerning(StringWriter buf, Integer ch1, Integer ch2, Hashtable kerning, String startText, String endText) { Hashtable kernPair = (Hashtable)kerning.get(ch1); if (kernPair != null) { Integer width = (Integer)kernPair.get(ch2); if (width != null) { currentStream.write(endText + (-width.intValue()) + " " + startText); } } } /** * Convert a char to a multibyte hex representation */ private String getUnicodeString(char c) { StringBuffer buf = new StringBuffer(4); byte[] uniBytes = null; try { char[] a = { c }; uniBytes = new String(a).getBytes("UnicodeBigUnmarked"); } catch (Exception e) { // This should never fail } for (int i = 0; i < uniBytes.length; i++) { int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) : (int)uniBytes[i]; String hexString = Integer.toHexString(b); if (hexString.length() == 1) buf = buf.append("0" + hexString); else buf = buf.append(hexString); } return buf.toString(); } /** * Renders the text of the specified iterator, using the * <code>Graphics2D</code> context's current <code>Paint</code>. The * iterator must specify a font * for each character. The baseline of the * first character is at position (<i>x</i>,&nbsp;<i>y</i>) in the * User Space. * The rendering attributes applied include the <code>Clip</code>, * <code>Transform</code>, <code>Paint</code>, and * <code>Composite</code> attributes. * For characters in script systems such as Hebrew and Arabic, * the glyphs can be rendered from right to left, in which case the * coordinate supplied is the location of the leftmost character * on the baseline. * @param iterator the iterator whose text is to be rendered * @param x,&nbsp;y the coordinates where the iterator's text is to be * rendered * @see #setPaint * @see java.awt.Graphics#setColor * @see #setTransform * @see #setComposite * @see #setClip */ public void drawString(AttributedCharacterIterator iterator, float x, float y) { System.err.println("drawString(AttributedCharacterIterator)"); Shape imclip = getClip(); writeClip(imclip); Color c = getColor(); applyColor(c, true); c = getBackground(); applyColor(c, false); currentStream.write("BT\n"); AffineTransform trans = getTransform(); trans.translate(x, y); double[] vals = new double[6]; trans.getMatrix(vals); for (char ch = iterator.first(); ch != CharacterIterator.DONE; ch = iterator.next()) { Map attr = iterator.getAttributes(); String name = fontState.getFontName(); int size = fontState.getFontSize(); if ((!name.equals(this.currentFontName)) || (size != this.currentFontSize)) { this.currentFontName = name; this.currentFontSize = size; currentStream.write("/" + name + " " + (size / 1000) + " Tf\n"); } currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4]) + " " + PDFNumber.doubleOut(vals[5]) + " Tm (" + ch + ") Tj\n"); } currentStream.write("ET\n"); } /** * Fills the interior of a <code>Shape</code> using the settings of the * <code>Graphics2D</code> context. The rendering attributes applied * include the <code>Clip</code>, <code>Transform</code>, * <code>Paint</code>, and <code>Composite</code>. * @param s the <code>Shape</code> to be filled * @see #setPaint * @see java.awt.Graphics#setColor * @see #transform * @see #setTransform * @see #setComposite * @see #clip * @see #setClip */ public void fill(Shape s) { // System.err.println("fill"); Color c; c = getBackground(); if(c.getAlpha() == 0) { c = getColor(); if(c.getAlpha() == 0) { return; } } currentStream.write("q\n"); Shape imclip = getClip(); writeClip(imclip); c = getColor(); applyColor(c, true); c = getBackground(); applyColor(c, false); applyPaint(getPaint(), true); PathIterator iter = s.getPathIterator(getTransform()); while (!iter.isDone()) { double vals[] = new double[6]; int type = iter.currentSegment(vals); switch (type) { case PathIterator.SEG_CUBICTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " " + PDFNumber.doubleOut(vals[4]) + " " + PDFNumber.doubleOut(vals[5]) + " c\n"); break; case PathIterator.SEG_LINETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " l\n"); break; case PathIterator.SEG_MOVETO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " m\n"); break; case PathIterator.SEG_QUADTO: currentStream.write(PDFNumber.doubleOut(vals[0]) + " " + PDFNumber.doubleOut(vals[1]) + " " + PDFNumber.doubleOut(vals[2]) + " " + PDFNumber.doubleOut(vals[3]) + " y\n"); break; case PathIterator.SEG_CLOSE: currentStream.write("h\n"); break; default: break; } iter.next(); } doDrawing(true, false, iter.getWindingRule() == PathIterator.WIND_EVEN_ODD); currentStream.write("Q\n"); } protected void doDrawing(boolean fill, boolean stroke, boolean nonzero) { if (fill) { if (stroke) { if (nonzero) currentStream.write("B*\n"); else currentStream.write("B\n"); } else { if (nonzero) currentStream.write("f*\n"); else currentStream.write("f\n"); } } else { // if(stroke) currentStream.write("S\n"); } } /** * Returns the device configuration associated with this * <code>Graphics2D</code>. */ public GraphicsConfiguration getDeviceConfiguration() { return new PDFGraphicsConfiguration(); } /** * Our implementation of the class that returns information about * roughly what we can handle and want to see (alpha for example). */ static class PDFGraphicsConfiguration extends GraphicsConfiguration { // We use this to get a good colormodel.. static BufferedImage BIWithAlpha = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); // We use this to get a good colormodel.. static BufferedImage BIWithOutAlpha = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); /** * Construct a buffered image with an alpha channel, unless * transparencty is OPAQUE (no alpha at all). */ public BufferedImage createCompatibleImage(int width, int height, int transparency) { if (transparency == Transparency.OPAQUE) return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); else return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } /** * Construct a buffered image with an alpha channel. */ public BufferedImage createCompatibleImage(int width, int height) { return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } /** * FIXX ME: This should return the page bounds in Pts, * I couldn't figure out how to get this for the current * page from the PDFDocument (this still works for now, * but it should be fixed...). */ public Rectangle getBounds() { return null; } /** * Return a good default color model for this 'device'. */ public ColorModel getColorModel() { return BIWithAlpha.getColorModel(); } /** * Return a good color model given <tt>transparency</tt> */ public ColorModel getColorModel(int transparency) { if (transparency == Transparency.OPAQUE) return BIWithOutAlpha.getColorModel(); else return BIWithAlpha.getColorModel(); } /** * The default transform (1:1). */ public AffineTransform getDefaultTransform() { return new AffineTransform(); } /** * The normalizing transform (1:1) (since we currently * render images at 72dpi, which we might want to change * in the future). */ public AffineTransform getNormalizingTransform() { return new AffineTransform(); } /** * Return our dummy instance of GraphicsDevice */ public GraphicsDevice getDevice() { return new PDFGraphicsDevice(this); } } /** * This implements the GraphicsDevice interface as appropriate for * a PDFGraphics2D. This is quite simple since we only have one * GraphicsConfiguration for now (this might change in the future * I suppose). */ static class PDFGraphicsDevice extends GraphicsDevice { /** * The Graphics Config that created us... */ GraphicsConfiguration gc; /** * @param The gc we should reference */ PDFGraphicsDevice(PDFGraphicsConfiguration gc) { this.gc = gc; } /** * Ignore template and return the only config we have */ public GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate gct) { return gc; } /** * Return an array of our one GraphicsConfig */ public GraphicsConfiguration[] getConfigurations() { return new GraphicsConfiguration[] { gc }; } /** * Return out sole GraphicsConfig. */ public GraphicsConfiguration getDefaultConfiguration() { return gc; } /** * Generate an IdString.. */ public String getIDstring() { return toString(); } /** * Let the caller know that we are "a printer" */ public int getType() { return GraphicsDevice.TYPE_PRINTER; } } /** * Used to create proper font metrics */ private Graphics2D fmg; { BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); fmg = bi.createGraphics(); } /** * Gets the font metrics for the specified font. * @return the font metrics for the specified font. * @param f the specified font * @see java.awt.Graphics#getFont * @see java.awt.FontMetrics * @see java.awt.Graphics#getFontMetrics() */ public FontMetrics getFontMetrics(Font f) { return fmg.getFontMetrics(f); } /** * Sets the paint mode of this graphics context to alternate between * this graphics context's current color and the new specified color. * This specifies that logical pixel operations are performed in the * XOR mode, which alternates pixels between the current color and * a specified XOR color. * <p> * When drawing operations are performed, pixels which are the * current color are changed to the specified color, and vice versa. * <p> * Pixels that are of colors other than those two colors are changed * in an unpredictable but reversible manner; if the same figure is * drawn twice, then all pixels are restored to their original values. * @param c1 the XOR alternation color */ public void setXORMode(Color c1) { System.out.println("setXORMode"); } /** * Copies an area of the component by a distance specified by * <code>dx</code> and <code>dy</code>. From the point specified * by <code>x</code> and <code>y</code>, this method * copies downwards and to the right. To copy an area of the * component to the left or upwards, specify a negative value for * <code>dx</code> or <code>dy</code>. * If a portion of the source rectangle lies outside the bounds * of the component, or is obscured by another window or component, * <code>copyArea</code> will be unable to copy the associated * pixels. The area that is omitted can be refreshed by calling * the component's <code>paint</code> method. * @param x the <i>x</i> coordinate of the source rectangle. * @param y the <i>y</i> coordinate of the source rectangle. * @param width the width of the source rectangle. * @param height the height of the source rectangle. * @param dx the horizontal distance to copy the pixels. * @param dy the vertical distance to copy the pixels. */ public void copyArea(int x, int y, int width, int height, int dx, int dy) { System.out.println("copyArea"); } }
package org.subethamail.core.admin; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.mail.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.core.admin.i.Eegor; import org.subethamail.core.post.OutboundMTA; import org.subethamail.core.smtp.SMTPService; import com.caucho.remote.HessianService; /** * Implements some basic plumbing methods for testing. * * @author Jeff Schnitzer * @author Scott Hernandez */ @Singleton @Named("eegor") @HessianService(urlPattern="/api/Eegor") public class EegorBean implements Eegor { private final static Logger log = LoggerFactory.getLogger(EegorBean.class); @Inject @OutboundMTA Session mailSession; String mailSmtpHost; String mailSmtpPort; /** Needed to get/set the fallback host */ @Inject SMTPService smtpService; /* (non-Javadoc) * @see org.subethamail.core.admin.i.EegorBringMeAnotherBrain#log(java.lang.String) */ public void log(String msg) { log.info(msg); } /* * (non-Javadoc) */ @RolesAllowed("siteAdmin") public void enableTestMode(String mtaHost) { log.debug(" if (!this.isTestModeEnabled()) { this.mailSmtpHost = this.mailSession.getProperties().getProperty("mail.smtp.host"); this.mailSmtpPort = this.mailSession.getProperties().getProperty("mail.smtp.port"); } // If there was a port, separate the two String[] parts = mtaHost.split(":"); String newHost = parts[0]; String newPort = (parts.length > 1) ? parts[1] : "25"; //store old value, and update the overrides this.mailSession.getProperties().setProperty("mail.smtp.host", newHost); this.mailSession.getProperties().setProperty("mail.smtp.port", newPort); } /* * (non-Javadoc) */ @RolesAllowed("siteAdmin") public void disableTestMode() { //if (!this.isTestModeEnabled()) if (this.mailSmtpHost == null) { log.warn("Test mode already disabled"); } else { log.info("Restoring base mail configuration"); this.mailSession.getProperties().setProperty("mail.smtp.host", this.mailSmtpHost); this.mailSession.getProperties().setProperty("mail.smtp.port", this.mailSmtpPort); this.mailSmtpHost = null; this.mailSmtpPort = null; } } public boolean isTestModeEnabled() { return this.mailSmtpHost != null; //return true; } /* (non-Javadoc) * @see org.subethamail.core.admin.i.Eegor#setFallbackHost(java.lang.String) */ @Override public void setFallbackHost(String host) { this.smtpService.setFallbackHost(host); } }
import com.sun.star.uno.XComponentContext; import com.sun.star.util.XMacroExpander; import java.util.Calendar; import com.sun.star.beans.Property; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.i18n.NumberFormatIndex; import com.sun.star.lang.Locale; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.Any; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.RuntimeException; import com.sun.star.uno.UnoRuntime; import com.sun.star.util.DateTime; import com.sun.star.util.XNumberFormatsSupplier; import com.sun.star.util.XNumberFormatter; public class Helper { /** Creates a new instance of Helper */ public Helper() { } public static long convertUnoDatetoInteger(com.sun.star.util.Date DateValue) { java.util.Calendar oCal = java.util.Calendar.getInstance(); oCal.set(DateValue.Year, DateValue.Month, DateValue.Day); java.util.Date dTime = oCal.getTime(); long lTime = dTime.getTime(); long lDate = lTime / (3600 * 24000); return lDate; } public static void setUnoPropertyValue(Object oUnoObject, String PropertyName, Object PropertyValue) { try { XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUnoObject); if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName)) xPSet.setPropertyValue(PropertyName, PropertyValue); else{ Property[] selementnames = xPSet.getPropertySetInfo().getProperties(); throw new java.lang.IllegalArgumentException("No Such Property: '" + PropertyName+ "'"); } } catch (Exception exception) { exception.printStackTrace(System.out); } } public static Object getUnoObjectbyName(Object oUnoObject, String ElementName) { try { com.sun.star.container.XNameAccess xName = (com.sun.star.container.XNameAccess) UnoRuntime.queryInterface(com.sun.star.container.XNameAccess.class, oUnoObject); if (xName.hasByName(ElementName) == true) return xName.getByName(ElementName); else throw new RuntimeException(); } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static Object getPropertyValue(PropertyValue[] CurPropertyValue, String PropertyName) { int MaxCount = CurPropertyValue.length; for (int i = 0; i < MaxCount; i++) { if (CurPropertyValue[i] != null) { if (CurPropertyValue[i].Name.equals(PropertyName)) { return CurPropertyValue[i].Value; } } } throw new RuntimeException(); } public static Object getUnoPropertyValue(Object oUnoObject, String PropertyName, java.lang.Class xClass) { try { if (oUnoObject != null) { XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUnoObject); Object oObject = xPSet.getPropertyValue(PropertyName); if ( AnyConverter.isVoid(oObject) ) return null; else return com.sun.star.uno.AnyConverter.toObject(new com.sun.star.uno.Type(xClass), oObject); } return null; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static Object getPropertyValuefromAny(Object[] CurPropertyValue, String PropertyName) { if (CurPropertyValue != null) { int MaxCount = CurPropertyValue.length; for (int i = 0; i < MaxCount; i++) { if (CurPropertyValue[i] != null) { PropertyValue aValue = (PropertyValue) CurPropertyValue[i]; if (aValue != null && aValue.Name.equals(PropertyName)) return aValue.Value; } } } // System.out.println("Property not found: " + PropertyName); return null; } public static Object getPropertyValuefromAny(Object[] CurPropertyValue, String PropertyName, java.lang.Class xClass) { try { if (CurPropertyValue != null) { int MaxCount = CurPropertyValue.length; for (int i = 0; i < MaxCount; i++) { if (CurPropertyValue[i] != null) { PropertyValue aValue = (PropertyValue) CurPropertyValue[i]; if (aValue != null && aValue.Name.equals(PropertyName)) return com.sun.star.uno.AnyConverter.toObject(new com.sun.star.uno.Type(xClass), aValue.Value); } } } // System.out.println("Property not found: " + PropertyName); return null; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static Object getUnoPropertyValue(Object oUnoObject, String PropertyName) { try { if (oUnoObject != null) { XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUnoObject); Property[] aProps = xPSet.getPropertySetInfo().getProperties(); Object oObject = xPSet.getPropertyValue(PropertyName); return oObject; } } catch (Exception exception) { exception.printStackTrace(System.out); } return null; } public static Object getUnoArrayPropertyValue(Object oUnoObject, String PropertyName) { try { if (oUnoObject != null) { XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUnoObject); Object oObject = xPSet.getPropertyValue(PropertyName); if (AnyConverter.isArray(oObject)) return getArrayValue(oObject); } } catch (Exception exception) { exception.printStackTrace(System.out); } return null; } public static Object getUnoStructValue(Object oUnoObject, String PropertyName) { try { if (oUnoObject != null) { XPropertySet xPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oUnoObject); if (xPSet.getPropertySetInfo().hasPropertyByName(PropertyName) == true) { Object oObject = xPSet.getPropertyValue(PropertyName); return oObject; } } return null; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } public static void setUnoPropertyValues(Object oUnoObject, String[] PropertyNames, Object[] PropertyValues) { try { com.sun.star.beans.XMultiPropertySet xMultiPSetLst = (com.sun.star.beans.XMultiPropertySet) UnoRuntime.queryInterface(com.sun.star.beans.XMultiPropertySet.class, oUnoObject); if (xMultiPSetLst != null) xMultiPSetLst.setPropertyValues(PropertyNames, PropertyValues); else for (int i = 0; i < PropertyNames.length; i++) { //System.out.println(PropertyNames[i] + "=" + PropertyValues[i]); setUnoPropertyValue(oUnoObject, PropertyNames[i], PropertyValues[i]); } } catch (Exception exception) { exception.printStackTrace(System.out); } } /** * @author bc93774 * checks if the value of an object that represents an array is null. * check beforehand if the Object is really an array with "AnyConverter.IsArray(oObject) * @param oValue the paramter that has to represent an object * @return a null reference if the array is empty */ public static Object getArrayValue(Object oValue) { try { Object oPropList = com.sun.star.uno.AnyConverter.toArray(oValue); int nlen = java.lang.reflect.Array.getLength(oPropList); if (nlen == 0) return null; else return oPropList; } catch (Exception exception) { exception.printStackTrace(System.out); return null; } } private static long DAY_IN_MILLIS = ( 24 * 60 * 60 * 1000 ); public static class DateUtils { private long docNullTime; private XNumberFormatter formatter; private XNumberFormatsSupplier formatSupplier; private Calendar calendar; public DateUtils(XMultiServiceFactory xmsf, Object document) throws Exception { XMultiServiceFactory docMSF = (XMultiServiceFactory)UnoRuntime.queryInterface(XMultiServiceFactory.class,document); Object defaults = docMSF.createInstance("com.sun.star.text.Defaults"); Locale l = (Locale) Helper.getUnoStructValue(defaults, "CharLocale"); java.util.Locale jl = new java.util.Locale( l.Language , l.Country, l.Variant ); calendar = Calendar.getInstance(jl); formatSupplier = (XNumberFormatsSupplier)UnoRuntime.queryInterface(XNumberFormatsSupplier.class,document); Object formatSettings = formatSupplier.getNumberFormatSettings(); com.sun.star.util.Date date = (com.sun.star.util.Date)Helper.getUnoPropertyValue( formatSettings, "NullDate"); calendar.set(date.Year, date.Month - 1 , date.Day); docNullTime = getTimeInMillis(); formatter = NumberFormatter.createNumberFormatter(xmsf, formatSupplier ); } /** * @param format a constant of the enumeration NumberFormatIndex * @return */ public int getFormat( short format ) { return NumberFormatter.getNumberFormatterKey( formatSupplier , format); } public XNumberFormatter getFormatter() { return formatter; } private long getTimeInMillis(){ java.util.Date dDate = calendar.getTime(); return dDate.getTime(); } /** * @param date a VCL date in form of 20041231 * @return a document relative date */ public synchronized double getDocumentDateAsDouble(int date) { calendar.clear(); calendar.set( date / 10000 , ( date % 10000 ) / 100 - 1 , date % 100 ) ; long date1 = getTimeInMillis(); /* * docNullTime and date1 are in millis, but * I need a day... */ double daysDiff = ( date1 - docNullTime ) / DAY_IN_MILLIS + 1; return daysDiff; } public double getDocumentDateAsDouble(DateTime date) { return getDocumentDateAsDouble (date.Year * 10000 + date.Month * 100 + date.Day ); } public synchronized double getDocumentDateAsDouble(long javaTimeInMillis) { calendar.clear(); JavaTools.setTimeInMillis(calendar, javaTimeInMillis ) ; long date1 = getTimeInMillis(); /* * docNullTime and date1 are in millis, but * I need a day... */ double daysDiff = ( date1 - docNullTime ) / DAY_IN_MILLIS + 1; return daysDiff; } public String format(int formatIndex, int date) { return formatter.convertNumberToString( formatIndex, getDocumentDateAsDouble(date)); } public String format(int formatIndex, DateTime date) { return formatter.convertNumberToString( formatIndex, getDocumentDateAsDouble(date)); } public String format(int formatIndex, long javaTimeInMillis) { return formatter.convertNumberToString( formatIndex, getDocumentDateAsDouble(javaTimeInMillis)); } } public static XComponentContext getComponentContext(XMultiServiceFactory _xMSF) { // Get the path to the extension and try to add the path to the class loader final XPropertySet xProps = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, _xMSF); final PropertySetHelper aHelper = new PropertySetHelper(xProps); final Object aDefaultContext = aHelper.getPropertyValueAsObject("DefaultContext"); final XComponentContext xComponentContext = (XComponentContext)UnoRuntime.queryInterface(XComponentContext.class, aDefaultContext); return xComponentContext; } public static XMacroExpander getMacroExpander(XMultiServiceFactory _xMSF) { final XComponentContext xComponentContext = getComponentContext(_xMSF); final Object aSingleton = xComponentContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander"); XMacroExpander xExpander = (XMacroExpander)UnoRuntime.queryInterface(XMacroExpander.class, aSingleton); // String[][] aStrListList = xProvider.getExtensionList(); // final String sLocation = xProvider.getPackageLocation("com.sun.reportdesigner"); return xExpander; } }
package org.santhoshkumar.Graphs; public class AdjacencyList { } class Neighbor { public int vertexNum; public Neighbor next; public Neighbor(int vertexNum, Neighbor neighbor) { this.vertexNum = vertexNum; next = neighbor; } } class Vertex { String name; Neighbor neighbors; Vertex(String name, Neighbor neighbors) { this.name = name; this.neighbors = neighbors; } } class Graph{ Vertex[] vertices; public void addVertex(String name){ } public void addEdge(String vertexA, String vertexB){ } int indexForName(String name) { for (int v=0; v < vertices.length; v++) { if (vertices[v].name.equals(name)) { return v; } } return -1; } }
package io.cucumber.testng; import io.cucumber.core.eventbus.EventBus; import io.cucumber.core.exception.CucumberException; import io.cucumber.core.feature.FeatureParser; import io.cucumber.core.filter.Filters; import io.cucumber.core.gherkin.Feature; import io.cucumber.core.gherkin.Pickle; import io.cucumber.core.logging.Logger; import io.cucumber.core.logging.LoggerFactory; import io.cucumber.core.options.Constants; import io.cucumber.core.options.CucumberOptionsAnnotationParser; import io.cucumber.core.options.CucumberProperties; import io.cucumber.core.options.CucumberPropertiesParser; import io.cucumber.core.options.RuntimeOptions; import io.cucumber.core.plugin.PluginFactory; import io.cucumber.core.plugin.Plugins; import io.cucumber.core.resource.ClassLoaders; import io.cucumber.core.runner.Runner; import io.cucumber.core.runtime.BackendServiceLoader; import io.cucumber.core.runtime.FeaturePathFeatureSupplier; import io.cucumber.core.runtime.ObjectFactoryServiceLoader; import io.cucumber.core.runtime.ObjectFactorySupplier; import io.cucumber.core.runtime.ScanningTypeRegistryConfigurerSupplier; import io.cucumber.core.runtime.ThreadLocalObjectFactorySupplier; import io.cucumber.core.runtime.ThreadLocalRunnerSupplier; import io.cucumber.core.runtime.TimeServiceEventBus; import io.cucumber.core.runtime.TypeRegistryConfigurerSupplier; import io.cucumber.plugin.event.TestRunFinished; import io.cucumber.plugin.event.TestRunStarted; import io.cucumber.plugin.event.TestSourceRead; import org.apiguardian.api.API; import java.time.Clock; import java.util.List; import java.util.UUID; import java.util.function.Predicate; import java.util.function.Supplier; import static java.util.stream.Collectors.toList; /** * Glue code for running Cucumber via TestNG. * <p> * Options can be provided in by (order of precedence): * <ol> * <li>Properties from {@link System#getProperties()}</li> * <li>Properties from in {@link System#getenv()}</li> * <li>Annotating the runner class with {@link CucumberOptions}</li> * <li>Properties from {@value Constants#CUCUMBER_PROPERTIES_FILE_NAME}</li> * </ol> * For available properties see {@link Constants}. */ @API(status = API.Status.STABLE) public final class TestNGCucumberRunner { private static final Logger log = LoggerFactory.getLogger(TestNGCucumberRunner.class); private final EventBus bus; private final Predicate<Pickle> filters; private final ThreadLocalRunnerSupplier runnerSupplier; private final RuntimeOptions runtimeOptions; private final List<Feature> features; /** * Bootstrap the cucumber runtime * * @param clazz Which has the {@link CucumberOptions} * and {@link org.testng.annotations.Test} annotations */ public TestNGCucumberRunner(Class<?> clazz) { // Parse the options early to provide fast feedback about invalid options RuntimeOptions propertiesFileOptions = new CucumberPropertiesParser() .parse(CucumberProperties.fromPropertiesFile()) .build(); RuntimeOptions annotationOptions = new CucumberOptionsAnnotationParser() .withOptionsProvider(new TestNGCucumberOptionsProvider()) .parse(clazz) .build(propertiesFileOptions); RuntimeOptions environmentOptions = new CucumberPropertiesParser() .parse(CucumberProperties.fromEnvironment()) .build(annotationOptions); this.runtimeOptions = new CucumberPropertiesParser() .parse(CucumberProperties.fromSystemProperties()) .addDefaultSummaryPrinterIfAbsent() .build(environmentOptions); this.bus = new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID); if (!runtimeOptions.isStrict()) { log.warn(() -> "By default Cucumber is running in --non-strict mode.\n" + "This default will change to --strict and --non-strict will be removed.\n" + "You can use --strict or @CucumberOptions(strict = true) to suppress this warning" ); } Supplier<ClassLoader> classLoader = ClassLoaders::getDefaultClassLoader; FeatureParser parser = new FeatureParser(bus::generateId); FeaturePathFeatureSupplier featureSupplier = new FeaturePathFeatureSupplier(classLoader, runtimeOptions, parser); Plugins plugins = new Plugins(new PluginFactory(), runtimeOptions); ObjectFactoryServiceLoader objectFactoryServiceLoader = new ObjectFactoryServiceLoader(runtimeOptions); ObjectFactorySupplier objectFactorySupplier = new ThreadLocalObjectFactorySupplier(objectFactoryServiceLoader); BackendServiceLoader backendSupplier = new BackendServiceLoader(clazz::getClassLoader, objectFactorySupplier); this.filters = new Filters(runtimeOptions); TypeRegistryConfigurerSupplier typeRegistryConfigurerSupplier = new ScanningTypeRegistryConfigurerSupplier(classLoader, runtimeOptions); this.runnerSupplier = new ThreadLocalRunnerSupplier(runtimeOptions, bus, backendSupplier, objectFactorySupplier, typeRegistryConfigurerSupplier); // Start test execution now. plugins.setSerialEventBusOnEventListenerPlugins(bus); features = featureSupplier.get(); bus.send(new TestRunStarted(bus.getInstant())); features.forEach(feature -> bus.send(new TestSourceRead(bus.getInstant(), feature.getUri(), feature.getSource()))); } public void runScenario(io.cucumber.testng.Pickle pickle) throws Throwable { //Possibly invoked in a multi-threaded context Runner runner = runnerSupplier.get(); try (TestCaseResultObserver observer = TestCaseResultObserver.observe(runner.getBus(), runtimeOptions.isStrict())) { Pickle cucumberPickle = pickle.getPickle(); runner.runPickle(cucumberPickle); observer.assertTestCasePassed(); } } /** * Finishes test execution by Cucumber. */ public void finish() { bus.send(new TestRunFinished(bus.getInstant())); } /** * @return returns the cucumber scenarios as a two dimensional array of * {@link PickleWrapper} scenarios combined with their * {@link FeatureWrapper} feature. */ public Object[][] provideScenarios() { //Possibly invoked in a multi-threaded context try { return features.stream() .flatMap(feature -> feature.getPickles().stream() .filter(filters) .map(cucumberPickle -> new Object[]{ new PickleWrapperImpl(new io.cucumber.testng.Pickle(cucumberPickle)), new FeatureWrapperImpl(feature)})) .collect(toList()) .toArray(new Object[0][0]); } catch (CucumberException e) { return new Object[][]{new Object[]{new CucumberExceptionWrapper(e), null}}; } } }
import java.util.function.IntConsumer; import java.util.*; public class GameEngine { public GameEngine (Vector<String> instructions, boolean debug) { _computer = new Intcode(instructions, INITIAL_INPUT, debug); _debug = debug; _theScreen = new Screen(_debug); _paddlePosition = null; _ballPosition = null; _stick = new Joystick(); } public final boolean playGame () { int[] output = null; /* * Initialise the screen. Run the game instructions * once. */ // Replace entry 0 with 2 (unlimited lives) _computer.changeInstruction(0, "2"); while (!_computer.waitingForInput()) { output = getOutput(INITIAL_INPUT); if (_debug) System.out.println("Tile information: <"+output[0]+", "+output[1]+"> and "+TileId.idToString(output[2])); System.out.println("**initial "+output[0]+" "+output[1]+" "+output[2]); Tile theTile = new Tile(new Coordinate(output[0], output[1]), output[2]); _theScreen.updateTile(theTile); if (theTile.getId() == TileId.BALL) _ballPosition = theTile.getPosition(); else { if (theTile.getId() == TileId.PADDLE) _paddlePosition = theTile.getPosition(); } } /* * Where is the joystick? */ if (_ballPosition.getX() > _paddlePosition.getX()) _stick.setPosition(Joystick.TILTED_RIGHT); else { if (_ballPosition.getX() < _paddlePosition.getX()) _stick.setPosition(Joystick.TILTED_LEFT); } System.out.println("**initial joystick "+_stick); /* * Now let's play the game! */ System.out.println("\n\nPLAYING"); //_computer = new Intcode(instructions, INITIAL_INPUT, debug); while (!_computer.hasHalted()) { output = getOutput(Integer.toString(_stick.getPosition())); if (_debug) System.out.println("Tile information: <"+output[0]+", "+output[1]+"> and "+TileId.idToString(output[2])); System.out.println("**gaming values "+output[0]+" "+output[1]+" "+output[2]); if ((output[0] == -1) && (output[1] == 0)) { // update score _theScreen.getSegmentDisplay().setScore(output[2]); System.out.println("**score now "+_theScreen.getSegmentDisplay()); } else { Tile theTile = new Tile(new Coordinate(output[0], output[1]), output[2]); _theScreen.updateTile(theTile); if(theTile.getId() == TileId.BALL) { _ballPosition = theTile.getPosition(); if (_ballPosition.getX() > _paddlePosition.getX()) _stick.setPosition(Joystick.TILTED_RIGHT); else { if (_ballPosition.getX() < _paddlePosition.getX()) _stick.setPosition(Joystick.TILTED_LEFT); else _stick.setPosition(Joystick.NEUTRAL_POSITION); } System.out.println("**gaming joystick "+_stick); } else { if (theTile.getId() == TileId.PADDLE) _paddlePosition = theTile.getPosition(); } } } System.out.println("**score "+_theScreen.getSegmentDisplay()); return true; } public final int getNumberOfBlocks () { return _theScreen.numberOfBlocks(); } private final int[] getOutput (String input) { int[] values = new int[3]; System.out.println("**got "+_computer.hasPaused()+" "+_computer.hasOutput()); while (!_computer.hasPaused() && !_computer.hasOutput()) { _computer.singleStepExecution(input); } if (!_computer.hasPaused()) { values[0] = Integer.parseInt(_computer.getOutput()); while (!_computer.hasPaused() && !_computer.hasOutput()) { _computer.singleStepExecution(input); } if (!_computer.hasPaused()) { values[1] = Integer.parseInt(_computer.getOutput()); while (!_computer.hasPaused() && !_computer.hasOutput()) { _computer.singleStepExecution(input); } values[2] = Integer.parseInt(_computer.getOutput()); } else { System.out.println("Error - computer halted after outputing x value!"); } } return values; } private Intcode _computer; private boolean _debug; private Screen _theScreen; private Coordinate _paddlePosition; private Coordinate _ballPosition; private Joystick _stick; private static final String INITIAL_INPUT = null; // nothing specified in the overview }
// PictReader.java package loci.formats; import java.awt.image.BufferedImage; import java.awt.Dimension; import java.io.*; import java.util.*; public class PictReader extends FormatReader { // -- Constants -- // opcodes that we need private static final int PICT_CLIP_RGN = 0x1; private static final int PICT_BITSRECT = 0x90; private static final int PICT_BITSRGN = 0x91; private static final int PICT_PACKBITSRECT = 0x98; private static final int PICT_PACKBITSRGN = 0x99; private static final int PICT_9A = 0x9a; private static final int PICT_HEADER = 0xc00; private static final int PICT_END = 0xff; private static final int PICT_LONGCOMMENT = 0xa1; // possible image states private static final int INITIAL = 1; private static final int STATE2 = 2; // other stuff? private static final int INFOAVAIL = 0x0002; private static final int IMAGEAVAIL = 0x0004; /** Table used in expanding pixels that use less than 8 bits. */ private static final byte[] EXPANSION_TABLE = new byte[256 * 8]; static { int index = 0; for (int i = 0; i < 256; i++) { EXPANSION_TABLE[index++] = (i & 128) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 64) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 32) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 16) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 8) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 4) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 2) == 0 ? (byte) 0 : (byte) 1; EXPANSION_TABLE[index++] = (i & 1) == 0 ? (byte) 0 : (byte) 1; } } // -- Fields -- /** Current file. */ protected RandomAccessFile in; /** Flag indicating whether current file is little endian. */ protected boolean little; /** Pixel bytes. */ protected byte[] bytes; /** Width of the image. */ protected int width; /** Height of the image. */ protected int height; /** Number of bytes in a row of pixel data (variable). */ protected int rowBytes; /** Decoder state. */ protected int state; /** Image state. */ protected int pictState; /** Pointer into the array of bytes representing the file. */ protected int pt; /** Vector of byte arrays representing individual rows. */ protected Vector strips; /** Whether or not the file is PICT v1. */ protected boolean versionOne; /** Color lookup table for palette color images. */ protected short[][] lookup; /** Helper reader in case this one fails. */ protected LegacyQTReader qtReader = new LegacyQTReader(); // -- Constructor -- /** Constructs a new PICT reader. */ public PictReader() { super("PICT", new String[] {"pict", "pct"}); } // -- FormatReader API methods -- /** Checks if the given block is a valid header for a PICT file. */ public boolean isThisType(byte[] block) { try { if (in.length() < 528) return false; return true; } catch (IOException e) { return false; } } /** Determines the number of images in the given PICT file. */ public int getImageCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); return 1; } /** Obtains the specified image from the given PICT file. */ public BufferedImage open(String id, int no) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (no != 0) throw new FormatException("Invalid image number: " + no); return openBytes(bytes); } /** Closes any open files. */ public void close() throws FormatException, IOException { if (in != null) in.close(); in = null; currentId = null; } /** Initializes the given PICT file. */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessFile(id, "r"); little = false; // skip the header and read in the remaining bytes int len = (int) (in.length() - 512); bytes = new byte[len]; in.skipBytes(512); in.read(bytes); } // -- PictReader API methods -- /** Get the dimensions of a PICT file from the first 4 bytes after header. */ public Dimension getDimensions(byte[] stuff) throws FormatException { if (stuff.length < 10) { throw new FormatException("Need 10 bytes to calculate dimension"); } int w = DataTools.bytesToInt(stuff, 6, 2, little); int h = DataTools.bytesToInt(stuff, 8, 2, little); if (DEBUG) { System.out.println("PictReader.getDimensions: " + w + " x " + h); } return new Dimension(h, w); } /** Open a PICT image from an array of bytes (used by OpenlabReader). */ public BufferedImage openBytes(byte[] pix) throws FormatException { // handles case when we call this method directly, instead of // through initFile(String) if (DEBUG) System.out.println("PictReader.openBytes"); strips = new Vector(); state = 0; pictState = INITIAL; bytes = pix; pt = 0; try { while (driveDecoder()); } catch (Exception e) { e.printStackTrace(); return ImageTools.makeBuffered(qtReader.pictToImage(pix)); } // combine everything in the strips Vector if ((height*4 < strips.size()) && (((strips.size() / 3) % height) != 0)) { height = strips.size(); } if (strips.size() == 0) { return ImageTools.makeBuffered(qtReader.pictToImage(pix)); } if (lookup != null) { // 8 bit data short[][] data = new short[3][height * width]; byte[] row; for (int i=0; i<height; i++) { row = (byte[]) strips.get(i); for (int j=0; j<row.length; j++) { if (j < width) { int ndx = row[j]; if (ndx < 0) ndx += lookup[0].length; ndx = ndx % lookup[0].length; int outIndex = i*width + j; if (outIndex >= data[0].length) outIndex = data[0].length - 1; data[0][outIndex] = lookup[0][ndx]; data[1][outIndex] = lookup[1][ndx]; data[2][outIndex] = lookup[2][ndx]; } else j = row.length; } } if (DEBUG) { System.out.println("PictReader.openBytes: 8-bit data, " + width + " x " + height + ", length=" + data.length + "x" + data[0].length); } return ImageTools.makeImage(data, width, height); } else if (height*3 == strips.size()) { // 24 bit data byte[][] data = new byte[3][width * height]; int outIndex = 0; for (int i=0; i<3*height; i+=3) { byte[] c0 = (byte[]) strips.get(i); byte[] c1 = (byte[]) strips.get(i+1); byte[] c2 = (byte[]) strips.get(i+2); System.arraycopy(c0, 0, data[0], outIndex, c0.length); System.arraycopy(c1, 0, data[1], outIndex, c1.length); System.arraycopy(c2, 0, data[2], outIndex, c2.length); outIndex += width; } if (DEBUG) { System.out.println("PictReader.openBytes: 24-bit data, " + width + " x " + height + ", length=" + data.length + "x" + data[0].length); } return ImageTools.makeImage(data, width, height); } else if (height*4 == strips.size()) { // 32 bit data byte[][] data = new byte[3][width * height]; int outIndex = 0; for (int i=0; i<4*height; i+=4) { //byte[] a = (byte[]) strips.get(i); byte[] r = (byte[]) strips.get(i+1); byte[] g = (byte[]) strips.get(i+2); byte[] b = (byte[]) strips.get(i+3); System.arraycopy(r, 0, data[0], outIndex, r.length); System.arraycopy(g, 0, data[1], outIndex, g.length); System.arraycopy(b, 0, data[2], outIndex, b.length); //System.arraycopy(a, 0, data[3], outIndex, a.length); outIndex += width; } if (DEBUG) { System.out.println("PictReader.openBytes: 32-bit data, " + width + " x " + height + ", length=" + data.length + "x" + data[0].length); } return ImageTools.makeImage(data, width, height); } else { // 16 bit data short[] data = new short[3 * height * width]; int outIndex = 0; for (int i=0; i<height; i++) { int[] row = (int[]) strips.get(i); for (int j=0; j<row.length; j++, outIndex+=3) { if (j < width) { if (outIndex >= data.length - 2) break; int s0 = (row[j] & 0x1f); int s1 = (row[j] & 0x3e0) >> 5; // 0x1f << 5; int s2 = (row[j] & 0x7c00) >> 10; // 0x1f << 10; data[outIndex] = (short) s2; data[outIndex+1] = (short) s1; data[outIndex+2] = (short) s0; } else j = row.length; } } if (DEBUG) { System.out.println("PictReader.openBytes: 16-bit data, " + width + " x " + height + ", length=" + data.length); } return ImageTools.makeImage(data, width, height, 3, true); } } // -- Helper methods -- /** Loop through the remainder of the file and find relevant opcodes. */ private boolean driveDecoder() throws FormatException { if (DEBUG) System.out.println("PictReader.driveDecoder"); int opcode, version; switch (pictState) { case INITIAL: int ret; int fileSize = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; // skip over frame pt += 8; int verOpcode = DataTools.bytesToInt(bytes, pt, 1, little); pt++; int verNumber = DataTools.bytesToInt(bytes, pt, 1, little); pt++; if (verOpcode == 0x11 && verNumber == 0x01) versionOne = true; else if (verOpcode == 0x00 && verNumber == 0x11) { versionOne = false; int verOpcode2 = 0x0011; int verNumber2 = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; if (verNumber2 != 0x02ff) { throw new FormatException("Invalid PICT file : " + verNumber2); } // skip over v2 header -- don't need it here pt += 26; } else throw new FormatException("Invalid PICT file"); pictState = STATE2; state |= INFOAVAIL; return true; case STATE2: if (versionOne) { opcode = DataTools.bytesToInt(bytes, pt, 1, little); pt++; } else { // if at odd boundary skip a byte for opcode in PICT v2 if ((pt & 0x1L) != 0) { pt++; } opcode = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; } return drivePictDecoder(opcode); } return true; } /** Handles the opcodes in the PICT file. */ private boolean drivePictDecoder(int opcode) throws FormatException { if (DEBUG) System.out.println("PictReader.drivePictDecoder"); short size, kind; switch (opcode) { case PICT_BITSRGN: // rowBytes must be < 8 handlePackBits(opcode); break; case PICT_PACKBITSRGN: // rowBytes must be < 8 handlePackBits(opcode); break; case PICT_BITSRECT: // rowBytes must be < 8 handlePackBits(opcode); break; case PICT_PACKBITSRECT: handlePackBits(opcode); break; case PICT_9A: handlePackBits(opcode); break; case PICT_CLIP_RGN: int x = DataTools.bytesToInt(bytes, pt, 2, little); pt += x; break; case PICT_LONGCOMMENT: pt += 2; x = DataTools.bytesToInt(bytes, pt, 2, little); pt += x + 2; break; case PICT_END: // end of PICT state |= IMAGEAVAIL; return false; } return (pt < bytes.length); } /** Handles bitmap and pixmap opcodes of PICT format. */ private void handlePackBits(int opcode) throws FormatException { if (DEBUG) System.out.println("PictReader.handlePackBits(" + opcode + ")"); if (opcode == PICT_9A) { // special case handlePixmap(opcode); } else { rowBytes = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; if (versionOne || (rowBytes & 0x8000) == 0) handleBitmap(opcode); else handlePixmap(opcode); } } /** Extract the image data in a PICT bitmap structure. */ private void handleBitmap(int opcode) throws FormatException { if (DEBUG) System.out.println("PictReader.handleBitmap(" + opcode + ")"); int row; byte[] buf; // raw byte buffer for data from file byte[] uBuf; // uncompressed data -- possibly still pixel packed byte[] outBuf; // expanded pixel data rowBytes &= 0x3fff; // mask off flags // read the bitmap data -- 3 rectangles + mode int tlY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int tlX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; // skip next two rectangles pt += 16; int mode = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; width = brX - tlX; height = brY - tlY; // allocate enough space to handle compressed data length for rowBytes try { buf = new byte[rowBytes + 1 + rowBytes/128]; uBuf = new byte[rowBytes]; outBuf = new byte[width]; } catch (NegativeArraySizeException n) { throw new FormatException("Sorry, vector data not supported."); } for (row=0; row < height; ++row) { if (rowBytes < 8) { // data is not compressed System.arraycopy(bytes, pt, buf, 0, rowBytes); for (int j=buf.length; --j >= 0; ) { buf[j] = (byte) ~buf[j]; } expandPixels(1, buf, outBuf, outBuf.length); } else { int rawLen; if (rowBytes > 250) { rawLen = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; } else { rawLen = DataTools.bytesToInt(bytes, pt, 1, little); pt++; } try { System.arraycopy(bytes, pt, buf, 0, rawLen); pt += rawLen; } catch (ArrayIndexOutOfBoundsException e) { throw new FormatException("Sorry, vector data not supported."); } uBuf = Compression.packBitsUncompress(buf); // invert the pixels -- PICT images map zero to white for (int j=0; j<uBuf.length; j++) uBuf[j] = (byte) ~uBuf[j]; expandPixels(1, uBuf, outBuf, outBuf.length); } strips.add(outBuf); } } /** Extracts the image data in a PICT pixmap structure. */ private void handlePixmap(int opcode) throws FormatException { if (DEBUG) System.out.println("PictReader.handlePixmap(" + opcode + ")"); int pixelSize; int compCount; // handle 9A variation if (opcode == PICT_9A) { // this is the only opcode that holds 16, 24, and 32 bit data // read the pixmap (9A) pt += 4; // skip fake length and fake EOF int version = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; // read the bounding box int tlY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int tlX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; pt += 2; // undocumented extra short in the data structure int packType = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int packSize = DataTools.bytesToInt(bytes, pt, 4, little); pt += 4; int hRes = DataTools.bytesToInt(bytes, pt, 4, little); pt += 4; int vRes = DataTools.bytesToInt(bytes, pt, 4, little); pt += 4; int pixelType = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; pixelSize = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; compCount = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int compSize = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int planeBytes = DataTools.bytesToInt(bytes, pt, 4, little); pt += 4; int pmTable = DataTools.bytesToInt(bytes, pt, 4, little); pt += 4; pt += 4; // reserved width = brX - tlX; height = brY - tlY; // rowBytes doesn't exist, so set it to its logical value switch (pixelSize) { case 32: rowBytes = width * compCount; break; case 16: rowBytes = width * 2; break; default: throw new FormatException("Sorry, vector data not supported."); } } else { rowBytes &= 0x3fff; // mask off flags int tlY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int tlX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brY = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int brX = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; // unnecessary data pt += 18; pixelSize = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; compCount = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; // unnecessary data pt += 14; // read the lookup table pt += 2; int id = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int flags = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; int count = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; count++; lookup = new short[3][count]; for (int i=0; i<count; i++) { int index = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; if ((flags & 0x8000) != 0) index = i; lookup[0][index] = DataTools.bytesToShort(bytes, pt, 2, little); pt += 2; lookup[1][index] = DataTools.bytesToShort(bytes, pt, 2, little); pt += 2; lookup[2][index] = DataTools.bytesToShort(bytes, pt, 2, little); pt += 2; } width = brX - tlX; height = brY - tlY; } // skip over two rectangles pt += 16; int mode = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; if (opcode == PICT_BITSRGN || opcode == PICT_PACKBITSRGN) { int x = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; } handlePixmap(rowBytes, pixelSize, compCount); } /** Handles the unpacking of the image data. */ private void handlePixmap(int rowBytes, int pixelSize, int compCount) throws FormatException { if (DEBUG) { System.out.println("PictReader.handlePixmap(" + rowBytes + ", " + pixelSize + ", " + compCount + ")"); } int rawLen; byte[] buf; // row raw bytes byte[] uBuf = null; // row uncompressed data int[] uBufI = null; // row uncompressed data - 16+ bit pixels int bufSize; int outBufSize; byte[] outBuf = null; // used to expand pixel data boolean compressed = (rowBytes >= 8) || (pixelSize == 32); bufSize = rowBytes; outBufSize = width; // allocate buffers switch (pixelSize) { case 32: if (!compressed) uBufI = new int[width]; else uBuf = new byte[bufSize]; break; case 16: uBufI = new int[width]; break; case 8: uBuf = new byte[bufSize]; break; default: outBuf = new byte[outBufSize]; uBuf = new byte[bufSize]; break; } if (!compressed) { if (DEBUG) { System.out.println("Pixel data is uncompressed (pixelSize=" + pixelSize + ")."); } buf = new byte[bufSize]; for (int row=0; row<height; row++) { System.arraycopy(bytes, pt, buf, 0, rowBytes); switch (pixelSize) { case 16: for (int i=0; i<width; i++) { uBufI[i] = ((buf[i*2] & 0xff) << 8) + (buf[i*2+1] & 0xff); } strips.add(uBufI); break; case 8: strips.add(buf); break; default: // pixel size < 8 expandPixels(pixelSize, buf, outBuf, outBuf.length); strips.add(outBuf); } } } else { if (DEBUG) { System.out.println("Pixel data is compressed (pixelSize=" + pixelSize + "; compCount=" + compCount + ")."); } buf = new byte[bufSize + 1 + bufSize / 128]; for (int row=0; row<height; row++) { if (rowBytes > 250) { rawLen = DataTools.bytesToInt(bytes, pt, 2, little); pt += 2; } else { rawLen = DataTools.bytesToInt(bytes, pt, 1, little); pt++; } if (rawLen > buf.length) rawLen = buf.length; if ((bytes.length - pt) <= rawLen) { rawLen = bytes.length - pt - 1; } if (rawLen < 0) { rawLen = 0; pt = bytes.length - 1; } System.arraycopy(bytes, pt, buf, 0, rawLen); pt += rawLen; if (pixelSize == 16) { uBufI = new int[width]; unpackBits(buf, uBufI); strips.add(uBufI); } else uBuf = Compression.packBitsUncompress(buf); if (pixelSize < 8) { expandPixels(pixelSize, uBuf, outBuf, outBuf.length); strips.add(outBuf); } else if (pixelSize == 8) strips.add(uBuf); else if (pixelSize == 24 || pixelSize == 32) { byte[] newBuf = null; int offset = 0; if (compCount == 4) { // alpha channel //newBuf = new byte[width]; //System.arraycopy(uBuf, offset, newBuf, 0, width); strips.add(newBuf); offset += width; } // red channel newBuf = new byte[width]; System.arraycopy(uBuf, offset, newBuf, 0, width); strips.add(newBuf); offset += width; // green channel newBuf = new byte[width]; System.arraycopy(uBuf, offset, newBuf, 0, width); strips.add(newBuf); offset += width; // blue channel newBuf = new byte[width]; System.arraycopy(uBuf, offset, newBuf, 0, width); strips.add(newBuf); } } } } /** Expand an array of bytes. */ private void expandPixels(int bitSize, byte[] in, byte[] out, int outLen) throws FormatException { if (DEBUG) { System.out.println("PictReader.expandPixels(" + bitSize + ", " + in.length + ", " + out.length + ", " + outLen + ")"); } if (bitSize == 1) { int remainder = outLen % 8; int max = outLen / 8; for (int i=0; i<max; i++) { if (i < in.length) { int look = (in[i] & 0xff) * 8; System.arraycopy(EXPANSION_TABLE, look, out, i*8, 8); } else i = max; } if (remainder != 0) { if (max < in.length) { System.arraycopy(EXPANSION_TABLE, (in[max] & 0xff) * 8, out, max*8, remainder); } } return; } int i; int o; int t; byte v; int count = 0; // number of pixels in a byte int maskshift = 1; // num bits to shift mask int pixelshift = 0; // num bits to shift pixel int tpixelshift = 0; int pixelshiftdelta = 0; int mask = 0; int tmask; // temp mask if (bitSize != 1 && bitSize != 2 && bitSize != 4) { throw new FormatException("Can only expand 1, 2, and 4 bit values"); } switch (bitSize) { case 1: mask = 0x80; maskshift = 1; count = 8; pixelshift = 7; pixelshiftdelta = 1; break; case 2: mask = 0xC0; maskshift = 2; count = 4; pixelshift = 6; pixelshiftdelta = 2; break; case 4: mask = 0xF0; maskshift = 4; count = 2; pixelshift = 4; pixelshiftdelta = 4; break; } i = 0; for (o = 0; o < out.length;) { tmask = mask; tpixelshift = pixelshift; v = in[i]; for (t = 0; t < count && o < out.length; ++t, ++o) { out[o] = (byte) (((v & tmask) >>> tpixelshift) & 0xff); tmask = (byte) ((tmask & 0xff) >>> maskshift); tpixelshift -= pixelshiftdelta; } ++i; } } /** PackBits variant that outputs an int array. */ private void unpackBits(byte[] in, int[] out) { if (DEBUG) { System.out.println("PictReader.unpackBits(" + in + ", " + out + ")"); } int i = 0; int o = 0; int b; int rep; int end; for (o=0; o<out.length;) { if ((i+1) < in.length) { b = in[i++]; if (b >= 0) { b++; end = o + b; for(; o < end; o++, i+=2) { if ((o < out.length) && ((i+1) < in.length)) { out[o] = (((in[i] & 0xff) << 8) + (in[i+1] & 0xff)) & 0xffff; } else o = end; } } else if (b != -128) { rep = (((in[i] & 0xff) << 8) + (in[i+1] & 0xff)) & 0xffff; i += 2; end = o - b + 1; for (; o < end; o++) { if (o < out.length) { out[o] = rep; } else o = end; } } } else o = out.length; } } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new PictReader().testRead(args); } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.widget.VenueView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; import java.io.IOException; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class ShoutActivity extends Activity { public static final String TAG = "ShoutActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_VENUE_NAME = "com.joelapenna.foursquared.ShoutActivity.VENUE_NAME"; public static final String EXTRA_VENUE_ADDRESS = "com.joelapenna.foursquared.ShoutActivity.VENUE_ADDRESS"; public static final String EXTRA_VENUE_CROSSSTREET = "com.joelapenna.foursquared.ShoutActivity.VENUE_CROSSSTREET"; public static final String EXTRA_VENUE_CITY = "com.joelapenna.foursquared.ShoutActivity.VENUE_CITY"; public static final String EXTRA_VENUE_ZIP = "com.joelapenna.foursquared.ShoutActivity.VENUE_ZIP"; public static final String EXTRA_VENUE_STATE = "com.joelapenna.foursquared.ShoutActivity.VENUE_STATE"; public static final String EXTRA_IMMEDIATE_CHECKIN = "com.joelapenna.foursquared.ShoutActivity.IMMEDIATE_CHECKIN"; private static final int DIALOG_CHECKIN_PROGRESS = 1; private StateHolder mStateHolder = new StateHolder(); private boolean isShouting = true; private Button mCheckinButton; private CheckBox mTwitterCheckBox; private CheckBox mFriendsCheckBox; private EditText mShoutEditText; private VenueView mVenueView; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.shout_activity); registerReceiver(mLoggedInReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(ShoutActivity.this); mCheckinButton = (Button)findViewById(R.id.checkinButton); mFriendsCheckBox = (CheckBox)findViewById(R.id.tellFriendsCheckBox); mTwitterCheckBox = (CheckBox)findViewById(R.id.tellTwitterCheckBox); mShoutEditText = (EditText)findViewById(R.id.shoutEditText); mVenueView = (VenueView)findViewById(R.id.venue); mCheckinButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStateHolder.checkinTask = new CheckinTask().execute(); } }); mTwitterCheckBox.setChecked(settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false)); mFriendsCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mTwitterCheckBox.setEnabled(isChecked); if (!isChecked) { mTwitterCheckBox.setChecked(false); } } }); mFriendsCheckBox .setChecked(settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true)); isShouting = !getIntent().hasExtra(Foursquared.EXTRA_VENUE_ID); if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Using last non configuration instance"); mStateHolder = (StateHolder)getLastNonConfigurationInstance(); } else if (!isShouting) { // Translate the extras received in this intent int a venue, then attach it to the // venue view. mStateHolder.venue = new Venue(); intentExtrasIntoVenue(getIntent(), mStateHolder.venue); } if (isShouting) { mVenueView.setVisibility(ViewGroup.GONE); mFriendsCheckBox.setChecked(true); mCheckinButton.setText("Shout!"); } else { mVenueView.setVenue(mStateHolder.venue); if (getIntent().getBooleanExtra(EXTRA_IMMEDIATE_CHECKIN, false)) { if (mStateHolder.checkinTask == null) { if (DEBUG) Log.d(TAG, "Immediate checkin is set."); mStateHolder.checkinTask = new CheckinTask().execute(); } } } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CHECKIN_PROGRESS: String title = (isShouting) ? "Shouting!" : "Checking in!"; String messageAction = (isShouting) ? "shout!" : "check-in!"; ProgressDialog dialog = new ProgressDialog(this); dialog.setCancelable(true); dialog.setIndeterminate(true); dialog.setTitle(title); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setMessage("Please wait while we " + messageAction); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mStateHolder.checkinTask.cancel(true); } }); return dialog; } return null; } /** * Because we cannot parcel venues properly yet (issue #5) we have to mutate a series of intent * extras into a venue so that we can code to this future possibility. */ public static void intentExtrasIntoVenue(Intent intent, Venue venue) { Bundle extras = intent.getExtras(); venue.setId(extras.getString(Foursquared.EXTRA_VENUE_ID)); venue.setName(extras.getString(EXTRA_VENUE_NAME)); venue.setAddress(extras.getString(EXTRA_VENUE_ADDRESS)); venue.setCrossstreet(extras.getString(EXTRA_VENUE_CROSSSTREET)); venue.setCity(extras.getString(EXTRA_VENUE_CITY)); venue.setZip(extras.getString(EXTRA_VENUE_ZIP)); venue.setState(extras.getString(EXTRA_VENUE_STATE)); } public static void venueIntoIntentExtras(Venue venue, Intent intent) { intent.putExtra(Foursquared.EXTRA_VENUE_ID, venue.getId()); intent.putExtra(ShoutActivity.EXTRA_VENUE_NAME, venue.getName()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ADDRESS, venue.getAddress()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CITY, venue.getCity()); intent.putExtra(ShoutActivity.EXTRA_VENUE_CROSSSTREET, venue.getCrossstreet()); intent.putExtra(ShoutActivity.EXTRA_VENUE_STATE, venue.getState()); intent.putExtra(ShoutActivity.EXTRA_VENUE_ZIP, venue.getZip()); } private AlertDialog createCheckinResultDialog(CheckinResult checkinResult) { LayoutInflater inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.checkin_result_dialog, (ViewGroup)findViewById(R.id.layout_root)); String userId = PreferenceManager.getDefaultSharedPreferences(this).getString( Preferences.PREFERENCE_ID, ""); WebView webView = (WebView)layout.findViewById(R.id.webView); webView.setBackgroundColor(0); // make it transparent... how do we do this in xml? String breakdownUrl = "http://playfoursquare.com/incoming/breakdown"; String breakdownQuery = "?client=iphone&uid=" + userId + "&cid=" + checkinResult.getId(); webView.loadUrl(breakdownUrl + breakdownQuery); TextView messageView = (TextView)layout.findViewById(R.id.messageTextView); messageView.setText(checkinResult.getMessage()); return new AlertDialog.Builder(this) .setView(layout) .setIcon(android.R.drawable.ic_dialog_info) // icon .setTitle("Checked in @ " + checkinResult.getVenue().getName()) // title .setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .create(); } class CheckinTask extends AsyncTask<Void, Void, CheckinResult> { @Override public void onPreExecute() { mCheckinButton.setEnabled(false); showDialog(DIALOG_CHECKIN_PROGRESS); } @Override public CheckinResult doInBackground(Void... params) { String venueId = (mStateHolder.venue == null) ? null : mStateHolder.venue.getId(); boolean isPrivate = !mFriendsCheckBox.isChecked(); boolean twitter = mTwitterCheckBox.isChecked(); String shout = TextUtils.isEmpty(mShoutEditText.getText()) ? null : mShoutEditText .getText().toString(); try { return Foursquared.getFoursquare() .checkin(null, venueId, shout, isPrivate, twitter); } catch (FoursquareError e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareError", e); } catch (FoursquareException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "FoursquareException", e); } catch (IOException e) { // TODO Auto-generated catch block if (DEBUG) Log.d(TAG, "IOException", e); } return null; } @Override public void onPostExecute(CheckinResult checkinResult) { if (DEBUG) Log.d(TAG, "CheckinTask: onPostExecute()"); dismissDialog(DIALOG_CHECKIN_PROGRESS); if (checkinResult == null) { mCheckinButton.setEnabled(true); Toast.makeText(ShoutActivity.this, "Unable to checkin!", Toast.LENGTH_LONG).show(); return; } else { setResult(Activity.RESULT_OK); createCheckinResultDialog(checkinResult).show(); } } @Override public void onCancelled() { mCheckinButton.setEnabled(true); dismissDialog(DIALOG_CHECKIN_PROGRESS); setResult(Activity.RESULT_CANCELED); finish(); } } private static class StateHolder { // These are all enumerated because we currently cannot handle parceling venues! How sad! Venue venue = null; AsyncTask<Void, Void, CheckinResult> checkinTask = null; } }
package org.basex.gui.view.map; import java.util.ArrayList; import org.basex.data.Data; import org.basex.gui.GUIProp; import org.basex.gui.view.ViewData; import org.basex.util.IntList; import org.basex.util.Token; abstract class MapLayout { /** Layout rectangle. */ MapRect layout; /** Font size. */ final int o = GUIProp.fontsize + 4; /** * Constructor. */ MapLayout() { switch(GUIProp.maplayout) { case 0: layout = new MapRect(0, 0, 0, 0); break; case 1: layout = new MapRect(1, 1, 2, 2); break; case 2: layout = new MapRect(0, o, 0, o); break; case 3: layout = new MapRect(2, o - 1, 4, o + 1); break; case 4: layout = new MapRect(o >> 2, o, o >> 1, o + (o >> 2)); break; case 5: layout = new MapRect(o >> 1, o, o, o + (o >> 1)); break; default: } } /** * Calculates the average aspect Ratios of rectangles given in the List. * * @param r Array of rectangles * @return average aspect ratio */ public static double lineRatio(final ArrayList<MapRect> r) { if (r.isEmpty()) return Double.MAX_VALUE; double ar = 0; for(int i = 0; i < r.size(); i++) { if (r.get(i).w != 0 && r.get(i).h != 0) { if (r.get(i).w > r.get(i).h) { ar += r.get(i).w / r.get(i).h; } else { ar += r.get(i).h / r.get(i).w; } } } return ar / r.size(); } /** * Computes average aspect ratio of a rectangle list as specified by * Shneiderman (checks only leafnodes). * * @param r arrraylist of rects * @return aar */ public static double aar(final ArrayList<MapRect> r) { double aar = 0; for(int i = 0; i < r.size(); i++) { MapRect curr = r.get(i); // [JH] some problems occur after changing database. // solve to include only leafnodes // ViewData.isLeaf(data, curr.pre) && if (curr.w != 0 && curr.h != 0) { if (curr.w > curr.h) { aar += curr.w / curr.h; } else { aar += curr.h / curr.w; } } } return aar / r.size(); } /** * Calculates the average distance of two maplayouts using the euclidean * distance of each rect in the first and the second rectlist. * * [JH] how to handle rects available in one of the lists not included in * the other one? * * @param first array of view rectangles * @param second array of view rectangles * @return average distance */ public static double averageDistanceChange(final ArrayList<MapRect> first, final ArrayList<MapRect> second) { double aDist = 0.0; int length = Math.min(first.size(), second.size()); int x1, x2, y1, y2; for (int i = 0; i < length; i++) { if(first.get(i).pre == second.get(i).pre) { x1 = first.get(i).x + first.get(i).w >> 1; x2 = second.get(i).x + second.get(i).w >> 1; y1 = first.get(i).y + first.get(i).h >> 1; y2 = second.get(i).y + second.get(i).h >> 1; aDist += ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) ^ (1 / 2); } } return aDist / length; } /** * Returns the number of rectangles painted. * * @param rectangles array of painted rects * @return nr of rects in the list */ public int getNumberRects(final ArrayList<MapRect> rectangles) { return rectangles.size(); } /** * Returns all children of the specified node. * @param data data reference * @param par parent node * @return children */ protected static MapList children(final Data data, final int par) { final MapList list = new MapList(); final int kind = data.kind(par); final int last = par + data.size(par, kind); final boolean atts = GUIProp.mapatts && data.fs == null; int p = par + (atts ? 1 : data.attSize(par, kind)); while(p != last) { list.add(p); p += data.size(p, data.kind(p)); } // paint all children if(list.size != 0) list.add(p); return list; } /** * Calculates the percentual weight to use. * uses gui prop slider (size_p) to define size by any attributes (for now * use mixture of size and number of children) * weight = size_p * size + (1 - size_p) * |childs| whereas size_p in [0;1] * * [JH] should be possible to replace size and childs by any other * numerical attributes in future. * * @param rect pre val of rect * @param par comparison rectangles * @param data Data reference * @return weight in context */ public static double calcWeight(final int rect, final int par, final Data data) { double weight; // get size of the node long size = Token.toLong(data.attValue(data.sizeID, rect)); // parents size long sSize = Token.toLong(data.attValue(data.sizeID, par)); // call weightening function weight = calcWeight(size, children(data, rect).size, sSize, children(data, par).size, data); return weight; } /** * Computes weight with given values for each value using GUIprop.sizep. * weight = sizep/100 * size + (1 - sizep/100) * |childs| * whereas sizep in (0;100) * * @param size one nodes size * @param childs one nodes number of childs * @param sSize compare to more nodes size * @param sChilds compare to more nodes number of childs * @param data context * @return weight */ public static double calcWeight(final long size, final int childs, final long sSize, final int sChilds, final Data data) { // if its not a filesystem, set sliderval for calc only to nr of childs double sizeP = data.fs != null ? (double) GUIProp.sizep : 0d; if (sSize == 0) sizeP = 0d; long dadSize = (size == 0 && sSize == 0) ? 1 : sSize; return ((sizeP / 100) * ((double) size / dadSize)) + ((1 - sizeP / 100) * ((double) childs / sChilds)); } /** * Adds all the sizes attribute of the nodes in the given list. * @param l list of nodes * @param start at element * @param end here * @param data take this data kontext * @return sum of the size attribute */ public static long addSizes(final IntList l, final int start, final int end, final Data data) { long sum = 0; for (int i = start; i < end; i++) { sum += Token.toLong(data.attValue(data.sizeID, l.list[i])); } return sum; } /** * One rectangle left, add it and continue with its children. * @param data data reference * @param r parent rectangle * @param mainRects stores already layout rectangles * @param l children array * @param ns start array position * @param level indicates level which is calculated */ protected void putRect(final Data data, final MapRect r, final ArrayList<MapRect> mainRects, final IntList l, final int ns, final int level) { // calculate rectangle sizes final MapRect t = new MapRect(r.x, r.y, r.w, r.h, l.list[ns], r.level); mainRects.add(t); // position, with and height calculated using sizes of former level final int x = t.x + layout.x; final int y = t.y + layout.y; final int w = t.w - layout.w; final int h = t.h - layout.h; // skip too small rectangles and leaf nodes (= meta data in deepfs) if((w >= o || h >= o) && w > 0 && h > 0 && !ViewData.isLeaf(data, t.pre)) { final MapList ch = children(data, t.pre); if(ch.size != 0) calcMap(data, new MapRect(x, y, w, h, l.list[ns], r.level + 1), mainRects, ch, 0, ch.size - 1, level + 1); } } /** * Splits and adds rectangles uniformly distributed. * @param data reference * @param r rectangles to lay out in * @param mainRects rect array reference * @param l list of rectangles to lay out * @param ns starting point * @param ne ending * @param level on which the nodes are * @param v vertically??? * */ protected void splitUniformly(final Data data, final MapRect r, final ArrayList<MapRect> mainRects, final MapList l, final int ns, final int ne, final int level, final boolean v) { long nn, ln; int ni; // number of nodes used to calculate space nn = ne - ns; // nn / 2, pretends to be the middle of the handled list // except if starting point in the list is not at position 0 ln = nn >> 1; // pivot with integrated list start ni = (int) (ns + ln); int xx = r.x; int yy = r.y; int ww = !v ? r.w : (int) (r.w * ln / nn); int hh = v ? r.h : (int) (r.h * ln / nn); // paint both rectangles if enough space is left if(ww > 0 && hh > 0) calcMap(data, new MapRect(xx, yy, ww, hh, 0, r.level), mainRects, l, ns, ni, level); if(v) { xx += ww; ww = r.w - ww; } else { yy += hh; hh = r.h - hh; } if(ww > 0 && hh > 0) calcMap(data, new MapRect(xx, yy, ww, hh, 0, r.level), mainRects, l, ni, ne, level); } /** * Recursively splits rectangles. * @param data data reference * @param r parent rectangle * @param mainRects stores already layout rectangles * @param l children array * @param ns start array position * @param ne end array position * @param level indicates level which is calculated */ abstract void calcMap(final Data data, final MapRect r, ArrayList<MapRect> mainRects, final MapList l, final int ns, final int ne, final int level); /** * Find out which kind of Maplayout is used right now. * @return name Of Layoutalgorithm */ abstract String getType(); }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import org.usfirst.frc330.Beachbot2013Java.commands.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /* * $Log: OI.java,v $ * Revision 1.24 2013-03-18 00:36:38 echan * removed armpickup * * Revision 1.23 2013-03-17 18:22:25 jross * add shootLowCommandGroup to SmartDashboard * * Revision 1.22 2013-03-17 17:27:05 jross * Add PickupOffCommandGroup to safely turn off pickup and shooter * * Revision 1.21 2013-03-17 17:21:06 jross * change pickup buttons per Matt's direction * * Revision 1.20 2013-03-17 17:17:32 jross * use command group for shooting and pickup on * * Revision 1.19 2013-03-17 01:57:22 jdavid * Added pickup sensor * * Revision 1.18 2013-03-15 03:08:37 echan * Added the command to shoot low at full speed * * Revision 1.17 2013-03-15 02:50:16 echan * added cvs log comments * */ /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public JoystickButton shiftHighButton; public Joystick leftJoystick; public JoystickButton shiftLowButton; public Joystick rightJoystick; public JoystickButton pickupDownButton; public JoystickButton pickupUpButton; public JoystickButton shootButton; public JoystickButton shootHighButton; public JoystickButton shootLowButton; public JoystickButton armClimbingButton; public JoystickButton frisbeePickupOffButton; public JoystickButton frisbeePickupOnButton; public JoystickButton slowFrisbeePickupButton; public JoystickButton reversePickupButton; public JoystickButton climbButton; public Joystick operatorJoystick; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS operatorJoystick = new Joystick(3); climbButton = new JoystickButton(operatorJoystick, 11); climbButton.whenPressed(new LiftRobot()); reversePickupButton = new JoystickButton(operatorJoystick, 10); reversePickupButton.whenPressed(new ReversePickup()); slowFrisbeePickupButton = new JoystickButton(operatorJoystick, 3); slowFrisbeePickupButton.whenPressed(new SlowPickupFrisbees()); frisbeePickupOnButton = new JoystickButton(operatorJoystick, 7); frisbeePickupOnButton.whenPressed(new PickupOnCommandGroup()); frisbeePickupOffButton = new JoystickButton(operatorJoystick, 6); frisbeePickupOffButton.whenPressed(new PickupOffCommandGroup()); armClimbingButton = new JoystickButton(operatorJoystick, 5); armClimbingButton.whenPressed(new ArmClimbing()); shootLowButton = new JoystickButton(operatorJoystick, 2); shootLowButton.whenPressed(new ShootLowCommandGroup()); shootHighButton = new JoystickButton(operatorJoystick, 4); shootHighButton.whenPressed(new ArmHighShooting()); shootButton = new JoystickButton(operatorJoystick, 1); shootButton.whenPressed(new LaunchFrisbee()); pickupUpButton = new JoystickButton(operatorJoystick, 8); pickupUpButton.whenPressed(new PickupUp()); pickupDownButton = new JoystickButton(operatorJoystick, 9); pickupDownButton.whenPressed(new PickupDown()); rightJoystick = new Joystick(2); shiftLowButton = new JoystickButton(rightJoystick, 1); shiftLowButton.whenPressed(new ShiftLow()); leftJoystick = new Joystick(1); shiftHighButton = new JoystickButton(leftJoystick, 1); shiftHighButton.whenPressed(new ShiftHigh()); // SmartDashboard Buttons SmartDashboard.putData("AutonomousCommand", new AutonomousCommand()); SmartDashboard.putData("ShiftHigh", new ShiftHigh()); SmartDashboard.putData("ShiftLow", new ShiftLow()); SmartDashboard.putData("MarsRock", new MarsRock()); SmartDashboard.putData("PickupDown", new PickupDown()); SmartDashboard.putData("PickupUp", new PickupUp()); SmartDashboard.putData("LaunchFrisbee", new LaunchFrisbee()); SmartDashboard.putData("ShootHigh", new ShootHigh()); SmartDashboard.putData("ShootLow", new ShootLow()); SmartDashboard.putData("PickupFrisbeesOn", new PickupFrisbeesOn()); SmartDashboard.putData("PickupFrisbeesOff", new PickupFrisbeesOff()); SmartDashboard.putData("ReversePickup", new ReversePickup()); SmartDashboard.putData("SlowPickupFrisbees", new SlowPickupFrisbees()); SmartDashboard.putData("ArmLowShooting", new ArmLowShooting()); SmartDashboard.putData("ArmHighShooting", new ArmHighShooting()); SmartDashboard.putData("ArmClimbing", new ArmClimbing()); SmartDashboard.putData("StopShootHigh", new StopShootHigh()); SmartDashboard.putData("StopShootLow", new StopShootLow()); SmartDashboard.putData("ShootLowCommandGroup", new ShootLowCommandGroup()); SmartDashboard.putData("ControlLEDs", new ControlLEDs()); SmartDashboard.putData("TurnCamera", new TurnCamera()); SmartDashboard.putData("TurnCameraIterative", new TurnCameraIterative()); SmartDashboard.putData("ArmLowPickup", new ArmLowPickup()); SmartDashboard.putData("SetArmZero", new SetArmZero()); SmartDashboard.putData("FullSpeedShootLow", new FullSpeedShootLow()); SmartDashboard.putData("PickupOnCommandGroup", new PickupOnCommandGroup()); SmartDashboard.putData("PickupOffCommandGroup", new PickupOffCommandGroup()); SmartDashboard.putData("ArmVariableShooting", new ArmVariableShooting()); SmartDashboard.putData("LiftRobot", new LiftRobot()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS public Joystick getLeftJoystick() { return leftJoystick; } public Joystick getRightJoystick() { return rightJoystick; } public Joystick getOperatorJoystick() { return operatorJoystick; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
package org.dc.jdbc.core.utils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dc.jdbc.core.CacheCenter; import org.dc.jdbc.core.entity.ClassRelation; import org.dc.jdbc.core.entity.ColumnBean; import org.dc.jdbc.core.entity.TableInfoBean; import org.dc.jdbc.exceptions.TooManyResultsException; /** * jdbc api * @author DC * */ public class JDBCUtils{ private static final Log LOG = LogFactory.getLog(JDBCUtils.class); public static void close(AutoCloseable...ac){ for (int i = 0; i < ac.length; i++) { AutoCloseable autoClose = ac[i]; if(autoClose!=null){ try { autoClose.close(); } catch (Exception e) { LOG.error("",e); } } } } /** * sql * @param ps * @param sql * @param params * @return * @throws Exception */ public static ResultSet preparedSQLReturnRS(PreparedStatement ps,String sql,Object[] params) throws Exception{ setParams(ps, params); return ps.executeQuery(); } /** * sql * @param conn * @param sql * @param params * @return * @throws Exception */ public static int preparedAndExcuteSQL(Connection conn,String sql,Object[] params) throws Exception{ PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); JDBCUtils.setParams(ps, params); return ps.executeUpdate(); } catch (Exception e) { throw e; }finally{ close(ps); } } /** * sqlmap * @param rs * @param list * @throws Exception */ @SuppressWarnings("unchecked") private static <T> List<T> parseSqlResultToListMap(ResultSet rs) throws Exception{ List<Object> list = new ArrayList<Object>(); ResultSetMetaData metaData = rs.getMetaData(); int cols_len = metaData.getColumnCount(); while(rs.next()){ list.add(getMap(rs, metaData, cols_len)); } if(list.size()==0){ return null; }else{ return (List<T>) list; } } /** * sql * @param <T> * @param rs * @param cls * @param list * @throws Exception */ @SuppressWarnings("unchecked") private static <T> List<T> parseSqlResultToListObject(ResultSet rs,Class<? extends T> cls) throws Exception{ List<Object> list = new ArrayList<Object>(); ResultSetMetaData metaData = rs.getMetaData(); int cols_len = metaData.getColumnCount(); while(rs.next()){ list.add(getObject(rs, metaData, cls, cols_len)); } if(list.size()==0){ return null; }else{ return (List<T>) list; } } /** * sqljava * @param rs * @return * @throws Exception */ @SuppressWarnings("unchecked") private static <T> List<T> parseSqlResultToListBaseType(ResultSet rs) throws Exception{ List<Object> list = new ArrayList<Object>(); ResultSetMetaData metaData = rs.getMetaData(); int cols_len = metaData.getColumnCount(); if(cols_len>1){ throw new TooManyResultsException(cols_len); } while(rs.next()){ Object cols_value = getValueByObjectType(metaData, rs, 0); list.add(cols_value); } if(list.size()==0){ return null; }else{ return (List<T>) list; } } /** * sqlcls * @param rs * @param cls * @return * @throws Exception */ public static <T> List<T> parseSqlResultList(ResultSet rs, Class<? extends T> cls) throws Exception { if(cls==null || Map.class.isAssignableFrom(cls)){//Map return parseSqlResultToListMap(rs); }else{ if(cls.getClassLoader()==null){ return parseSqlResultToListBaseType(rs); }else{ return parseSqlResultToListObject(rs, cls); } } } public static void setParams(PreparedStatement ps, Object[] params) throws Exception { if(params!=null){ for (int i = 0,len=params.length; i < len; i++) { ps.setObject(i+1, params[i]); } } } private static Object getObject(ResultSet rs,ResultSetMetaData metaData,Class<?> cls,int cols_len) throws Exception{ //TableInfoBean tabInfo = JDBCUtils.getTableInfo(cls,SqlContext.getContext().getCurrentDataSource()); //List<ClassRelation> classRelationsList = JDBCUtils.getClassRelationList(cls, tabInfo, false); Object obj_newInsten = cls.newInstance(); for(int i = 0; i<cols_len; i++){ String col_name = metaData.getColumnLabel(i+1); /*String col_name = metaData.getColumnLabel(i+1); for (int j = 0; j < classRelationsList.size(); j++) { if(classRelationsList.get(j).getColumnBean().getColumnName().equals(col_name)){ Object cols_value = getValueByObjectType(metaData, rs, i); Field field = classRelationsList.get(j).getField(); field.setAccessible(true); field.set(obj_newInsten, cols_value); break; } }*/ Field field = null; try{ field = obj_newInsten.getClass().getDeclaredField(col_name); }catch (Exception e) { try{ field = obj_newInsten.getClass().getDeclaredField(JDBCUtils.getBeanName(col_name)); }catch (Exception e1) { } } if(field!=null && !Modifier.isStatic(field.getModifiers())){ Object cols_value = getValueByObjectType(metaData, rs, i); field.setAccessible(true); field.set(obj_newInsten, cols_value); } } return obj_newInsten; } private static Map<String, Object> getMap(ResultSet rs,ResultSetMetaData metaData,int cols_len) throws Exception{ Map<String, Object> map = new LinkedHashMap<String, Object>(); for(int i=0; i<cols_len; i++){ String cols_name = metaData.getColumnLabel(i+1); Object cols_value = getValueByObjectType(metaData, rs, i); map.put(cols_name, cols_value); } return map; } /** * indexjava * @param metaData * @param rs * @param index * @return * @throws Exception */ public static Object getValueByObjectType(ResultSetMetaData metaData,ResultSet rs,int index) throws Exception{ int columnIndex = index+1; Object return_obj = rs.getObject(columnIndex); if(return_obj!=null){ int type = metaData.getColumnType(columnIndex); switch (type){ case Types.BIT: return_obj = rs.getByte(columnIndex); break; case Types.TINYINT: return_obj = rs.getByte(columnIndex); break; case Types.SMALLINT: return_obj = rs.getShort(columnIndex); break; case Types.LONGVARBINARY: return_obj = rs.getBytes(columnIndex); break; default : return_obj = rs.getObject(columnIndex); } } return return_obj; } public static List<TableInfoBean> initDataBaseInfo(final DataSource dataSource){ List<TableInfoBean> tabList = CacheCenter.DATABASE_INFO_CACHE.get(dataSource); if(tabList==null){ Connection conn = null; try { tabList = new ArrayList<TableInfoBean>(); conn = dataSource.getConnection(); DatabaseMetaData meta = conn.getMetaData(); ResultSet tablesResultSet = meta.getTables(conn.getCatalog(), null, "%",new String[] { "TABLE" }); while(tablesResultSet.next()){ TableInfoBean tableBean = new TableInfoBean(); String tableName = tablesResultSet.getString("TABLE_NAME"); ResultSet colRS = meta.getColumns(conn.getCatalog(), "%", tableName, "%"); tableBean.setTableName(tableName); while(colRS.next()){ ColumnBean colbean = new ColumnBean(); String colName = colRS.getString("COLUMN_NAME"); colbean.setColumnType(colRS.getInt("DATA_TYPE")); colbean.setColumnName(colName); tableBean.getColumnList().add(colbean); } ResultSet primaryKeyResultSet = meta.getPrimaryKeys(conn.getCatalog(),null,tableName); while(primaryKeyResultSet.next()){ String primaryKeyColumnName = primaryKeyResultSet.getString("COLUMN_NAME"); for (int i = 0; i < tableBean.getColumnList().size(); i++) { ColumnBean colbean = tableBean.getColumnList().get(i); if(colbean.getColumnName().equals(primaryKeyColumnName)){ colbean.setPrimaryKey(true); break; } } } List<ColumnBean> colList = tableBean.getColumnList(); for (int i = 0; i < colList.size(); i++) { String col_name = colList.get(i).getColumnName(); for (int j = i+1; j < colList.size(); j++) { if(getBeanName(colList.get(j).getColumnName()).equalsIgnoreCase(getBeanName(col_name))){ try{ throw new Exception("field name='"+tableName+"."+col_name+"' is not standard"); }catch(Exception e ){ LOG.error("",e); } } } } for (int i = 0; i < tabList.size(); i++) { if(getBeanName(tabList.get(i).getTableName()).equalsIgnoreCase(getBeanName(tableName))){ try{ throw new Exception("table name= '"+tabList.get(i).getTableName()+"' is not standard"); }catch(Exception e ){ LOG.error("",e); } } } tabList.add(tableBean); } CacheCenter.DATABASE_INFO_CACHE.put(dataSource, tabList); } catch (Exception e) { LOG.info("",e); }finally{ try { if(conn!=null && !conn.isClosed()){ conn.close(); } } catch (SQLException e) { LOG.info("",e); } } } return tabList; } /** * java bean * @param str * @return */ public static String getBeanName(String str){ int markIndex = str.lastIndexOf("_"); if(markIndex!=-1){ String startStr = str.substring(0, markIndex); String endStr = str.substring(markIndex, str.length()); String newStr = startStr + endStr.substring(1, 2).toUpperCase()+endStr.substring(2); return getBeanName(newStr); }else{ return str.substring(0,1).toLowerCase()+str.substring(1); } } /** * java() * @param str * @return */ public static String javaBeanToSeparator(String str,Character separatorChar){ if(str==null || str.length()==0){ return null; } if(separatorChar==null){ separatorChar = '_'; } StringBuilder sb =new StringBuilder(str); int index=0; for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if(Character.isUpperCase(c)){ sb.replace(i+index, i+1+index, String.valueOf(c).toLowerCase()); sb.insert(i+index, separatorChar); index++; } } return sb.toString().toLowerCase(); } public static TableInfoBean getTableInfo(Class<?> entityClass,DataSource dataSource) throws Exception{ TableInfoBean tabInfo = CacheCenter.SQL_TABLE_CACHE.get(entityClass); if(tabInfo==null){ String className = entityClass.getSimpleName(); String class_tabName = javaBeanToSeparator(className, null); List<TableInfoBean> db_tabList = initDataBaseInfo(dataSource); for (int i = 0; i < db_tabList.size(); i++) { TableInfoBean db_tabInfo = db_tabList.get(i); String tabname = db_tabInfo.getTableName(); if(tabname.equalsIgnoreCase(class_tabName)){ tabInfo = db_tabInfo; break; } } if(tabInfo == null){ throw new Exception("table "+JDBCUtils.javaBeanToSeparator(entityClass.getSimpleName(), null)+" is not exist"); } CacheCenter.SQL_TABLE_CACHE.put(entityClass, tabInfo); } return tabInfo; } public static List<ClassRelation> getClassRelationList(Class<?> entityClass,TableInfoBean tabInfo,boolean ischeckPK) throws Exception{ List<ClassRelation> classRelationsList = CacheCenter.CLASS_REL_FIELD_CACHE.get(entityClass); if(classRelationsList==null){ classRelationsList = new ArrayList<ClassRelation>(); Field[] fieldArr = entityClass.getDeclaredFields(); Field pk_field = null; ColumnBean col_pk = null; for (int i = 0; i < fieldArr.length; i++) { Field field = fieldArr[i]; if(!Modifier.isStatic(field.getModifiers())){ String fdName = field.getName(); for (int j = 0; j < tabInfo.getColumnList().size(); j++) { ColumnBean col = tabInfo.getColumnList().get(j); if(fdName.equalsIgnoreCase(col.getColumnName()) || JDBCUtils.getBeanName(col.getColumnName()).equalsIgnoreCase(fdName)){ if(col.isPrimaryKey()){ pk_field = field; if(col_pk!=null){ throw new Exception("primary key ="+col_pk.getColumnName()+" is too many.Make sure there is only one primary key."); } col_pk = col; break; }else{ ClassRelation classRelation = new ClassRelation(); classRelation.setField(field); classRelation.setColumnBean(col); classRelationsList.add(classRelation); } } } } } if(ischeckPK && col_pk==null ){ throw new Exception("primary key is not exist"); }else{ if(col_pk!=null){ ClassRelation classRelation = new ClassRelation(); classRelation.setField(pk_field); classRelation.setColumnBean(col_pk); classRelationsList.add(classRelation); } } CacheCenter.CLASS_REL_FIELD_CACHE.put(entityClass, classRelationsList); } return classRelationsList; } }
package org.usfirst.frc.team1306.robot; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team1306.robot.commands.ExampleCommand; import org.usfirst.frc.team1306.robot.subsystems.ExampleSubsystem; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem(); public static OI oi; Command autonomousCommand; SendableChooser chooser; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { oi = new OI(); chooser = new SendableChooser(); chooser.addDefault("Default Auto", new ExampleCommand()); // chooser.addObject("My Auto", new MyAutoCommand()); SmartDashboard.putData("Auto mode", chooser); } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ public void disabledInit(){ } public void disabledPeriodic() { Scheduler.getInstance().run(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example) * or additional comparisons to the switch structure below with additional strings & commands. */ public void autonomousInit() { autonomousCommand = (Command) chooser.getSelected(); /* String autoSelected = SmartDashboard.getString("Auto Selector", "Default"); switch(autoSelected) { case "My Auto": autonomousCommand = new MyAutoCommand(); break; case "Default Auto": default: autonomousCommand = new ExampleCommand(); break; } */ // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package yaplstack; import java.lang.reflect.*; import java.util.function.BiFunction; import java.util.function.Function; // Instructions should be replaced by first class objects, that are designed to be ("more") interpretable public interface Instruction { void eval(Thread thread); interface IncIP extends Instruction { default void eval(Thread thread) { doEval(thread); thread.callFrame.incrementIP(); } void doEval(Thread thread); } class Factory { public static IncIP loadConst(Object obj) { return thread -> thread.callFrame.push(obj); } public static IncIP dup = thread -> thread.callFrame.dup(); public static IncIP dupx1down = thread -> thread.callFrame.dupx1down(); public static IncIP pop = thread -> thread.callFrame.pop(); public static IncIP dupx(int delta) { return thread -> thread.callFrame.dupx(delta); } public static IncIP bp = thread -> new String(); public static Instruction resume(int pushCount) { return thread -> { CallFrame target = (CallFrame)thread.callFrame.pop(); thread.callFrame.pushTo(target, pushCount); target.incrementIP(); thread.callFrame = target; }; } public static Instruction finish = thread -> thread.setFinished(); public static Instruction store(String name) { return thread -> { int code = thread.symbolTable.getCode(name); thread.callFrame.codeSegment.instructions[thread.callFrame.ip] = store(code); }; } public static IncIP store(int code) { return thread -> { Object value = thread.callFrame.pop(); Environment environment = (Environment)thread.callFrame.pop(); environment.store(code, value); }; } public static Instruction load(String name) { return thread -> { int code = thread.symbolTable.getCode(name); thread.callFrame.codeSegment.instructions[thread.callFrame.ip] = load(code); }; } public static IncIP load(int code) { return thread -> { Environment environment = (Environment)thread.callFrame.pop(); Object value = environment.load(code); if(value == null) throw new RuntimeException("\"" + thread.symbolTable.getSymbol(code) + "\" is undefined."); thread.callFrame.push(value); }; } public static Instruction loadd(String name) { return thread -> { int code = thread.symbolTable.getCode(name); thread.callFrame.codeSegment.instructions[thread.callFrame.ip] = loadd(code); }; } public static IncIP loadd(int code) { return thread -> { // Load via "dynamic scope" CallFrame frame = thread.callFrame; while(true) { Environment environment = (Environment)frame.stack.get(0); Object value = environment.load(code); if(value != null) { thread.callFrame.push(value); return; } frame = frame.outer; if(frame == null) break; } throw new RuntimeException("\"" + thread.symbolTable.getSymbol(code) + "\" is undefined."); }; } public static IncIP storeVar(int ordinal) { return thread -> { Object value = thread.callFrame.pop(); thread.callFrame.set(ordinal, value); }; } public static IncIP loadVar(int ordinal) { return thread -> { Object value = thread.callFrame.get(ordinal); thread.callFrame.push(value); }; } public static IncIP frameStoreVar(int ordinal) { return thread -> { Object value = thread.callFrame.pop(); CallFrame frame = (CallFrame)thread.callFrame.pop(); frame.set(ordinal, value); }; } public static IncIP frameLoadVar(int ordinal) { return thread -> { CallFrame frame = (CallFrame)thread.callFrame.pop(); Object value = frame.get(ordinal); thread.callFrame.push(value); }; } public static IncIP newEnvironment = thread -> thread.callFrame.push(new Environment()); public static IncIP loadCallFrame = thread -> thread.callFrame.push(thread.callFrame); public static Instruction pushCallFrame(int pushCount) { return thread -> { CodeSegment codeSegment = (CodeSegment)thread.callFrame.pop(); if(codeSegment == null) throw new NullPointerException(); thread.callFrame = new CallFrame(thread.callFrame, codeSegment); thread.callFrame.outer.pushTo(thread.callFrame, pushCount); }; } public static Instruction jumpIfTrue(int index) { return thread -> { boolean condition = (boolean)thread.callFrame.pop(); if(condition) thread.callFrame.setIP(index); else thread.callFrame.incrementIP(); }; }; public static Instruction popCallFrame(int pushCount) { return thread -> { thread.callFrame.pushTo(thread.callFrame.outer, pushCount); thread.callFrame = thread.callFrame.outer; thread.callFrame.incrementIP(); }; } private static <T, R> IncIP unaryReducer(Function<T, R> reducer) { return thread -> { T operand = (T)thread.callFrame.pop(); R res = reducer.apply(operand); thread.callFrame.push(res); }; } private static <T, R, S> IncIP binaryReducer(BiFunction<T, R, S> reducer) { return thread -> { R operand2 = (R)thread.callFrame.pop(); T operand1 = (T)thread.callFrame.pop(); S res = reducer.apply(operand1, operand2); thread.callFrame.push(res); }; } public static IncIP not = unaryReducer((Boolean b) -> !b); public static IncIP and = binaryReducer((Boolean lhs, Boolean rhs) -> lhs && rhs);; public static IncIP or = binaryReducer((Boolean lhs, Boolean rhs) -> lhs || rhs);; public static IncIP addi = binaryReducer((Integer lhs, Integer rhs) -> lhs + rhs); public static IncIP subi = binaryReducer((Integer lhs, Integer rhs) -> lhs - rhs); public static IncIP muli = binaryReducer((Integer lhs, Integer rhs) -> lhs * rhs); public static IncIP divi = binaryReducer((Integer lhs, Integer rhs) -> lhs / rhs); public static IncIP lti = binaryReducer((Integer lhs, Integer rhs) -> lhs < rhs); public static IncIP gti = binaryReducer((Integer lhs, Integer rhs) -> lhs > rhs); public static IncIP eqi = binaryReducer((Integer lhs, Integer rhs) -> (int)lhs == (int)rhs); public static IncIP eqc = binaryReducer((Character lhs, Character rhs) -> (char)lhs == (char)rhs); public static IncIP itoc = unaryReducer((Integer i) -> (char) i.intValue()); public static IncIP newInstance(Constructor<?> constructor) { return thread -> { int argCount = constructor.getParameterCount(); Object[] args = new Object[argCount]; for(int i = argCount - 1; i >= 0; i args[i] = thread.callFrame.pop(); Object res = null; try { res = constructor.newInstance(args); thread.callFrame.push(res); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // How to handle exceptions? }; } public static IncIP invoke(Method method) { boolean instance = !Modifier.isStatic(method.getModifiers()); return thread -> { Method m = method; if(method.getName().equals("append")) new String(); int argCount = method.getParameterCount(); Object[] args = new Object[argCount]; for(int i = argCount - 1; i >= 0; i args[i] = thread.callFrame.pop(); Object obj = instance ? thread.callFrame.pop() : null; Object res = null; try { res = method.invoke(obj, args); thread.callFrame.push(res); thread.toString(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch(NullPointerException e) { e.printStackTrace(); } // How to handle exceptions? }; } public static IncIP fieldGet(Field field) { boolean instance = !Modifier.isStatic(field.getModifiers()); return thread -> { Object obj = instance ? thread.callFrame.pop() : null; Object res = null; try { res = field.get(obj); thread.callFrame.push(res); } catch (IllegalAccessException e) { e.printStackTrace(); } // How to handle exceptions? }; } public static IncIP fieldSet(Field field) { boolean instance = !Modifier.isStatic(field.getModifiers()); return thread -> { Object value = thread.callFrame.pop(); Object obj = instance ? thread.callFrame.pop() : null; try { field.set(obj, value); } catch (IllegalAccessException e) { e.printStackTrace(); } // How to handle exceptions? }; } } }
package org.usfirst.frc.team1492.robot; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.Joystick.AxisType; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.PIDController; public class Robot extends SampleRobot { Talon motorLeft; Talon motorRight; Talon motorCenter; // Motor controller for the middle of the H Talon motorLift; Talon motorArm; DoubleSolenoid pistonArmTilt; Solenoid pistonHand; Solenoid pistonLiftWidth; //PIDController PIDControllerLift; AnalogInput analogLift; DigitalInput digitalInLiftTop; DigitalInput digitalInLiftBottom; DigitalInput digitalInArmUp; DigitalInput digitalInArmDown; Joystick stickLeft; Joystick stickRight; Joystick stickAux; boolean[] stickAuxLastButton = new boolean[stickAux.getButtonCount()]; double SETTING_hDriveDampening; double SETTING_motorLiftSpeed; double SETTING_armLiftSpeed; int liftPos = 0; int liftPosMax = 4; int liftPosMin = 0; int armSpeed = 0; double[] liftPosPresets = { 0, .25, .5, .75, 1 }; double hCurrent; public Robot() { motorLeft = new Talon(1); motorRight = new Talon(2); motorCenter = new Talon(0); motorLift = new Talon(4); motorArm = new Talon(3); pistonArmTilt = new DoubleSolenoid(0, 1); pistonHand = new Solenoid(2); pistonLiftWidth = new Solenoid(3); analogLift = new AnalogInput(0); digitalInLiftTop = new DigitalInput(0); digitalInLiftBottom = new DigitalInput(1); digitalInArmUp = new DigitalInput(2); digitalInArmDown = new DigitalInput(3); /* PIDControllerLift = new PIDController(0, 0, 0, analogLift, motorLift); PIDControllerLift.setInputRange(0, 1); PIDControllerLift.setOutputRange(0, .5); PIDControllerLift.disable(); */ stickLeft = new Joystick(0); stickRight = new Joystick(1); stickAux = new Joystick(2); } public void autonomous() { } public void operatorControl() { // CameraThread c = new CameraThread(); //PIDControllerLift.enable(); while (isOperatorControl() && isEnabled()) { driveControl(); manipulatorControl(); Timer.delay(0.005); } //PIDControllerLift.disable(); // c.finish(); } public void test() { } public void driveControl() { SETTING_hDriveDampening = SmartDashboard.getNumber("hDriveDampening", 5); double leftSide = -stickLeft.getAxis(AxisType.kY); double rightSide = stickRight.getAxis(AxisType.kY); double hTarget = farthestFrom0(stickLeft.getAxis(AxisType.kX), stickRight.getAxis(AxisType.kX)); hTarget = deadbandScale(hTarget, .2); hTarget /= 2; motorLeft.set(leftSide); motorRight.set(rightSide); motorCenter.set(hCurrent); } public void manipulatorControl() { // Calibration: SETTING_motorLiftSpeed = stickAux.getAxis(AxisType.kZ); SmartDashboard.putNumber("motorLiftSpeed (auxStick)", SETTING_motorLiftSpeed); SETTING_armLiftSpeed = stickRight.getAxis(AxisType.kZ); SmartDashboard.putNumber("armLiftSpeed (rightStick)", SETTING_armLiftSpeed); //Lift Up/Down /* DISABLED PID if(stickAux.getRawButton(3) && !stickAuxLastButton[3]){//up liftPos ++; } if(stickAux.getRawButton(2) && !stickAuxLastButton[2]){//down liftPos --; } if (liftPos > liftPosMax) { liftPos = liftPosMax; } if (liftPos < liftPosMin) { liftPos = liftPosMin; } PIDControllerLift.setSetpoint(liftPosPresets[liftPos]); */ //Instead of PID if(stickAux.getRawButton(3)){ motorLift.set(-0.1); } if(stickAux.getRawButton(2)){ motorLift.set(0.1); } if ((digitalInLiftTop.get() && liftPos == liftPosMax) || (digitalInLiftBottom.get() && liftPos == liftPosMin)) { motorLift.set(0); } // Arm Up/Down motorArm.set(stickAux.getAxis(AxisType.kY)); if ((digitalInArmUp.get() && armSpeed > 0) || (digitalInArmDown.get() && armSpeed < 0)) { motorArm.set(0); } // Lift Width in/out if (stickAux.getRawButton(4)) { // left out pistonLiftWidth.set(true); } if (stickAux.getRawButton(5)) { // right in pistonLiftWidth.set(false); } // arm tilt pistonArmTilt.set(Value.kOff); if (stickAux.getRawButton(6)) { // tilt forward pistonArmTilt.set(Value.kForward); } if (stickAux.getRawButton(7)) { // tilt backward pistonArmTilt.set(Value.kReverse); } //Hand pistonHand.set(stickAux.getRawButton(1)); for(int i=1;i<stickAuxLastButton.length;i++){ stickAuxLastButton[i] = stickAux.getRawButton(7); } // Hand pistonHand.set(stickAux.getRawButton(1)); } double deadbandScale(double input, double threshold){ return input > threshold ? (input - threshold)/(1-threshold) : input < -threshold ? (input + threshold)/(1-threshold) : 0; } double farthestFrom0(double a, double b){ if(Math.abs(a) > Math.abs(b)){ return a; }else{ return b; } } }
package matlabcontrol; import java.rmi.MarshalException; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.rmi.UnmarshalException; import java.rmi.server.UnicastRemoteObject; import java.util.Timer; import java.util.TimerTask; /** * Allows for calling MATLAB from <strong>outside</strong> of MATLAB. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxy extends MatlabProxy { /** * The remote JMI wrapper which is a remote object connected over RMI. */ private final JMIWrapperRemote _jmiWrapper; /** * The receiver for the proxy. While the receiver is bound to the RMI registry and a reference is maintained * (the RMI registry uses weak references), the connection to MATLAB's JVM will remain active. The JMI wrapper, * while a remote object, is not bound to the registry, and will not keep the RMI thread running. */ private final RequestReceiver _receiver; /** * A timer that periodically checks if still connected. */ private final Timer _connectionTimer; /** * Whether the proxy is connected. If the value is {@code false} the proxy is definitely disconnected. If the value * is {@code true} then the proxy <i>may</i> be disconnected. The accuracy of this will be checked then the next * time {@link #isConnected()} is called and this value will be updated if necessary. */ private volatile boolean _isConnected = true; /** * The duration (in milliseconds) between checks to determine if still connected. */ private static final int CONNECTION_CHECK_PERIOD = 1000; /** * The proxy is never to be created outside of this package, it is to be constructed after a * {@link JMIWrapperRemote} has been received via RMI. * * @param internalProxy * @param receiver * @param id * @param existingSession */ RemoteMatlabProxy(JMIWrapperRemote internalProxy, RequestReceiver receiver, Identifier id, boolean existingSession) { super(id, existingSession); _connectionTimer = new Timer("MLC Connection Listener " + id); _jmiWrapper = internalProxy; _receiver = receiver; } /** * Initializes aspects of the proxy that cannot be done safely in the constructor without leaking a reference to * {@code this}. */ void init() { _connectionTimer.schedule(new CheckConnectionTask(), CONNECTION_CHECK_PERIOD, CONNECTION_CHECK_PERIOD); } private class CheckConnectionTask extends TimerTask { @Override public void run() { if(!RemoteMatlabProxy.this.isConnected()) { //If not connected, perform disconnection so RMI thread can terminate RemoteMatlabProxy.this.disconnect(); //Notify listeners notifyDisconnectionListeners(); //Cancel timer, which will terminate the timer's thread _connectionTimer.cancel(); } } } @Override public boolean isRunningInsideMatlab() { return false; } @Override public boolean isConnected() { //If believed to be connected, verify this is up to date information if(_isConnected) { boolean connected; //Call a remote method, if it throws a RemoteException then it is no longer connected try { _jmiWrapper.checkConnection(); connected = true; } catch(RemoteException e) { connected = false; } _isConnected = connected; } return _isConnected; } @Override public boolean disconnect() { _connectionTimer.cancel(); //Unexport the receiver so that the RMI threads can shut down try { //If succesfully exported, then definitely not connected //If the export failed, we still might be connected, isConnected() will check _isConnected = !UnicastRemoteObject.unexportObject(_receiver, true); } //If it is not exported, that's ok because we were trying to unexport it catch(NoSuchObjectException e) { } return this.isConnected(); } // Methods which interact with MATLAB (and helper methods and interfaces) private static interface RemoteInvocation<T> { public T invoke() throws RemoteException, MatlabInvocationException; } private <T> T invoke(RemoteInvocation<T> invocation) throws MatlabInvocationException { if(!_isConnected) { throw MatlabInvocationException.Reason.PROXY_NOT_CONNECTED.asException(); } else { try { return invocation.invoke(); } catch(UnmarshalException e) { throw MatlabInvocationException.Reason.UNMARSHAL.asException(e); } catch(MarshalException e) { throw MatlabInvocationException.Reason.MARSHAL.asException(e); } catch(RemoteException e) { if(this.isConnected()) { throw MatlabInvocationException.Reason.UNKNOWN.asException(e); } else { throw MatlabInvocationException.Reason.PROXY_NOT_CONNECTED.asException(e); } } } } @Override public void setVariable(final String variableName, final Object value) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.setVariable(variableName, value); return null; } }); } @Override public Object getVariable(final String variableName) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object>() { @Override public Object invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.getVariable(variableName); } }); } @Override public void exit() throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.exit(); return null; } }); } @Override public void eval(final String command) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.eval(command); return null; } }); } @Override public Object[] returningEval(final String command, final int nargout) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object[]>() { @Override public Object[] invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.returningEval(command, nargout); } }); } @Override public void feval(final String functionName, final Object... args) throws MatlabInvocationException { this.invoke(new RemoteInvocation<Void>() { @Override public Void invoke() throws RemoteException, MatlabInvocationException { _jmiWrapper.feval(functionName, args); return null; } }); } @Override public Object[] returningFeval(final String functionName, final int nargout, final Object... args) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<Object[]>() { @Override public Object[] invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.returningFeval(functionName, nargout, args); } }); } @Override public <T> T invokeAndWait(final MatlabThreadCallable<T> callable) throws MatlabInvocationException { return this.invoke(new RemoteInvocation<T>() { @Override public T invoke() throws RemoteException, MatlabInvocationException { return _jmiWrapper.invokeAndWait(callable); } }); } }
package org.intermine.webservice.server.template.result; import javax.servlet.http.HttpServletRequest; import org.intermine.web.logic.template.TemplateHelper; import org.intermine.web.logic.template.TemplateHelper.TemplateValueParseException; import org.intermine.web.logic.template.TemplateResultInput; import org.intermine.webservice.server.WebServiceRequestParser; import org.intermine.webservice.server.exceptions.BadRequestException; import org.intermine.webservice.server.query.result.QueryResultRequestParser; /** * Processes service request. Evaluates parameters and validates them and check if * its combination is valid. * * @author Jakub Kulaviak **/ public class TemplateResultRequestParser extends WebServiceRequestParser { private static final String NAME_PARAMETER = "name"; private HttpServletRequest request; /** * TemplateResultRequestProcessor constructor. * @param request request */ public TemplateResultRequestParser(HttpServletRequest request) { this.request = request; } /** * Returns parsed parameters in parameter object - so this * values can be easily obtained from this object. * @return web service input */ public TemplateResultInput getInput() { TemplateResultInput input = new TemplateResultInput(); parseRequest(input); return input; } private void parseRequest(TemplateResultInput input) { super.parseRequest(request, input); input.setName(getRequiredStringParameter(NAME_PARAMETER)); try { input.setConstraints(TemplateHelper.parseConstraints(request)); } catch (TemplateValueParseException e) { throw new BadRequestException(e.getMessage(), e); } input.setLayout(request.getParameter(QueryResultRequestParser.LAYOUT_PARAMETER)); } private String getRequiredStringParameter(String name) { String param = request.getParameter(name); if (param == null || "".equals(param)) { throw new BadRequestException("Missing required parameter: " + name); } else { return param; } } }