code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins.newui; import com.intellij.application.options.RegistryManager; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.*; import com.intellij.ide.plugins.org.PluginManagerFilters; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.HtmlChunk; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.Gray; import com.intellij.ui.JBColor; import com.intellij.ui.LicensingFacade; import com.intellij.ui.RelativeFont; import com.intellij.ui.components.labels.LinkListener; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.ui.AbstractLayoutManager; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.JBValue; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.plaf.ButtonUI; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.BooleanSupplier; public final class ListPluginComponent extends JPanel { public static final Color DisabledColor = JBColor.namedColor("Plugins.disabledForeground", new JBColor(0xB1B1B1, 0x696969)); public static final Color GRAY_COLOR = JBColor.namedColor("Label.infoForeground", new JBColor(Gray._120, Gray._135)); public static final Color SELECTION_COLOR = JBColor.namedColor("Plugins.lightSelectionBackground", new JBColor(0xEDF6FE, 0x464A4D)); public static final Color HOVER_COLOR = JBColor.namedColor("Plugins.hoverBackground", new JBColor(0xEDF6FE, 0x464A4D)); private static final Ref<Boolean> HANDLE_FOCUS_ON_SELECTION = new Ref<>(Boolean.TRUE); private final MyPluginModel myPluginModel; private final LinkListener<Object> mySearchListener; private final boolean myMarketplace; private final boolean myIsAllowed; private @NotNull IdeaPluginDescriptor myPlugin; private final @NotNull PluginsGroup myGroup; private boolean myOnlyUpdateMode; public IdeaPluginDescriptor myUpdateDescriptor; private final JLabel myNameComponent = new JLabel(); private final JLabel myIconComponent = new JLabel(AllIcons.Plugins.PluginLogo); private final BaselineLayout myLayout = new BaselineLayout(); JButton myRestartButton; InstallButton myInstallButton; JButton myUpdateButton; private JComponent myEnableDisableButton; private JCheckBox myChooseUpdateButton; private JComponent myAlignButton; private JPanel myMetricsPanel; private JLabel myRating; private JLabel myDownloads; private JLabel myVersion; private JLabel myVendor; private LicensePanel myLicensePanel; private LicensePanel myUpdateLicensePanel; private JPanel myErrorPanel; private ErrorComponent myErrorComponent; private OneLineProgressIndicator myIndicator; private EventHandler myEventHandler; @NotNull private EventHandler.SelectionType mySelection = EventHandler.SelectionType.NONE; public ListPluginComponent(@NotNull MyPluginModel pluginModel, @NotNull IdeaPluginDescriptor plugin, @NotNull PluginsGroup group, @NotNull LinkListener<Object> searchListener, boolean marketplace) { myPlugin = plugin; myGroup = group; myPluginModel = pluginModel; mySearchListener = searchListener; myMarketplace = marketplace; myIsAllowed = PluginManagerFilters.getInstance().isPluginAllowed(!marketplace, plugin); pluginModel.addComponent(this); setOpaque(true); setBorder(JBUI.Borders.empty(10)); setLayout(myLayout); myIconComponent.setVerticalAlignment(SwingConstants.TOP); myIconComponent.setOpaque(false); myLayout.setIconComponent(myIconComponent); myNameComponent.setText(myPlugin.getName()); myLayout.setNameComponent(RelativeFont.BOLD.install(myNameComponent)); createTag(); if (myIsAllowed) { createButtons(); createMetricsPanel(); createLicensePanel(); } else { createNotAllowedMarker(); } if (marketplace) { updateIcon(false, !myIsAllowed); } else { updateErrors(); } if (MyPluginModel.isInstallingOrUpdate(myPlugin)) { showProgress(false); } updateColors(EventHandler.SelectionType.NONE); } @NotNull PluginsGroup getGroup() { return myGroup; } @NotNull EventHandler.SelectionType getSelection() { return mySelection; } void setSelection(@NotNull EventHandler.SelectionType type) { setSelection(type, type == EventHandler.SelectionType.SELECTION); } void setSelection(@NotNull EventHandler.SelectionType type, boolean scrollAndFocus) { mySelection = type; if (scrollAndFocus) { JComponent parent = (JComponent)getParent(); if (parent != null) { scrollToVisible(parent, getBounds()); if (type == EventHandler.SelectionType.SELECTION && HANDLE_FOCUS_ON_SELECTION.get()) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(this, true)); } } } updateColors(type); repaint(); } void onSelection(@NotNull Runnable runnable) { try { HANDLE_FOCUS_ON_SELECTION.set(Boolean.FALSE); runnable.run(); } finally { HANDLE_FOCUS_ON_SELECTION.set(Boolean.TRUE); } } private static void scrollToVisible(@NotNull JComponent parent, @NotNull Rectangle bounds) { if (!parent.getVisibleRect().contains(bounds)) { parent.scrollRectToVisible(bounds); } } private void createNotAllowedMarker() { myInstallButton = new InstallButton(false); setupNotAllowedMarkerButton(); myLayout.addButtonComponent(myInstallButton); } private void setupNotAllowedMarkerButton() { if (myMarketplace || myPluginModel.getState(myPlugin).isDisabled()) { myInstallButton.setButtonColors(false); myInstallButton.setEnabled(false, IdeBundle.message("plugin.status.not.allowed")); myInstallButton.setToolTipText(IdeBundle.message("plugin.status.not.allowed.tooltip")); } else { myInstallButton.setButtonColors(false); myInstallButton.setEnabled(true, IdeBundle.message("plugin.status.not.allowed.but.enabled")); myInstallButton.setText(IdeBundle.message("plugin.status.not.allowed.but.enabled")); myInstallButton.setToolTipText(IdeBundle.message("plugin.status.not.allowed.tooltip")); myInstallButton.setBorderColor(JBColor.red); myInstallButton.setTextColor(JBColor.red); myInstallButton.addActionListener(e -> { myPluginModel.disable(List.of(myPlugin)); setupNotAllowedMarkerButton(); }); } ColorButton.setWidth72(myInstallButton); } private void createButtons() { if (myMarketplace) { if (InstalledPluginsState.getInstance().wasInstalled(myPlugin.getPluginId())) { myLayout.addButtonComponent(myRestartButton = new RestartButton(myPluginModel)); } else { myLayout.addButtonComponent(myInstallButton = new InstallButton(false)); myInstallButton .addActionListener( e -> myPluginModel.installOrUpdatePlugin(this, myPlugin, null, ModalityState.stateForComponent(myInstallButton))); myInstallButton.setEnabled(PluginManagerCore.getPlugin(myPlugin.getPluginId()) == null && !InstalledPluginsState.getInstance().wasInstalledWithoutRestart(myPlugin.getPluginId()), IdeBundle.message("plugin.status.installed")); ColorButton.setWidth72(myInstallButton); } } else { if (myPlugin instanceof IdeaPluginDescriptorImpl && ((IdeaPluginDescriptorImpl)myPlugin).isDeleted()) { myLayout.addButtonComponent(myRestartButton = new RestartButton(myPluginModel)); myPluginModel.addUninstalled(myPlugin); } else { InstalledPluginsState pluginsState = InstalledPluginsState.getInstance(); PluginId id = myPlugin.getPluginId(); if (pluginsState.wasInstalled(id) || pluginsState.wasUpdated(id)) { myLayout.addButtonComponent(myRestartButton = new RestartButton(myPluginModel)); } else { if (DynamicPluginEnabler.isPerProjectEnabled() && !RegistryManager.getInstance().is("ide.plugins.per.project.use.checkboxes")) { myEnableDisableButton = SelectionBasedPluginModelAction.createGearButton( action -> createEnableDisableAction(action, List.of(this)), () -> createUninstallAction(List.of(this)) ); myEnableDisableButton.setBorder(JBUI.Borders.emptyLeft(5)); myEnableDisableButton.setBackground(PluginManagerConfigurable.MAIN_BG_COLOR); } else { myEnableDisableButton = createEnableDisableButton( __ -> { List<IdeaPluginDescriptor> descriptors = List.of(myPlugin); if (myPluginModel.getState(myPlugin).isDisabled()) { myPluginModel.enable(descriptors); } else { myPluginModel.disable(descriptors); } } ); } myLayout.addButtonComponent(myEnableDisableButton); myEnableDisableButton.setOpaque(false); updateEnabledStateUI(); } } myLayout.addButtonComponent(myAlignButton = new JComponent() { @Override public Dimension getPreferredSize() { return myEnableDisableButton instanceof JCheckBox ? myEnableDisableButton.getPreferredSize() : super.getPreferredSize(); } }); myAlignButton.setOpaque(false); } } private static @NotNull JCheckBox createEnableDisableButton(@NotNull ActionListener listener) { return new JCheckBox() { private int myBaseline = -1; { addActionListener(listener); } @Override public int getBaseline(int width, int height) { if (myBaseline == -1) { JCheckBox checkBox = new JCheckBox("Foo", true); // NON-NLS Dimension size = checkBox.getPreferredSize(); myBaseline = checkBox.getBaseline(size.width, size.height) - JBUIScale.scale(1); } return myBaseline; } @Override public void setUI(ButtonUI ui) { myBaseline = -1; super.setUI(ui); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); return new Dimension( size.width + JBUIScale.scale(8), size.height + JBUIScale.scale(2) ); } }; } private void createMetricsPanel() { myMetricsPanel = new NonOpaquePanel(new TextHorizontalLayout(JBUIScale.scale(7))); myMetricsPanel.setBorder(JBUI.Borders.emptyTop(5)); myLayout.addLineComponent(myMetricsPanel); if (myMarketplace) { assert myPlugin instanceof PluginNode; PluginNode pluginNode = (PluginNode)myPlugin; String downloads = pluginNode.getPresentableDownloads(); if (downloads != null) { myDownloads = createRatingLabel(myMetricsPanel, downloads, AllIcons.Plugins.Downloads); } String rating = pluginNode.getPresentableRating(); if (rating != null) { myRating = createRatingLabel(myMetricsPanel, rating, AllIcons.Plugins.Rating); } } else { String version = myPlugin.isBundled() ? IdeBundle.message("plugin.status.bundled") : myPlugin.getVersion(); if (!StringUtil.isEmptyOrSpaces(version)) { myVersion = createRatingLabel(myMetricsPanel, version, null); } } String vendor = myPlugin.isBundled() ? null : StringUtil.trim(myPlugin.getVendor()); if (!StringUtil.isEmptyOrSpaces(vendor)) { myVendor = createRatingLabel(myMetricsPanel, TextHorizontalLayout.FIX_LABEL, vendor, null, null, true); } } private void createTag() { List<String> tags = PluginManagerConfigurable.getTags(myPlugin); if (!tags.isEmpty()) { TagComponent tagComponent = createTagComponent(tags.get(0)); myLayout.setTagComponent(PluginManagerConfigurable.setTinyFont(tagComponent)); } } private @NotNull TagComponent createTagComponent(@Nls @NotNull String tag) { TagComponent component = new TagComponent(tag); //noinspection unchecked component.setListener(mySearchListener, component); return component; } private void setTagTooltip(@Nullable @Nls String text) { if (myLayout.myTagComponent != null) { myLayout.myTagComponent.setToolTipText(text); } } private void createLicensePanel() { String productCode = myPlugin.getProductCode(); LicensingFacade instance = LicensingFacade.getInstance(); if (myMarketplace || productCode == null || instance == null || myPlugin.isBundled() || LicensePanel.isEA2Product(productCode)) { return; } LicensePanel licensePanel = new LicensePanel(true); String stamp = instance.getConfirmationStamp(productCode); if (stamp == null) { if (ApplicationManager.getApplication().isEAP() && !Boolean.getBoolean("eap.require.license")) { setTagTooltip(IdeBundle.message("label.text.plugin.eap.license.not.required")); return; } licensePanel.setText(IdeBundle.message("label.text.plugin.no.license"), true, false); } else { licensePanel.setTextFromStamp(stamp, instance.getExpirationDate(productCode)); } setTagTooltip(licensePanel.getMessage()); if (licensePanel.isNotification()) { licensePanel.setBorder(JBUI.Borders.emptyTop(3)); //licensePanel.setLink("Manage licenses", () -> { XXX }, false); myLayout.addLineComponent(licensePanel); myLicensePanel = licensePanel; } } public void setOnlyUpdateMode() { myOnlyUpdateMode = true; removeButtons(false); myLayout.setCheckBoxComponent(myChooseUpdateButton = new JCheckBox((String)null, true)); myChooseUpdateButton.setOpaque(false); IdeaPluginDescriptor descriptor = PluginManagerCore.getPlugin(myPlugin.getPluginId()); if (descriptor != null) { if (myDownloads != null) { myMetricsPanel.remove(myDownloads); } if (myRating != null) { myMetricsPanel.remove(myRating); } if (myVendor != null) { myMetricsPanel.remove(myVendor); } if (myVersion != null) { myMetricsPanel.remove(myVendor); } String version = NewUiUtil.getVersion(descriptor, myPlugin); String size = myPlugin instanceof PluginNode ? ((PluginNode)myPlugin).getPresentableSize() : null; myVersion = createRatingLabel(myMetricsPanel, null, size != null ? version + " | " + size : version, null, null, false); } updateColors(EventHandler.SelectionType.NONE); } public JCheckBox getChooseUpdateButton() { return myChooseUpdateButton; } public void setUpdateDescriptor(@Nullable IdeaPluginDescriptor descriptor) { if (myUpdateDescriptor == null && descriptor == null) { return; } if (myIndicator != null || isRestartEnabled()) { return; } myUpdateDescriptor = descriptor; if (descriptor == null) { if (myVersion != null) { myVersion.setText(myPlugin.getVersion()); } if (myUpdateLicensePanel != null) { myLayout.removeLineComponent(myUpdateLicensePanel); myUpdateLicensePanel = null; } if (myUpdateButton != null) { myUpdateButton.setVisible(false); } if (myAlignButton != null) { myAlignButton.setVisible(false); } } else { if (myVersion != null) { myVersion.setText(NewUiUtil.getVersion(myPlugin, descriptor)); } if (myPlugin.getProductCode() == null && descriptor.getProductCode() != null && !myPlugin.isBundled() && !LicensePanel.isEA2Product(descriptor.getProductCode())) { if (myUpdateLicensePanel == null) { myLayout.addLineComponent(myUpdateLicensePanel = new LicensePanel(true)); myUpdateLicensePanel.setBorder(JBUI.Borders.emptyTop(3)); myUpdateLicensePanel.setVisible(myErrorPanel == null); if (myEventHandler != null) { myEventHandler.addAll(myUpdateLicensePanel); } } myUpdateLicensePanel .setText(IdeBundle.message("label.next.plugin.version.is.paid.use.the.trial.for.up.to.30.days.or"), true, false); myUpdateLicensePanel.showBuyPlugin(() -> myUpdateDescriptor); myUpdateLicensePanel.setVisible(true); } if (myUpdateButton == null) { myLayout.addButtonComponent(myUpdateButton = new UpdateButton(), 0); myUpdateButton.addActionListener( e -> myPluginModel.installOrUpdatePlugin(this, myPlugin, myUpdateDescriptor, ModalityState.stateForComponent(myUpdateButton))); } else { myUpdateButton.setEnabled(true); myUpdateButton.setVisible(true); } if (myAlignButton != null) { myAlignButton.setVisible(myEnableDisableButton != null && !myEnableDisableButton.isVisible()); } } doLayout(); } public void setListeners(@NotNull EventHandler eventHandler) { myEventHandler = eventHandler; eventHandler.addAll(this); } void updateColors(@NotNull EventHandler.SelectionType type) { updateColors(GRAY_COLOR, type == EventHandler.SelectionType.NONE ? PluginManagerConfigurable.MAIN_BG_COLOR : (type == EventHandler.SelectionType.HOVER ? HOVER_COLOR : SELECTION_COLOR)); } private void updateColors(@NotNull Color grayedFg, @NotNull Color background) { setBackground(background); Color nameForeground = null; Color otherForeground = grayedFg; boolean calcColor = true; if (mySelection != EventHandler.SelectionType.NONE) { Color color = UIManager.getColor("Plugins.selectionForeground"); if (color != null) { nameForeground = otherForeground = color; calcColor = false; } } if (calcColor && !myIsAllowed) { calcColor = false; nameForeground = otherForeground = DisabledColor; } if (calcColor && !myMarketplace) { boolean disabled = myPluginModel.isUninstalled(myPlugin) || !MyPluginModel.isInstallingOrUpdate(myPlugin) && !isEnabledState(); if (disabled) { nameForeground = otherForeground = DisabledColor; } } myNameComponent.setHorizontalTextPosition(SwingConstants.LEFT); myNameComponent.setForeground(nameForeground); if (myRating != null) { myRating.setForeground(otherForeground); } if (myDownloads != null) { myDownloads.setForeground(otherForeground); } if (myVersion != null) { myVersion.setForeground(otherForeground); } if (myVendor != null) { myVendor.setForeground(otherForeground); } } public void updateErrors() { List<? extends HtmlChunk> errors = myOnlyUpdateMode ? List.of() : myPluginModel.getErrors(myPlugin); boolean hasErrors = !errors.isEmpty(); updateIcon(hasErrors, myPluginModel.isUninstalled(myPlugin) || !isEnabledState() || !myIsAllowed); if (myAlignButton != null) { myAlignButton.setVisible(myRestartButton != null); } if (hasErrors) { boolean addListeners = myErrorComponent == null && myEventHandler != null; if (myErrorPanel == null) { myErrorPanel = new NonOpaquePanel(); myLayout.addLineComponent(myErrorPanel); } if (myErrorComponent == null) { myErrorComponent = new ErrorComponent(); myErrorComponent.setBorder(JBUI.Borders.emptyTop(5)); myErrorPanel.add(myErrorComponent, BorderLayout.CENTER); } myErrorComponent.setErrors(errors, () -> myPluginModel.enableRequiredPlugins(myPlugin)); if (addListeners) { myEventHandler.addAll(myErrorPanel); } } else if (myErrorPanel != null) { myLayout.removeLineComponent(myErrorPanel); myErrorPanel = null; myErrorComponent = null; } if (myLicensePanel != null) { myLicensePanel.setVisible(!hasErrors); } if (myUpdateLicensePanel != null) { myUpdateLicensePanel.setVisible(!hasErrors); } } private void updateIcon(boolean errors, boolean disabled) { myIconComponent.setIcon(myPluginModel.getIcon(myPlugin, false, errors, disabled)); } public void showProgress() { showProgress(true); } private void showProgress(boolean repaint) { myIndicator = new OneLineProgressIndicator(false); myIndicator.setCancelRunnable(() -> myPluginModel.finishInstall(myPlugin, null, false, false, true)); myLayout.setProgressComponent(myIndicator.createBaselineWrapper()); MyPluginModel.addProgress(myPlugin, myIndicator); if (repaint) { fullRepaint(); } } public void hideProgress(boolean success, boolean restartRequired) { myIndicator = null; myLayout.removeProgressComponent(); if (success) { if (restartRequired) { enableRestart(); } else if (myInstallButton != null) { myInstallButton.setEnabled(false, IdeBundle.message("plugin.status.installed")); } else if (myUpdateButton != null) { myUpdateButton.setEnabled(false); myUpdateButton.setText(IdeBundle.message("plugin.status.installed")); } } fullRepaint(); } public void clearProgress() { myIndicator = null; } public void enableRestart() { removeButtons(true); } private void removeButtons(boolean showRestart) { if (myInstallButton != null) { myLayout.removeButtonComponent(myInstallButton); myInstallButton = null; } if (myUpdateButton != null) { myLayout.removeButtonComponent(myUpdateButton); myUpdateButton = null; } if (myEnableDisableButton != null) { myLayout.removeButtonComponent(myEnableDisableButton); myEnableDisableButton = null; } if (myIsAllowed && showRestart && myRestartButton == null) { myLayout.addButtonComponent(myRestartButton = new RestartButton(myPluginModel), 0); } if (myAlignButton != null) { myAlignButton.setVisible(true); } } public void updateEnabledState() { if (!myPluginModel.isUninstalled(myPlugin)) { updateEnabledStateUI(); } updateErrors(); setSelection(mySelection, false); } private void updateEnabledStateUI() { ProjectDependentPluginEnabledState state = myPluginModel.getProjectDependentState(myPlugin); if (myEnableDisableButton instanceof JCheckBox) { ((JCheckBox)myEnableDisableButton).setSelected(state.isEnabled()); } myNameComponent.setIcon(state.getIcon()); } public void updateAfterUninstall(boolean needRestartForUninstall) { myPluginModel.addUninstalled(myPlugin); updateColors(mySelection); removeButtons(needRestartForUninstall); } public void updatePlugin() { if (!myMarketplace && myUpdateButton != null && myUpdateButton.isVisible() && myUpdateButton.isEnabled()) { myUpdateButton.doClick(); } } private boolean isEnabledState() { return myPluginModel.isEnabled(myPlugin); } public boolean isMarketplace() { return myMarketplace; } public boolean isRestartEnabled() { return myRestartButton != null && myRestartButton.isVisible(); } public boolean isUpdatedWithoutRestart() { return myUpdateButton != null && myUpdateButton.isVisible() && !myUpdateButton.isEnabled(); } public boolean underProgress() { return myIndicator != null; } public void close() { if (myIndicator != null) { MyPluginModel.removeProgress(myPlugin, myIndicator); myIndicator = null; } myPluginModel.removeComponent(this); } public void createPopupMenu(@NotNull DefaultActionGroup group, @NotNull List<? extends ListPluginComponent> selection) { if (!myIsAllowed) { return; } if (myOnlyUpdateMode) { return; } for (ListPluginComponent component : selection) { if (MyPluginModel.isInstallingOrUpdate(component.myPlugin)) { return; } } boolean restart = true; for (ListPluginComponent component : selection) { if (component.myRestartButton == null) { restart = false; break; } } if (restart) { group.add(new ButtonAnAction(selection.get(0).myRestartButton)); return; } int size = selection.size(); if (myMarketplace) { JButton[] installButtons = new JButton[size]; for (int i = 0; i < size; i++) { JButton button = selection.get(i).myInstallButton; if (button == null || !button.isVisible() || !button.isEnabled()) { return; } installButtons[i] = button; } group.add(new ButtonAnAction(installButtons)); return; } JButton[] updateButtons = new JButton[size]; for (int i = 0; i < size; i++) { JButton button = selection.get(i).myUpdateButton; if (button == null || !button.isVisible() || !button.isEnabled()) { updateButtons = null; break; } updateButtons[i] = button; } if (updateButtons != null) { group.add(new ButtonAnAction(updateButtons)); if (size > 1) { return; } } SelectionBasedPluginModelAction.addActionsTo(group, action -> createEnableDisableAction(action, selection), () -> createUninstallAction(selection)); } public void handleKeyAction(@NotNull KeyEvent event, @NotNull List<? extends ListPluginComponent> selection) { if (myOnlyUpdateMode) { if (event.getKeyCode() == KeyEvent.VK_SPACE) { for (ListPluginComponent component : selection) { component.myChooseUpdateButton.doClick(); } } return; } for (ListPluginComponent component : selection) { if (MyPluginModel.isInstallingOrUpdate(component.myPlugin)) { return; } } boolean restart = true; for (ListPluginComponent component : selection) { if (component.myRestartButton == null) { restart = false; break; } } int keyCode = event.getKeyCode(); if (myMarketplace) { if (keyCode == KeyEvent.VK_ENTER) { if (restart) { selection.get(0).myRestartButton.doClick(); } for (ListPluginComponent component : selection) { JButton button = component.myInstallButton; if (button == null || !button.isVisible() || !button.isEnabled()) { return; } } for (ListPluginComponent component : selection) { component.myInstallButton.doClick(); } } return; } boolean update = true; for (ListPluginComponent component : selection) { JButton button = component.myUpdateButton; if (button == null || !button.isVisible() || !button.isEnabled()) { update = false; break; } } if (keyCode == KeyEvent.VK_ENTER) { if (restart) { selection.get(0).myRestartButton.doClick(); } else if (update) { for (ListPluginComponent component : selection) { component.myUpdateButton.doClick(); } } } else if (!restart && !update) { DumbAwareAction action = keyCode == KeyEvent.VK_SPACE && event.getModifiersEx() == 0 ? createEnableDisableAction(getEnableDisableAction(selection), selection) : keyCode == EventHandler.DELETE_CODE ? createUninstallAction(selection) : null; if (action != null) { ActionManager.getInstance().tryToExecute(action, event, this, ActionPlaces.UNKNOWN, true); } } } private void fullRepaint() { Container parent = getParent(); parent.doLayout(); parent.revalidate(); parent.repaint(); } public @NotNull IdeaPluginDescriptor getPluginDescriptor() { return myPlugin; } public void setPluginDescriptor(@NotNull IdeaPluginDescriptor plugin) { myPlugin = plugin; } private @NotNull PluginEnableDisableAction getEnableDisableAction(@NotNull List<? extends ListPluginComponent> selection) { Iterator<? extends ListPluginComponent> iterator = selection.iterator(); BooleanSupplier isGloballyEnabledGenerator = () -> myPluginModel.getState(iterator.next().getPluginDescriptor()) == PluginEnabledState.ENABLED; boolean firstDisabled = !isGloballyEnabledGenerator.getAsBoolean(); while (iterator.hasNext()) { if (firstDisabled == isGloballyEnabledGenerator.getAsBoolean()) { return PluginEnableDisableAction.ENABLE_GLOBALLY; } } return PluginEnableDisableAction.globally(firstDisabled); } private @NotNull SelectionBasedPluginModelAction.EnableDisableAction<ListPluginComponent> createEnableDisableAction(@NotNull PluginEnableDisableAction action, @NotNull List<? extends ListPluginComponent> selection) { return new SelectionBasedPluginModelAction.EnableDisableAction<>(myPluginModel, action, true, selection, ListPluginComponent::getPluginDescriptor); } private @NotNull SelectionBasedPluginModelAction.UninstallAction<ListPluginComponent> createUninstallAction(@NotNull List<? extends ListPluginComponent> selection) { return new SelectionBasedPluginModelAction.UninstallAction<>(myPluginModel, true, this, selection, ListPluginComponent::getPluginDescriptor); } @NotNull static JLabel createRatingLabel(@NotNull JPanel panel, @NotNull @Nls String text, @Nullable Icon icon) { return createRatingLabel(panel, null, text, icon, null, true); } @NotNull static JLabel createRatingLabel(@NotNull JPanel panel, @Nullable Object constraints, @NotNull @Nls String text, @Nullable Icon icon, @Nullable Color color, boolean tiny) { JLabel label = new JLabel(text, icon, SwingConstants.CENTER); label.setOpaque(false); label.setIconTextGap(2); if (color != null) { label.setForeground(color); } panel.add(tiny ? PluginManagerConfigurable.setTinyFont(label) : label, constraints); return label; } public static class ButtonAnAction extends DumbAwareAction { private final JButton[] myButtons; ButtonAnAction(JButton @NotNull ... buttons) { super(buttons[0].getText()); //NON-NLS myButtons = buttons; setShortcutSet(CommonShortcuts.ENTER); } @Override public void actionPerformed(@NotNull AnActionEvent e) { for (JButton button : myButtons) { button.doClick(); } } } private class BaselineLayout extends AbstractLayoutManager { private final JBValue myHGap = new JBValue.Float(10); private final JBValue myHOffset = new JBValue.Float(8); private final JBValue myButtonOffset = new JBValue.Float(6); private JComponent myIconComponent; private JLabel myNameComponent; private JComponent myProgressComponent; private JComponent myTagComponent; private JComponent myCheckBoxComponent; private final List<JComponent> myButtonComponents = new ArrayList<>(); private final List<JComponent> myLineComponents = new ArrayList<>(); private boolean[] myButtonEnableStates; @Override public Dimension preferredLayoutSize(Container parent) { Dimension result = new Dimension(myNameComponent.getPreferredSize()); if (myProgressComponent == null) { if (myCheckBoxComponent != null) { Dimension size = myCheckBoxComponent.getPreferredSize(); result.width += size.width + myHOffset.get(); result.height = Math.max(result.height, size.height); } if (myTagComponent != null) { Dimension size = myTagComponent.getPreferredSize(); result.width += size.width + 2 * myHOffset.get(); result.height = Math.max(result.height, size.height); } int count = myButtonComponents.size(); if (count > 0) { int visibleCount = 0; for (Component component : myButtonComponents) { if (component.isVisible()) { Dimension size = component.getPreferredSize(); result.width += size.width; result.height = Math.max(result.height, size.height); visibleCount++; } } if (visibleCount > 0) { result.width += myHOffset.get(); result.width += (visibleCount - 1) * myButtonOffset.get(); } } } else { Dimension size = myProgressComponent.getPreferredSize(); result.width += myHOffset.get() + size.width; result.height = Math.max(result.height, size.height); } for (JComponent component : myLineComponents) { if (component.isVisible()) { Dimension size = component.getPreferredSize(); result.width = Math.max(result.width, size.width); result.height += size.height; } } Dimension iconSize = myIconComponent.getPreferredSize(); result.width += iconSize.width + myHGap.get(); result.height = Math.max(result.height, iconSize.height); JBInsets.addTo(result, getInsets()); return result; } @Override public void layoutContainer(Container parent) { Insets insets = getInsets(); int x = insets.left; int y = insets.top; if (myProgressComponent == null && myCheckBoxComponent != null) { Dimension size = myCheckBoxComponent.getPreferredSize(); myCheckBoxComponent.setBounds(x, (parent.getHeight() - size.height) / 2, size.width, size.height); x += size.width + myHGap.get(); } Dimension iconSize = myIconComponent.getPreferredSize(); myIconComponent.setBounds(x, y, iconSize.width, iconSize.height); x += iconSize.width + myHGap.get(); y += JBUIScale.scale(2); int calcNameWidth = calculateNameWidth(); Dimension nameSize = myNameComponent.getPreferredSize(); int baseline = y + myNameComponent.getBaseline(nameSize.width, nameSize.height); myNameComponent.setToolTipText(calcNameWidth < nameSize.width ? myNameComponent.getText() : null); nameSize.width = Math.min(nameSize.width, calcNameWidth); myNameComponent.setBounds(x, y, nameSize.width, nameSize.height); y += nameSize.height; int width = getWidth(); if (myProgressComponent == null) { if (myTagComponent != null) { setBaselineBounds(x + nameSize.width + myHOffset.get(), baseline, myTagComponent, myTagComponent.getPreferredSize()); } int lastX = width - insets.right; for (int i = myButtonComponents.size() - 1; i >= 0; i--) { Component component = myButtonComponents.get(i); if (!component.isVisible()) { continue; } Dimension size = component.getPreferredSize(); lastX -= size.width; setBaselineBounds(lastX, baseline, component, size); lastX -= myButtonOffset.get(); } } else { Dimension size = myProgressComponent.getPreferredSize(); setBaselineBounds(width - size.width - insets.right, baseline, myProgressComponent, size); } int lineWidth = width - x - insets.right; for (JComponent component : myLineComponents) { if (component.isVisible()) { int lineHeight = component.getPreferredSize().height; component.setBounds(x, y, lineWidth, lineHeight); y += lineHeight; } } } private int calculateNameWidth() { Insets insets = getInsets(); int width = getWidth() - insets.left - insets.right - myIconComponent.getPreferredSize().width - myHGap.get(); if (myProgressComponent != null) { return width - myProgressComponent.getPreferredSize().width - myHOffset.get(); } if (myCheckBoxComponent != null) { width -= myCheckBoxComponent.getPreferredSize().width + myHOffset.get(); } if (myTagComponent != null) { width -= myTagComponent.getPreferredSize().width + 2 * myHOffset.get(); } int visibleCount = 0; for (Component component : myButtonComponents) { if (component.isVisible()) { width -= component.getPreferredSize().width; visibleCount++; } } width -= myButtonOffset.get() * (visibleCount - 1); if (visibleCount > 0) { width -= myHOffset.get(); } return width; } private void setBaselineBounds(int x, int y, @NotNull Component component, @NotNull Dimension size) { if (component instanceof ActionToolbar) { component.setBounds(x, getInsets().top - JBUI.scale(1), size.width, size.height); } else { component.setBounds(x, y - component.getBaseline(size.width, size.height), size.width, size.height); } } public void setIconComponent(@NotNull JComponent iconComponent) { assert myIconComponent == null; myIconComponent = iconComponent; add(iconComponent); } public void setNameComponent(@NotNull JLabel nameComponent) { assert myNameComponent == null; add(myNameComponent = nameComponent); } public void setTagComponent(@NotNull JComponent component) { assert myTagComponent == null; add(myTagComponent = component); } public void addLineComponent(@NotNull JComponent component) { myLineComponents.add(component); add(component); } public void removeLineComponent(@NotNull JComponent component) { myLineComponents.remove(component); remove(component); } public void addButtonComponent(@NotNull JComponent component) { addButtonComponent(component, -1); } public void addButtonComponent(@NotNull JComponent component, int index) { if (myButtonComponents.isEmpty() || index == -1) { myButtonComponents.add(component); } else { myButtonComponents.add(index, component); } add(component); updateVisibleOther(); } public void removeButtonComponent(@NotNull JComponent component) { myButtonComponents.remove(component); remove(component); updateVisibleOther(); } public void setCheckBoxComponent(@NotNull JComponent checkBoxComponent) { assert myCheckBoxComponent == null; myCheckBoxComponent = checkBoxComponent; add(checkBoxComponent); doLayout(); } public void setProgressComponent(@NotNull JComponent progressComponent) { assert myProgressComponent == null; myProgressComponent = progressComponent; add(progressComponent); if (myEventHandler != null) { myEventHandler.addAll(progressComponent); myEventHandler.updateHover(ListPluginComponent.this); } setVisibleOther(false); doLayout(); } public void removeProgressComponent() { if (myProgressComponent == null) { return; } remove(myProgressComponent); myProgressComponent = null; setVisibleOther(true); doLayout(); } private void updateVisibleOther() { if (myProgressComponent != null) { myButtonEnableStates = null; setVisibleOther(false); } } private void setVisibleOther(boolean value) { if (myTagComponent != null) { myTagComponent.setVisible(value); } if (myButtonComponents.isEmpty()) { return; } if (value) { assert myButtonEnableStates != null && myButtonEnableStates.length == myButtonComponents.size(); for (int i = 0, size = myButtonComponents.size(); i < size; i++) { myButtonComponents.get(i).setVisible(myButtonEnableStates[i]); } myButtonEnableStates = null; } else { assert myButtonEnableStates == null; myButtonEnableStates = new boolean[myButtonComponents.size()]; for (int i = 0, size = myButtonComponents.size(); i < size; i++) { Component component = myButtonComponents.get(i); myButtonEnableStates[i] = component.isVisible(); component.setVisible(false); } } } } }
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/newui/ListPluginComponent.java
Java
apache-2.0
42,623
package ch.iec._61400.ews._1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="LDRef" type="{http://iec.ch/61400/ews/1.0/}tLogicalDeviceReference"/> * &lt;/sequence> * &lt;attribute name="UUID" type="{http://iec.ch/61400/ews/1.0/}tstring36" /> * &lt;attribute name="AssocID" use="required" type="{http://iec.ch/61400/ews/1.0/}tAssocID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ldRef" }) @XmlRootElement(name = "GetLogicalDeviceDirectoryRequest") public class GetLogicalDeviceDirectoryRequest { @XmlElement(name = "LDRef", required = true) protected String ldRef; @XmlAttribute(name = "UUID") protected String uuid; @XmlAttribute(name = "AssocID", required = true) protected String assocID; /** * Gets the value of the ldRef property. * * @return * possible object is * {@link String } * */ public String getLDRef() { return ldRef; } /** * Sets the value of the ldRef property. * * @param value * allowed object is * {@link String } * */ public void setLDRef(String value) { this.ldRef = value; } /** * Gets the value of the uuid property. * * @return * possible object is * {@link String } * */ public String getUUID() { return uuid; } /** * Sets the value of the uuid property. * * @param value * allowed object is * {@link String } * */ public void setUUID(String value) { this.uuid = value; } /** * Gets the value of the assocID property. * * @return * possible object is * {@link String } * */ public String getAssocID() { return assocID; } /** * Sets the value of the assocID property. * * @param value * allowed object is * {@link String } * */ public void setAssocID(String value) { this.assocID = value; } }
B2M-Software/project-drahtlos-smg20
actuatorclient.siemens.impl/src/main/java/ch/iec/_61400/ews/_1/GetLogicalDeviceDirectoryRequest.java
Java
apache-2.0
2,784
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.jsonSchema.impl; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.diagnostic.PluginException; import com.intellij.ide.lightEdit.LightEdit; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.ClearableLazyValue; import com.intellij.openapi.util.ModificationTracker; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.impl.http.HttpVirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBusConnection; import com.jetbrains.jsonSchema.JsonPointerUtil; import com.jetbrains.jsonSchema.JsonSchemaCatalogEntry; import com.jetbrains.jsonSchema.JsonSchemaCatalogProjectConfiguration; import com.jetbrains.jsonSchema.JsonSchemaVfsListener; import com.jetbrains.jsonSchema.extension.*; import com.jetbrains.jsonSchema.ide.JsonSchemaService; import com.jetbrains.jsonSchema.remote.JsonFileResolver; import com.jetbrains.jsonSchema.remote.JsonSchemaCatalogExclusion; import com.jetbrains.jsonSchema.remote.JsonSchemaCatalogManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Supplier; public class JsonSchemaServiceImpl implements JsonSchemaService, ModificationTracker, Disposable { private static final Logger LOG = Logger.getInstance(JsonSchemaServiceImpl.class); @NotNull private final Project myProject; @NotNull private final MyState myState; @NotNull private final ClearableLazyValue<Set<String>> myBuiltInSchemaIds; @NotNull private final Set<String> myRefs = ContainerUtil.newConcurrentSet(); private final AtomicLong myAnyChangeCount = new AtomicLong(0); @NotNull private final JsonSchemaCatalogManager myCatalogManager; private final JsonSchemaProviderFactories myFactories; public JsonSchemaServiceImpl(@NotNull Project project) { myProject = project; myFactories = new JsonSchemaProviderFactories(); myState = new MyState(() -> myFactories.getProviders(), myProject); myBuiltInSchemaIds = new ClearableLazyValue<>() { @NotNull @Override protected Set<String> compute() { return ContainerUtil.map2SetNotNull(myState.getFiles(), f -> JsonCachedValues.getSchemaId(f, myProject)); } }; JsonSchemaProviderFactory.EP_NAME.addChangeListener(this::reset, this); JsonSchemaEnabler.EXTENSION_POINT_NAME.addChangeListener(this::reset, this); JsonSchemaCatalogExclusion.EP_NAME.addChangeListener(this::reset, this); myCatalogManager = new JsonSchemaCatalogManager(myProject); MessageBusConnection connection = project.getMessageBus().connect(this); connection.subscribe(JsonSchemaVfsListener.JSON_SCHEMA_CHANGED, myAnyChangeCount::incrementAndGet); connection.subscribe(JsonSchemaVfsListener.JSON_DEPS_CHANGED, () -> { myRefs.clear(); myAnyChangeCount.incrementAndGet(); }); JsonSchemaVfsListener.startListening(project, this, connection); myCatalogManager.startUpdates(); } @Override public long getModificationCount() { return myAnyChangeCount.get(); } @Override public void dispose() { } @NotNull protected List<JsonSchemaProviderFactory> getProviderFactories() { return JsonSchemaProviderFactory.EP_NAME.getExtensionList(); } @Nullable @Override public JsonSchemaFileProvider getSchemaProvider(@NotNull VirtualFile schemaFile) { return myState.getProvider(schemaFile); } @Nullable @Override public JsonSchemaFileProvider getSchemaProvider(@NotNull JsonSchemaObject schemaObject) { VirtualFile file = resolveSchemaFile(schemaObject); return file == null ? null : getSchemaProvider(file); } @Override public void reset() { myFactories.reset(); resetWithCurrentFactories(); } private void resetWithCurrentFactories() { myState.reset(); myBuiltInSchemaIds.drop(); myAnyChangeCount.incrementAndGet(); for (Runnable action: myResetActions) { action.run(); } DaemonCodeAnalyzer.getInstance(myProject).restart(); } @Override @NotNull public Project getProject() { return myProject; } @Override @Nullable public VirtualFile findSchemaFileByReference(@NotNull String reference, @Nullable VirtualFile referent) { final VirtualFile file = findBuiltInSchemaByReference(reference); if (file != null) return file; if (reference.startsWith("#")) return referent; return JsonFileResolver.resolveSchemaByReference(referent, JsonPointerUtil.normalizeId(reference)); } @Nullable private VirtualFile findBuiltInSchemaByReference(@NotNull String reference) { String id = JsonPointerUtil.normalizeId(reference); if (!myBuiltInSchemaIds.getValue().contains(id)) return null; for (VirtualFile file : myState.getFiles()) { if (id.equals(JsonCachedValues.getSchemaId(file, myProject))) { return file; } } return null; } @Override @NotNull public Collection<VirtualFile> getSchemaFilesForFile(@NotNull final VirtualFile file) { return getSchemasForFile(file, false, false); } @NotNull public Collection<VirtualFile> getSchemasForFile(@NotNull VirtualFile file, boolean single, boolean onlyUserSchemas) { String schemaUrl = null; if (!onlyUserSchemas) { // prefer schema-schema if it is specified in "$schema" property schemaUrl = JsonCachedValues.getSchemaUrlFromSchemaProperty(file, myProject); if (JsonFileResolver.isSchemaUrl(schemaUrl)) { final VirtualFile virtualFile = resolveFromSchemaProperty(schemaUrl, file); if (virtualFile != null) return Collections.singletonList(virtualFile); } } List<JsonSchemaFileProvider> providers = getProvidersForFile(file); // proper priority: // 1) user providers // 2) $schema property // 3) built-in providers // 4) schema catalog boolean checkSchemaProperty = true; if (!onlyUserSchemas && providers.stream().noneMatch(p -> p.getSchemaType() == SchemaType.userSchema)) { if (schemaUrl == null) schemaUrl = JsonCachedValues.getSchemaUrlFromSchemaProperty(file, myProject); VirtualFile virtualFile = resolveFromSchemaProperty(schemaUrl, file); if (virtualFile != null) return Collections.singletonList(virtualFile); checkSchemaProperty = false; } if (!single) { List<VirtualFile> files = new ArrayList<>(); for (JsonSchemaFileProvider provider : providers) { VirtualFile schemaFile = getSchemaForProvider(myProject, provider); if (schemaFile != null) { files.add(schemaFile); } } if (!files.isEmpty()) { return files; } } else if (!providers.isEmpty()) { final JsonSchemaFileProvider selected; if (providers.size() > 2) return ContainerUtil.emptyList(); if (providers.size() > 1) { final Optional<JsonSchemaFileProvider> userSchema = providers.stream().filter(provider -> SchemaType.userSchema.equals(provider.getSchemaType())).findFirst(); if (userSchema.isEmpty()) return ContainerUtil.emptyList(); selected = userSchema.get(); } else selected = providers.get(0); VirtualFile schemaFile = getSchemaForProvider(myProject, selected); return ContainerUtil.createMaybeSingletonList(schemaFile); } if (onlyUserSchemas) { return ContainerUtil.emptyList(); } if (checkSchemaProperty) { if (schemaUrl == null) schemaUrl = JsonCachedValues.getSchemaUrlFromSchemaProperty(file, myProject); VirtualFile virtualFile = resolveFromSchemaProperty(schemaUrl, file); if (virtualFile != null) return Collections.singletonList(virtualFile); } return ContainerUtil.createMaybeSingletonList(resolveSchemaFromOtherSources(file)); } @NotNull public List<JsonSchemaFileProvider> getProvidersForFile(@NotNull VirtualFile file) { Map<VirtualFile, List<JsonSchemaFileProvider>> map = myState.myData.getValue(); if (map.isEmpty()) { return Collections.emptyList(); } List<JsonSchemaFileProvider> result = null; for (List<JsonSchemaFileProvider> providers : map.values()) { for (JsonSchemaFileProvider provider : providers) { if (isProviderAvailable(file, provider)) { if (result == null) { result = new SmartList<>(); } result.add(provider); } } } return result == null ? Collections.emptyList() : result; } @Nullable private VirtualFile resolveFromSchemaProperty(@Nullable String schemaUrl, @NotNull VirtualFile file) { if (schemaUrl != null) { VirtualFile virtualFile = findSchemaFileByReference(schemaUrl, file); if (virtualFile != null) return virtualFile; } return null; } @Override public List<JsonSchemaInfo> getAllUserVisibleSchemas() { List<JsonSchemaCatalogEntry> schemas = myCatalogManager.getAllCatalogEntries(); Map<VirtualFile, List<JsonSchemaFileProvider>> map = myState.myData.getValue(); List<JsonSchemaInfo> results = new ArrayList<>(schemas.size() + map.size()); Map<String, JsonSchemaInfo> processedRemotes = new HashMap<>(); myState.processProviders(provider -> { if (provider.isUserVisible()) { final String remoteSource = provider.getRemoteSource(); if (remoteSource != null) { if (!processedRemotes.containsKey(remoteSource)) { JsonSchemaInfo info = new JsonSchemaInfo(provider); processedRemotes.put(remoteSource, info); results.add(info); } } else { results.add(new JsonSchemaInfo(provider)); } } }); for (JsonSchemaCatalogEntry schema: schemas) { final String url = schema.getUrl(); if (!processedRemotes.containsKey(url)) { final JsonSchemaInfo info = new JsonSchemaInfo(url); if (schema.getDescription() != null) { info.setDocumentation(schema.getDescription()); } if (schema.getName() != null) { info.setName(schema.getName()); } results.add(info); } else { // use documentation from schema catalog for bundled schemas if possible // we don't have our own docs, so let's reuse the existing docs from the catalog JsonSchemaInfo info = processedRemotes.get(url); if (info.getDocumentation() == null) { info.setDocumentation(schema.getDescription()); } if (info.getName() == null) { info.setName(schema.getName()); } } } return results; } @Nullable @Override public JsonSchemaObject getSchemaObject(@NotNull final VirtualFile file) { Collection<VirtualFile> schemas = getSchemasForFile(file, true, false); if (schemas.size() == 0) return null; assert schemas.size() == 1; VirtualFile schemaFile = schemas.iterator().next(); return JsonCachedValues.getSchemaObject(replaceHttpFileWithBuiltinIfNeeded(schemaFile), myProject); } @Nullable @Override public JsonSchemaObject getSchemaObject(@NotNull PsiFile file) { return JsonCachedValues.computeSchemaForFile(file, this); } public VirtualFile replaceHttpFileWithBuiltinIfNeeded(VirtualFile schemaFile) { // this hack is needed to handle user-defined mappings via urls // we cannot perform that inside corresponding provider, because it leads to recursive component dependency // this way we're preventing http files when a built-in schema exists if (schemaFile instanceof HttpVirtualFile && (!JsonSchemaCatalogProjectConfiguration.getInstance(myProject).isPreferRemoteSchemas() || JsonFileResolver.isSchemaUrl(schemaFile.getUrl()))) { String url = schemaFile.getUrl(); VirtualFile first1 = getLocalSchemaByUrl(url); return first1 != null ? first1 : schemaFile; } return schemaFile; } @Nullable public VirtualFile getLocalSchemaByUrl(String url) { return myState.getFiles().stream() .filter(f -> { JsonSchemaFileProvider prov = getSchemaProvider(f); return prov != null && !(prov.getSchemaFile() instanceof HttpVirtualFile) && (url.equals(prov.getRemoteSource()) || JsonFileResolver.replaceUnsafeSchemaStoreUrls(url).equals(prov.getRemoteSource()) || url.equals(JsonFileResolver.replaceUnsafeSchemaStoreUrls(prov.getRemoteSource()))); }).findFirst().orElse(null); } @Nullable @Override public JsonSchemaObject getSchemaObjectForSchemaFile(@NotNull VirtualFile schemaFile) { return JsonCachedValues.getSchemaObject(schemaFile, myProject); } @Override public boolean isSchemaFile(@NotNull VirtualFile file) { return isMappedSchema(file) || isSchemaByProvider(file) || hasSchemaSchema(file); } @Override public boolean isSchemaFile(@NotNull JsonSchemaObject schemaObject) { VirtualFile file = resolveSchemaFile(schemaObject); return file != null && isSchemaFile(file); } private boolean isMappedSchema(@NotNull VirtualFile file) { return isMappedSchema(file, true); } public boolean isMappedSchema(@NotNull VirtualFile file, boolean canRecompute) { return (canRecompute || myState.isComputed()) && myState.getFiles().contains(file); } private boolean isSchemaByProvider(@NotNull VirtualFile file) { JsonSchemaFileProvider provider = myState.getProvider(file); if (provider != null) { return isSchemaProvider(provider); } Map<VirtualFile, List<JsonSchemaFileProvider>> map = myState.myData.getValue(); for (List<JsonSchemaFileProvider> providers : map.values()) { for (JsonSchemaFileProvider p : providers) { if (isSchemaProvider(p) && p.isAvailable(file)) { return true; } } } return false; } private static boolean isSchemaProvider(JsonSchemaFileProvider provider) { return JsonFileResolver.isSchemaUrl(provider.getRemoteSource()); } @Override public JsonSchemaVersion getSchemaVersion(@NotNull VirtualFile file) { if (isMappedSchema(file)) { JsonSchemaFileProvider provider = myState.getProvider(file); if (provider != null) { return provider.getSchemaVersion(); } } return getSchemaVersionFromSchemaUrl(file); } @Nullable private JsonSchemaVersion getSchemaVersionFromSchemaUrl(@NotNull VirtualFile file) { Ref<String> res = Ref.create(null); //noinspection CodeBlock2Expr ApplicationManager.getApplication().runReadAction(() -> { res.set(JsonCachedValues.getSchemaUrlFromSchemaProperty(file, myProject)); }); if (res.isNull()) return null; return JsonSchemaVersion.byId(res.get()); } private boolean hasSchemaSchema(VirtualFile file) { return getSchemaVersionFromSchemaUrl(file) != null; } private static boolean isProviderAvailable(@NotNull final VirtualFile file, @NotNull JsonSchemaFileProvider provider) { return provider.isAvailable(file); } @Nullable private VirtualFile resolveSchemaFromOtherSources(@NotNull VirtualFile file) { return myCatalogManager.getSchemaFileForFile(file); } @Override public void registerRemoteUpdateCallback(Runnable callback) { myCatalogManager.registerCatalogUpdateCallback(callback); } @Override public void unregisterRemoteUpdateCallback(Runnable callback) { myCatalogManager.unregisterCatalogUpdateCallback(callback); } private final List<Runnable> myResetActions = ContainerUtil.createConcurrentList(); @Override public void registerResetAction(Runnable action) { myResetActions.add(action); } @Override public void unregisterResetAction(Runnable action) { myResetActions.remove(action); } @Override public void registerReference(String ref) { int index = StringUtil.lastIndexOfAny(ref, "\\/"); if (index >= 0) { ref = ref.substring(index + 1); } myRefs.add(ref); } @Override public boolean possiblyHasReference(String ref) { return myRefs.contains(ref); } @Override public void triggerUpdateRemote() { myCatalogManager.triggerUpdateCatalog(myProject); } @Override public boolean isApplicableToFile(@Nullable VirtualFile file) { if (file == null) return false; for (JsonSchemaEnabler e : JsonSchemaEnabler.EXTENSION_POINT_NAME.getExtensionList()) { if (e.isEnabledForFile(file, myProject)) { return true; } } return false; } @Override public @NotNull JsonSchemaCatalogManager getCatalogManager() { return myCatalogManager; } private static final class MyState { @NotNull private final Supplier<List<JsonSchemaFileProvider>> myFactory; @NotNull private final Project myProject; @NotNull private final ClearableLazyValue<Map<VirtualFile, List<JsonSchemaFileProvider>>> myData; private final AtomicBoolean myIsComputed = new AtomicBoolean(false); private MyState(@NotNull final Supplier<List<JsonSchemaFileProvider>> factory, @NotNull Project project) { myFactory = factory; myProject = project; myData = new ClearableLazyValue<>() { @NotNull @Override public Map<VirtualFile, List<JsonSchemaFileProvider>> compute() { Map<VirtualFile, List<JsonSchemaFileProvider>> map = createFileProviderMap(myFactory.get(), myProject); myIsComputed.set(true); return map; } @NotNull @Override public synchronized Map<VirtualFile, List<JsonSchemaFileProvider>> getValue() { return super.getValue(); } @Override public synchronized void drop() { myIsComputed.set(false); super.drop(); } }; } public void reset() { myData.drop(); } public void processProviders(@NotNull Consumer<JsonSchemaFileProvider> consumer) { Map<VirtualFile, List<JsonSchemaFileProvider>> map = myData.getValue(); if (map.isEmpty()) { return; } for (List<JsonSchemaFileProvider> providers : map.values()) { providers.forEach(consumer); } } @NotNull public Set<VirtualFile> getFiles() { return myData.getValue().keySet(); } @Nullable public JsonSchemaFileProvider getProvider(@NotNull VirtualFile file) { List<JsonSchemaFileProvider> providers = myData.getValue().get(file); if (providers == null || providers.isEmpty()) { return null; } for (JsonSchemaFileProvider p : providers) { if (p.getSchemaType() == SchemaType.userSchema) { return p; } } return providers.get(0); } public boolean isComputed() { return myIsComputed.get(); } @NotNull private static Map<VirtualFile, List<JsonSchemaFileProvider>> createFileProviderMap(@NotNull List<JsonSchemaFileProvider> list, @NotNull Project project) { // if there are different providers with the same schema files, // stream API does not allow to collect same keys with Collectors.toMap(): throws duplicate key Map<VirtualFile, List<JsonSchemaFileProvider>> map = new HashMap<>(); for (JsonSchemaFileProvider provider : list) { VirtualFile schemaFile; try { schemaFile = getSchemaForProvider(project, provider); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { LOG.error(e); continue; } if (schemaFile != null) { map.computeIfAbsent(schemaFile, __ -> new SmartList<>()).add(provider); } } return map; } } @Nullable private static VirtualFile getSchemaForProvider(@NotNull Project project, @NotNull JsonSchemaFileProvider provider) { if (JsonSchemaCatalogProjectConfiguration.getInstance(project).isPreferRemoteSchemas()) { final String source = provider.getRemoteSource(); if (source != null && !source.endsWith("!") && !JsonFileResolver.isSchemaUrl(source)) { return VirtualFileManager.getInstance().findFileByUrl(source); } } return provider.getSchemaFile(); } @Nullable @Override public VirtualFile resolveSchemaFile(@NotNull JsonSchemaObject schemaObject) { VirtualFile rawFile = schemaObject.getRawFile(); if (rawFile != null) { return rawFile; } String fileUrl = schemaObject.getFileUrl(); if (fileUrl == null) { return null; } return VirtualFileManager.getInstance().findFileByUrl(fileUrl); } private class JsonSchemaProviderFactories { private volatile List<JsonSchemaFileProvider> myProviders; public @NotNull List<JsonSchemaFileProvider> getProviders() { List<JsonSchemaFileProvider> providers = myProviders; if (providers == null) { providers = getDumbAwareProvidersAndUpdateRestWhenSmart(); myProviders = providers; } return providers; } public void reset() { myProviders = null; } private @NotNull List<JsonSchemaFileProvider> getDumbAwareProvidersAndUpdateRestWhenSmart() { List<JsonSchemaProviderFactory> readyFactories = new ArrayList<>(); List<JsonSchemaProviderFactory> notReadyFactories = new ArrayList<>(); boolean dumb = DumbService.getInstance(myProject).isDumb(); for (JsonSchemaProviderFactory factory : getProviderFactories()) { if (!dumb || DumbService.isDumbAware(factory)) { readyFactories.add(factory); } else { notReadyFactories.add(factory); } } List<JsonSchemaFileProvider> providers = getProvidersFromFactories(readyFactories); myProviders = providers; if (!notReadyFactories.isEmpty() && !LightEdit.owns(myProject)) { DumbService.getInstance(myProject).runWhenSmart(() -> { ApplicationManager.getApplication().executeOnPooledThread(() -> ReadAction.run(() -> { if (myProviders == providers) { List<JsonSchemaFileProvider> newProviders = getProvidersFromFactories(notReadyFactories); if (!newProviders.isEmpty()) { List<JsonSchemaFileProvider> oldProviders = myProviders; myProviders = ContainerUtil.concat(oldProviders, newProviders); JsonSchemaServiceImpl.this.resetWithCurrentFactories(); } } })); }); } return providers; } private @NotNull List<JsonSchemaFileProvider> getProvidersFromFactories(@NotNull List<JsonSchemaProviderFactory> factories) { List<JsonSchemaFileProvider> providers = new ArrayList<>(); for (JsonSchemaProviderFactory factory : factories) { try { providers.addAll(factory.getProviders(myProject)); } catch (ProcessCanceledException e) { throw e; } catch (Exception e) { PluginException.logPluginError(Logger.getInstance(JsonSchemaService.class), e.toString(), e, factory.getClass()); } } return providers; } } }
GunoH/intellij-community
json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java
Java
apache-2.0
24,109
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.rest.action.cat; import org.elasticsearch.client.Client; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.rest.*; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; public class RestCatAction extends BaseRestHandler { private static final String CAT = "=^.^=\n"; @Inject public RestCatAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_cat", this); } @Override public void handleRequest(final RestRequest request, final RestChannel channel) { try { channel.sendResponse(new StringRestResponse(RestStatus.OK, CAT)); } catch (Throwable t) { try { channel.sendResponse(new XContentThrowableRestResponse(request, t)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } } }
andrewvc/elasticsearch
src/main/java/org/elasticsearch/rest/action/cat/RestCatAction.java
Java
apache-2.0
1,881
package com.tngtech.test.java.junit.dataprovider.custom; import static org.assertj.core.api.Assertions.assertThat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.Test; import org.junit.runner.RunWith; import com.tngtech.java.junit.dataprovider.DataProvider; @RunWith(CustomDataProviderRunner.class) public class DataProviderCustomStringConverterAcceptanceTest { // @formatter:off @Test @DataProvider(value = { "2016-02-19 | 2016 | 02 | 19 | 00 | 00 | 00 | 000 | UTC", "2016-02-19T20:15:22.629 GMT | 2016 | 02 | 19 | 20 | 15 | 22 | 629 | UTC", }, splitBy = "\\|") // @formatter:off public void testDateTime(Date date, int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millis, String timeZone) { // Expect: assertThat(date).isEqualTo(date(year, month, dayOfMonth, hourOfDay, minute, second, millis, timeZone)); } private Date date(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millis, String timeZone) { GregorianCalendar calendar = new GregorianCalendar(year, month - 1, dayOfMonth, hourOfDay, minute, second); calendar.set(Calendar.MILLISECOND, millis); TimeZone.setDefault(TimeZone.getTimeZone(timeZone)); return calendar.getTime(); } }
TNG/junit-dataprovider
junit4/src/integTest/java/com/tngtech/test/java/junit/dataprovider/custom/DataProviderCustomStringConverterAcceptanceTest.java
Java
apache-2.0
1,409
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.subscriptions; import io.reactivex.annotations.Nullable; import org.reactivestreams.Subscriber; import io.reactivex.internal.fuseable.QueueSubscription; /** * An empty subscription that does nothing other than validates the request amount. */ public enum EmptySubscription implements QueueSubscription<Object> { /** A singleton, stateless instance. */ INSTANCE; @Override public void request(long n) { SubscriptionHelper.validate(n); } @Override public void cancel() { // no-op } @Override public String toString() { return "EmptySubscription"; } /** * Sets the empty subscription instance on the subscriber and then * calls onError with the supplied error. * * <p>Make sure this is only called if the subscriber hasn't received a * subscription already (there is no way of telling this). * * @param e the error to deliver to the subscriber * @param s the target subscriber */ public static void error(Throwable e, Subscriber<?> s) { s.onSubscribe(INSTANCE); s.onError(e); } /** * Sets the empty subscription instance on the subscriber and then * calls onComplete. * * <p>Make sure this is only called if the subscriber hasn't received a * subscription already (there is no way of telling this). * * @param s the target subscriber */ public static void complete(Subscriber<?> s) { s.onSubscribe(INSTANCE); s.onComplete(); } @Nullable @Override public Object poll() { return null; // always empty } @Override public boolean isEmpty() { return true; } @Override public void clear() { // nothing to do } @Override public int requestFusion(int mode) { return mode & ASYNC; // accept async mode: an onComplete or onError will be signalled after anyway } @Override public boolean offer(Object value) { throw new UnsupportedOperationException("Should not be called!"); } @Override public boolean offer(Object v1, Object v2) { throw new UnsupportedOperationException("Should not be called!"); } }
akarnokd/RxJava
src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java
Java
apache-2.0
2,867
package org.jboss.resteasy.test.util.resource; public interface TypesGenericAnotherFoo<T> extends TypesGenericAnotherBar { void foo(T t); }
awhitford/Resteasy
testsuite/unit-tests/src/test/java/org/jboss/resteasy/test/util/resource/TypesGenericAnotherFoo.java
Java
apache-2.0
145
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2014 Eric Lafortune ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.shrink; import proguard.classfile.*; import proguard.classfile.visitor.*; /** * This class can be used as a mark when keeping classes, class members, and * other elements. It can be certain or preliminary. It also contains additional * information about the reasons why an element is being kept. * * @see ClassShrinker * * @author Eric Lafortune */ final class ShortestUsageMark { private final boolean certain; private final String reason; private final int depth; private Clazz clazz; private Member member; /** * Creates a new certain ShortestUsageMark. * @param reason the reason for this mark. */ public ShortestUsageMark(String reason) { this.certain = true; this.reason = reason; this.depth = 0; } /** * Creates a new certain ShortestUsageMark. * @param previousUsageMark the previous mark to which this one is linked. * @param reason the reason for this mark. * @param clazz the class causing this mark. */ public ShortestUsageMark(ShortestUsageMark previousUsageMark, String reason, int cost, Clazz clazz) { this(previousUsageMark, reason, cost, clazz, null); } /** * Creates a new certain ShortestUsageMark. * @param previousUsageMark the previous mark to which this one is linked. * @param reason the reason for this mark. * @param clazz the class causing this mark. * @param member the member in the above class causing this mark. * @param cost the added cost of following this path. */ public ShortestUsageMark(ShortestUsageMark previousUsageMark, String reason, int cost, Clazz clazz, Member member) { this.certain = true; this.reason = reason; this.depth = previousUsageMark.depth + cost; this.clazz = clazz; this.member = member; } /** * Creates a new ShortestUsageMark, based on another mark. * @param otherUsageMark the other mark, whose properties will be copied. * @param certain specifies whether this is a certain mark. */ public ShortestUsageMark(ShortestUsageMark otherUsageMark, boolean certain) { this.certain = certain; this.reason = otherUsageMark.reason; this.depth = otherUsageMark.depth; this.clazz = otherUsageMark.clazz; this.member = otherUsageMark.member; } /** * Returns whether this is a certain mark. */ public boolean isCertain() { return certain; } /** * Returns the reason for this mark. */ public String getReason() { return reason; } /** * Returns whether this mark has a shorter chain of reasons than the * given mark. */ public boolean isShorter(ShortestUsageMark otherUsageMark) { return this.depth < otherUsageMark.depth; } /** * Returns whether this is mark is caused by the given class. */ public boolean isCausedBy(Clazz clazz) { return clazz.equals(this.clazz); } /** * Applies the given class visitor to this mark's class, if any, * and if this mark doesn't have a member. */ public void acceptClassVisitor(ClassVisitor classVisitor) { if (clazz != null && member == null) { clazz.accept(classVisitor); } } /** * Applies the given class visitor to this mark's member, if any. */ public void acceptMemberVisitor(MemberVisitor memberVisitor) { if (clazz != null && member != null) { member.accept(clazz, memberVisitor); } } // Implementations for Object. public String toString() { return "certain=" + certain + ", depth="+depth+": " + reason + (clazz != null ? clazz.getName() : "(none)") + ": " + (member != null ? member.getName(clazz) : "(none)"); } }
oneliang/third-party-lib
proguard/proguard/shrink/ShortestUsageMark.java
Java
apache-2.0
5,360
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.io; import com.intellij.openapi.Forceable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.LinkedHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.locks.ReentrantLock; /** * @author max */ public class PagedFileStorage implements Forceable { private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.PagedFileStorage"); public static final int MB = 1024 * 1024; public static final int BUFFER_SIZE; private static final int LOWER_LIMIT; private static final int UPPER_LIMIT; static { final int lower = 100; final int upper = SystemInfo.is64Bit ? 500 : 200; BUFFER_SIZE = Math.max(1, SystemProperties.getIntProperty("idea.paged.storage.page.size", 10)) * MB; final long max = maxDirectMemory() - 2 * BUFFER_SIZE; LOWER_LIMIT = (int)Math.min(lower * MB, max); UPPER_LIMIT = (int)Math.min(Math.max(LOWER_LIMIT, SystemProperties.getIntProperty("idea.max.paged.storage.cache", upper) * MB), max); LOG.info("lower=" + (LOWER_LIMIT / MB) + "; upper=" + (UPPER_LIMIT / MB) + "; buffer=" + (BUFFER_SIZE / MB) + "; max=" + (max / MB)); } private static long maxDirectMemory() { try { Class<?> aClass = Class.forName("sun.misc.VM"); Method maxDirectMemory = aClass.getMethod("maxDirectMemory"); return (Long)maxDirectMemory.invoke(null); } catch (Throwable ignore) { } try { Class<?> aClass = Class.forName("java.nio.Bits"); Field maxMemory = aClass.getDeclaredField("maxMemory"); maxMemory.setAccessible(true); return (Long)maxMemory.get(null); } catch (Throwable ignore) { } return Runtime.getRuntime().maxMemory(); } private static final int UNKNOWN_PAGE = -1; private static final int MAX_PAGES_COUNT = 0xFFFF; private static final int MAX_LIVE_STORAGES_COUNT = 0xFFFF; private static final ByteOrder ourNativeByteOrder = ByteOrder.nativeOrder(); private static final String RW = "rw"; // It is important to have ourLock after previous static constants as it depends on them private static final StorageLock ourLock = new StorageLock(); private final StorageLockContext myStorageLockContext; private final boolean myNativeBytesOrder; private int myLastPage = UNKNOWN_PAGE; private int myLastPage2 = UNKNOWN_PAGE; private int myLastPage3 = UNKNOWN_PAGE; private ByteBufferWrapper myLastBuffer; private ByteBufferWrapper myLastBuffer2; private ByteBufferWrapper myLastBuffer3; private int myLastChangeCount; private int myLastChangeCount2; private int myLastChangeCount3; private int myStorageIndex; private final Object myLastAccessedBufferCacheLock = new Object(); private final byte[] myTypedIOBuffer; private volatile boolean isDirty = false; private final File myFile; protected volatile long mySize = -1; protected final int myPageSize; protected final boolean myValuesAreBufferAligned; public PagedFileStorage(File file, StorageLock lock) throws IOException { this(file, lock, BUFFER_SIZE, false); } public PagedFileStorage(File file, StorageLock lock, int pageSize, boolean valuesAreBufferAligned) throws IOException { this(file, lock.myDefaultStorageLockContext, pageSize, valuesAreBufferAligned); } public PagedFileStorage(File file, @Nullable StorageLockContext storageLockContext, int pageSize, boolean valuesAreBufferAligned) throws IOException { this(file, storageLockContext, pageSize, valuesAreBufferAligned, false); } public PagedFileStorage(File file, @Nullable StorageLockContext storageLockContext, int pageSize, boolean valuesAreBufferAligned, boolean nativeBytesOrder) throws IOException { myFile = file; myStorageLockContext = storageLockContext != null ? storageLockContext : ourLock.myDefaultStorageLockContext; myPageSize = Math.max(pageSize > 0 ? pageSize : BUFFER_SIZE, Page.PAGE_SIZE); myValuesAreBufferAligned = valuesAreBufferAligned; myStorageIndex = myStorageLockContext.myStorageLock.registerPagedFileStorage(this); myTypedIOBuffer = valuesAreBufferAligned ? null:new byte[8]; myNativeBytesOrder = nativeBytesOrder; } public void lock() { myStorageLockContext.lock(); } public void unlock() { myStorageLockContext.unlock(); } public StorageLockContext getStorageLockContext() { return myStorageLockContext; } public File getFile() { return myFile; } public void putInt(long addr, int value) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int)(addr % myPageSize); getBuffer(page).putInt(page_offset, value); } else { Bits.putInt(myTypedIOBuffer, 0, value); put(addr, myTypedIOBuffer, 0, 4); } } public int getInt(long addr) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int) (addr % myPageSize); return getReadOnlyBuffer(page).getInt(page_offset); } else { get(addr, myTypedIOBuffer, 0, 4); return Bits.getInt(myTypedIOBuffer, 0); } } public final void putShort(long addr, short value) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int)(addr % myPageSize); getBuffer(page).putShort(page_offset, value); } else { Bits.putShort(myTypedIOBuffer, 0, value); put(addr, myTypedIOBuffer, 0, 2); } } int getOffsetInPage(long addr) { return (int)(addr % myPageSize); } ByteBufferWrapper getByteBuffer(long address, boolean modify) { return getBufferWrapper(address / myPageSize, modify); } public final short getShort(long addr) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int)(addr % myPageSize); return getReadOnlyBuffer(page).getShort(page_offset); } else { get(addr, myTypedIOBuffer, 0, 2); return Bits.getShort(myTypedIOBuffer, 0); } } public void putLong(long addr, long value) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int)(addr % myPageSize); getBuffer(page).putLong(page_offset, value); } else { Bits.putLong(myTypedIOBuffer, 0, value); put(addr, myTypedIOBuffer, 0, 8); } } @SuppressWarnings({"UnusedDeclaration"}) public void putByte(final long addr, final byte b) { put(addr, b); } public byte getByte(long addr) { return get(addr); } public long getLong(long addr) { if (myValuesAreBufferAligned) { long page = addr / myPageSize; int page_offset = (int)(addr % myPageSize); return getReadOnlyBuffer(page).getLong(page_offset); } else { get(addr, myTypedIOBuffer, 0, 8); return Bits.getLong(myTypedIOBuffer, 0); } } public byte get(long index) { long page = index / myPageSize; int offset = (int)(index % myPageSize); return getReadOnlyBuffer(page).get(offset); } public void put(long index, byte value) { long page = index / myPageSize; int offset = (int)(index % myPageSize); getBuffer(page).put(offset, value); } public void get(long index, byte[] dst, int offset, int length) { long i = index; int o = offset; int l = length; while (l > 0) { long page = i / myPageSize; int page_offset = (int) (i % myPageSize); int page_len = Math.min(l, myPageSize - page_offset); final ByteBuffer buffer = getReadOnlyBuffer(page); try { buffer.position(page_offset); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("can't position buffer to offset " + page_offset + ", " + "buffer.limit=" + buffer.limit() + ", " + "page=" + page + ", " + "file=" + myFile.getName() + ", "+ "file.length=" + length()); } buffer.get(dst, o, page_len); l -= page_len; o += page_len; i += page_len; } } public void put(long index, byte[] src, int offset, int length) { long i = index; int o = offset; int l = length; while (l > 0) { long page = i / myPageSize; int page_offset = (int) (i % myPageSize); int page_len = Math.min(l, myPageSize - page_offset); final ByteBuffer buffer = getBuffer(page); try { buffer.position(page_offset); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("can't position buffer to offset " + page_offset); } buffer.put(src, o, page_len); l -= page_len; o += page_len; i += page_len; } } public void close() { try { force(); } finally { unmapAll(); myStorageLockContext.myStorageLock.myIndex2Storage.remove(myStorageIndex); myStorageIndex = -1; } } private void unmapAll() { myStorageLockContext.myStorageLock.unmapBuffersForOwner(myStorageIndex, myStorageLockContext); synchronized (myLastAccessedBufferCacheLock) { myLastPage = UNKNOWN_PAGE; myLastPage2 = UNKNOWN_PAGE; myLastPage3 = UNKNOWN_PAGE; myLastBuffer = null; myLastBuffer2 = null; myLastBuffer3 = null; } } public void resize(long newSize) throws IOException { long oldSize = myFile.length(); if (oldSize == newSize && oldSize == length()) return; final long started = IOStatistics.DEBUG ? System.currentTimeMillis():0; myStorageLockContext.myStorageLock.invalidateBuffer(myStorageIndex | (int)(oldSize / myPageSize)); // TODO long page //unmapAll(); // we do not need it since all page aligned buffers can be reused final long unmapAllFinished = IOStatistics.DEBUG ? System.currentTimeMillis():0; resizeFile(newSize); // it is not guaranteed that new partition will consist of null // after resize, so we should fill it manually long delta = newSize - oldSize; if (delta > 0) fillWithZeros(oldSize, delta); if (IOStatistics.DEBUG) { long finished = System.currentTimeMillis(); if (finished - started > IOStatistics.MIN_IO_TIME_TO_REPORT) { IOStatistics.dump("Resized "+myFile + " from " + oldSize + " to " + newSize + " for " + (finished - started) + ", unmap all:" + (finished - unmapAllFinished)); } } } private void resizeFile(long newSize) throws IOException { mySize = -1; RandomAccessFile raf = new RandomAccessFile(myFile, RW); try { raf.setLength(newSize); } finally { raf.close(); } mySize = newSize; } private static final int MAX_FILLER_SIZE = 8192; private void fillWithZeros(long from, long length) { byte[] buff = new byte[MAX_FILLER_SIZE]; Arrays.fill(buff, (byte)0); while (length > 0) { final int filled = Math.min((int)length, MAX_FILLER_SIZE); put(from, buff, 0, filled); length -= filled; from += filled; } } public final long length() { long size = mySize; if (size == -1) { mySize = size = myFile.length(); } return size; } private ByteBuffer getBuffer(long page) { return getBufferWrapper(page, true).getCachedBuffer(); } private ByteBuffer getReadOnlyBuffer(long page) { return getBufferWrapper(page, false).getCachedBuffer(); } private ByteBufferWrapper getBufferWrapper(long page, boolean modify) { synchronized (myLastAccessedBufferCacheLock) { if (myLastPage == page) { ByteBuffer buf = myLastBuffer.getCachedBuffer(); if (buf != null && myLastChangeCount == myStorageLockContext.myStorageLock.myMappingChangeCount) { if (modify) markDirty(myLastBuffer); return myLastBuffer; } } else if (myLastPage2 == page) { ByteBuffer buf = myLastBuffer2.getCachedBuffer(); if (buf != null && myLastChangeCount2 == myStorageLockContext.myStorageLock.myMappingChangeCount) { if (modify) markDirty(myLastBuffer2); return myLastBuffer2; } } else if (myLastPage3 == page) { ByteBuffer buf = myLastBuffer3.getCachedBuffer(); if (buf != null && myLastChangeCount3 == myStorageLockContext.myStorageLock.myMappingChangeCount) { if (modify) markDirty(myLastBuffer3); return myLastBuffer3; } } } try { assert page >= 0 && page <= MAX_PAGES_COUNT:page; if (myStorageIndex == -1) { myStorageIndex = myStorageLockContext.myStorageLock.registerPagedFileStorage(this); } ByteBufferWrapper byteBufferWrapper = myStorageLockContext.myStorageLock.get(myStorageIndex | (int)page); // TODO: long page if (modify) markDirty(byteBufferWrapper); ByteBuffer buf = byteBufferWrapper.getBuffer(); if (myNativeBytesOrder && buf.order() != ourNativeByteOrder) { buf.order(ourNativeByteOrder); } synchronized (myLastAccessedBufferCacheLock) { if (myLastPage != page) { myLastPage3 = myLastPage2; myLastBuffer3 = myLastBuffer2; myLastChangeCount3 = myLastChangeCount2; myLastPage2 = myLastPage; myLastBuffer2 = myLastBuffer; myLastChangeCount2 = myLastChangeCount; myLastBuffer = byteBufferWrapper; myLastPage = (int)page; // TODO long page } else { myLastBuffer = byteBufferWrapper; } myLastChangeCount = myStorageLockContext.myStorageLock.myMappingChangeCount; } return byteBufferWrapper; } catch (IOException e) { throw new MappingFailedException("Cannot map buffer", e); } } private void markDirty(ByteBufferWrapper buffer) { if (!isDirty) isDirty = true; buffer.markDirty(); } @Override public void force() { long started = IOStatistics.DEBUG ? System.currentTimeMillis():0; if (isDirty) { myStorageLockContext.myStorageLock.flushBuffersForOwner(myStorageIndex, myStorageLockContext); isDirty = false; } if (IOStatistics.DEBUG) { long finished = System.currentTimeMillis(); if (finished - started > IOStatistics.MIN_IO_TIME_TO_REPORT) { IOStatistics.dump("Flushed "+myFile + " for " + (finished - started)); } } } @Override public boolean isDirty() { return isDirty; } public static class StorageLock { private static final int FILE_INDEX_MASK = 0xFFFF0000; private static final int FILE_INDEX_SHIFT = 16; public final StorageLockContext myDefaultStorageLockContext; private final ConcurrentIntObjectMap<PagedFileStorage> myIndex2Storage = ContainerUtil.createConcurrentIntObjectMap(); private final LinkedHashMap<Integer, ByteBufferWrapper> mySegments; private final ReentrantLock mySegmentsAccessLock = new ReentrantLock(); // protects map operations of mySegments, needed for LRU order, mySize and myMappingChangeCount // todo avoid locking for access private final ReentrantLock mySegmentsAllocationLock = new ReentrantLock(); private final ConcurrentLinkedQueue<ByteBufferWrapper> mySegmentsToRemove = new ConcurrentLinkedQueue<ByteBufferWrapper>(); private volatile long mySize; private volatile long mySizeLimit; private volatile int myMappingChangeCount; public StorageLock() { this(true); } public StorageLock(boolean checkThreadAccess) { myDefaultStorageLockContext = new StorageLockContext(this, checkThreadAccess); mySizeLimit = UPPER_LIMIT; mySegments = new LinkedHashMap<Integer, ByteBufferWrapper>(10, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, ByteBufferWrapper> eldest) { return mySize > mySizeLimit; } @Nullable @Override public ByteBufferWrapper remove(Object key) { // this method can be called after removeEldestEntry ByteBufferWrapper wrapper = super.remove(key); if (wrapper != null) { ++myMappingChangeCount; mySegmentsToRemove.offer(wrapper); mySize -= wrapper.myLength; } return wrapper; } }; } public void lock() { myDefaultStorageLockContext.lock(); } public void unlock() { myDefaultStorageLockContext.unlock(); } private int registerPagedFileStorage(@NotNull PagedFileStorage storage) { int registered = myIndex2Storage.size(); assert registered <= MAX_LIVE_STORAGES_COUNT; int value = registered << FILE_INDEX_SHIFT; while(myIndex2Storage.cacheOrGet(value, storage) != storage) { ++registered; assert registered <= MAX_LIVE_STORAGES_COUNT; value = registered << FILE_INDEX_SHIFT; } return value; } private PagedFileStorage getRegisteredPagedFileStorageByIndex(int index) { return myIndex2Storage.get(index); } private ByteBufferWrapper get(Integer key) { ByteBufferWrapper wrapper; try { // fast path mySegmentsAccessLock.lock(); wrapper = mySegments.get(key); if (wrapper != null) return wrapper; } finally { mySegmentsAccessLock.unlock(); } mySegmentsAllocationLock.lock(); try { // check if anybody cared about our segment mySegmentsAccessLock.lock(); try { wrapper = mySegments.get(key); if (wrapper != null) return wrapper; } finally { mySegmentsAccessLock.unlock(); } long started = IOStatistics.DEBUG ? System.currentTimeMillis() : 0; wrapper = createValue(key); if (IOStatistics.DEBUG) { long finished = System.currentTimeMillis(); if (finished - started > IOStatistics.MIN_IO_TIME_TO_REPORT) { IOStatistics.dump( "Mapping " + wrapper.myLength + " from " + wrapper.myPosition + " file:" + wrapper.myFile + " for " + (finished - started)); } } mySegmentsAccessLock.lock(); try { mySegments.put(key, wrapper); mySize += wrapper.myLength; } finally { mySegmentsAccessLock.unlock(); } ensureSize(mySizeLimit); return wrapper; } finally { mySegmentsAllocationLock.unlock(); } } private void disposeRemovedSegments() { if (mySegmentsToRemove.isEmpty()) return; assert mySegmentsAllocationLock.isHeldByCurrentThread(); Iterator<ByteBufferWrapper> iterator = mySegmentsToRemove.iterator(); while(iterator.hasNext()) { iterator.next().dispose(); iterator.remove(); } } private void ensureSize(long sizeLimit) { assert mySegmentsAllocationLock.isHeldByCurrentThread(); try { mySegmentsAccessLock.lock(); while (mySize > sizeLimit) { // we still have to drop something mySegments.doRemoveEldestEntry(); } } finally { mySegmentsAccessLock.unlock(); } disposeRemovedSegments(); } @NotNull private ByteBufferWrapper createValue(Integer key) { final int storageIndex = key & FILE_INDEX_MASK; PagedFileStorage owner = getRegisteredPagedFileStorageByIndex(storageIndex); assert owner != null: "No storage for index " + storageIndex; checkThreadAccess(owner.myStorageLockContext); long off = (long)(key & MAX_PAGES_COUNT) * owner.myPageSize; long ownerLength = owner.length(); if (off > ownerLength) { throw new IndexOutOfBoundsException("off=" + off + " key.owner.length()=" + ownerLength); } int min = (int)Math.min(ownerLength - off, owner.myPageSize); ByteBufferWrapper wrapper = ByteBufferWrapper.readWriteDirect(owner.myFile, off, min); Throwable oome = null; while (true) { try { // ensure it's allocated wrapper.getBuffer(); if (oome != null) { LOG.info("Successfully recovered OOME in memory mapping: -Xmx=" + Runtime.getRuntime().maxMemory() / MB + "MB " + "new size limit: " + mySizeLimit / MB + "MB " + "trying to allocate " + wrapper.myLength + " block"); } return wrapper; } catch (IOException e) { throw new MappingFailedException("Cannot map buffer", e); } catch (OutOfMemoryError e) { oome = e; if (mySizeLimit > LOWER_LIMIT) { mySizeLimit -= owner.myPageSize; } long newSize = mySize - owner.myPageSize; if (newSize < 0) { LOG.info("Currently allocated:"+mySize); LOG.info("Mapping failed due to OOME. Current buffers: " + mySegments); LOG.info(oome); try { Class<?> aClass = Class.forName("java.nio.Bits"); Field reservedMemory = aClass.getDeclaredField("reservedMemory"); reservedMemory.setAccessible(true); Field maxMemory = aClass.getDeclaredField("maxMemory"); maxMemory.setAccessible(true); Object max, reserved; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (aClass) { max = maxMemory.get(null); reserved = reservedMemory.get(null); } LOG.info("Max memory:" + max + ", reserved memory:" + reserved); } catch (Throwable ignored) { } throw new MappingFailedException( "Cannot recover from OOME in memory mapping: -Xmx=" + Runtime.getRuntime().maxMemory() / MB + "MB " + "new size limit: " + mySizeLimit / MB + "MB " + "trying to allocate " + wrapper.myLength + " block", e); } ensureSize(newSize); // next try } } } private static void checkThreadAccess(StorageLockContext storageLockContext) { if (storageLockContext.myCheckThreadAccess && !storageLockContext.myLock.isHeldByCurrentThread()) { throw new IllegalStateException("Must hold StorageLock lock to access PagedFileStorage"); } } @Nullable private Map<Integer, ByteBufferWrapper> getBuffersOrderedForOwner(int index, StorageLockContext storageLockContext) { mySegmentsAccessLock.lock(); try { checkThreadAccess(storageLockContext); Map<Integer, ByteBufferWrapper> mineBuffers = null; for (Map.Entry<Integer, ByteBufferWrapper> entry : mySegments.entrySet()) { if ((entry.getKey() & FILE_INDEX_MASK) == index) { if (mineBuffers == null) { mineBuffers = new TreeMap<Integer, ByteBufferWrapper>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); } mineBuffers.put(entry.getKey(), entry.getValue()); } } return mineBuffers; } finally { mySegmentsAccessLock.unlock(); } } private void unmapBuffersForOwner(int index, StorageLockContext storageLockContext) { final Map<Integer, ByteBufferWrapper> buffers = getBuffersOrderedForOwner(index, storageLockContext); if (buffers != null) { mySegmentsAccessLock.lock(); try { for (Integer key : buffers.keySet()) { mySegments.remove(key); } } finally { mySegmentsAccessLock.unlock(); } mySegmentsAllocationLock.lock(); try { disposeRemovedSegments(); } finally { mySegmentsAllocationLock.unlock(); } } } private void flushBuffersForOwner(int index, StorageLockContext storageLockContext) { Map<Integer, ByteBufferWrapper> buffers = getBuffersOrderedForOwner(index, storageLockContext); if (buffers != null) { mySegmentsAllocationLock.lock(); try { for(ByteBufferWrapper buffer:buffers.values()) { buffer.flush(); } } finally { mySegmentsAllocationLock.unlock(); } } } public void invalidateBuffer(int page) { mySegmentsAccessLock.lock(); try { mySegments.remove(page); } finally { mySegmentsAccessLock.unlock(); } mySegmentsAllocationLock.lock(); try { disposeRemovedSegments(); } finally { mySegmentsAllocationLock.unlock(); } } } public static class StorageLockContext { private final boolean myCheckThreadAccess; private final ReentrantLock myLock; private final StorageLock myStorageLock; @Deprecated public StorageLockContext(StorageLock lock) { this(lock, true); } private StorageLockContext(StorageLock lock, boolean checkAccess) { myLock = new ReentrantLock(); myStorageLock = lock; myCheckThreadAccess = checkAccess; } public StorageLockContext(boolean checkAccess) { this(ourLock, checkAccess); } public void lock() { myLock.lock(); } public void unlock() { myLock.unlock(); } } }
Soya93/Extract-Refactoring
platform/util/src/com/intellij/util/io/PagedFileStorage.java
Java
apache-2.0
26,646
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfa.lib.factory; import com.google.api.ads.common.lib.factory.BaseServices; import com.google.api.ads.dfa.lib.client.DfaServiceClient; import com.google.api.ads.dfa.lib.client.DfaServiceDescriptor; import com.google.api.ads.dfa.lib.client.DfaSession; import com.google.inject.Injector; /** * Base for a utility class which creates DFA service clients. */ public abstract class BaseDfaServices extends BaseServices<DfaServiceClient, DfaSession, DfaServiceDescriptor> { /** * Constructor. * * @param injector an injector which binds all the necessary classes */ protected BaseDfaServices(Injector injector) { super(new DfaServiceClientFactory(injector)); } }
raja15792/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/dfa/lib/factory/BaseDfaServices.java
Java
apache-2.0
1,439
/** * Copyright 2011-2019 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.dmdl.parser; import com.asakusafw.dmdl.Diagnostic; import com.asakusafw.dmdl.Region; /** * DMDL Syntax Error. * @since 0.2.0 * @version 0.5.3 */ public class DmdlSyntaxException extends Exception { private static final long serialVersionUID = 1L; private final Diagnostic diagnostic; /** * Creates a new instance. * @param diagnostic the source diagnostic * @param cause the original cause */ public DmdlSyntaxException(Diagnostic diagnostic, Throwable cause) { super(diagnostic.message, cause); this.diagnostic = diagnostic; } /** * Returns the region on this error. * @return the region, or {@code null} if not known */ public Region getRegion() { return diagnostic.region; } }
akirakw/asakusafw
dmdl-project/asakusa-dmdl-core/src/main/java/com/asakusafw/dmdl/parser/DmdlSyntaxException.java
Java
apache-2.0
1,416
/** * Copyright © 2014 - 2017 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.flink.algorithms.fsm.transactional.common.functions; import org.apache.flink.api.common.functions.FilterFunction; import org.gradoop.flink.model.impl.layouts.transactional.tuples.GraphTransaction; /** * (g, V, E) => true, if E not empty */ public class NotEmpty implements FilterFunction<GraphTransaction> { @Override public boolean filter(GraphTransaction graphTransaction) throws Exception { return !graphTransaction.getEdges().isEmpty(); } }
p3et/gradoop
gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/transactional/common/functions/NotEmpty.java
Java
apache-2.0
1,119
package cn.ac.ict.htc.knn.data; public class Vector2<T1, T2> { protected T1 v1; protected T2 v2; public Vector2() { } public Vector2(T1 v1, T2 v2) { this.v1 = v1; this.v2 = v2; } public T1 getV1() { return v1; } public T2 getV2() { return v2; } @Override public String toString() { return v1 + "-" + v2; } }
ict-carch/hadoop-plus
KNN_combine/src/main/java/cn/ac/ict/htc/knn/data/Vector2.java
Java
apache-2.0
338
/*- * #%L * ELK Reasoner Core * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2016 Department of Computer Science, University of Oxford * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.semanticweb.elk.reasoner.entailments.model; import java.util.List; import org.semanticweb.elk.owl.interfaces.ElkDisjointClassesAxiom; /** * {@link ElkDisjointClassesAxiom} was entailed because inconsistencies of * pairwise intersections of classes from * {@link ElkDisjointClassesAxiom#getClassExpressions()} were entailed. * <p> * {@link #getPremises()} returns {@link SubClassOfAxiomEntailment}-s where * subclasses are all pairwise intersections of classes from * {@link ElkDisjointClassesAxiom#getClassExpressions()} and superclasses are * {@code owl:Nothing}. * * @author Peter Skocovsky */ public interface EntailedIntersectionInconsistencyEntailsDisjointClassesAxiom extends AxiomEntailmentInference<ElkDisjointClassesAxiom> { @Override DisjointClassesAxiomEntailment getConclusion(); @Override List<? extends SubClassOfAxiomEntailment> getPremises(); public static interface Visitor<O> { O visit(EntailedIntersectionInconsistencyEntailsDisjointClassesAxiom derivedIntersectionInconsistencyEntailsDisjointClassesAxiom); } }
liveontologies/elk-reasoner
elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/entailments/model/EntailedIntersectionInconsistencyEntailsDisjointClassesAxiom.java
Java
apache-2.0
1,790
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.enterprise.adaptor; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * Asynchronous sender of feed items. {@code worker()} must be started by client * and running for items to be sent. */ class AsyncDocIdSender implements AsyncDocIdPusher, DocumentHandler.AsyncPusher { private static final Logger log = Logger.getLogger(AsyncDocIdSender.class.getName()); private final ItemPusher itemPusher; private final int maxBatchSize; private final long maxLatency; private final TimeUnit maxLatencyUnit; private final BlockingQueue<DocIdSender.Item> queue; private final Runnable worker = new WorkerRunnable(); /** * {@code queueCapacity} should be large enough to handle queuing the number * of new items that would be expected during the amount of time it takes to * send a feed. For example, if requests are coming in at 300 docs/sec and it * takes a second to send a feed of {@code maxBatchSize}, then {@code * queueCapacity} should be at least {@code 300}. */ public AsyncDocIdSender(ItemPusher itemPusher, int maxBatchSize, long maxLatency, TimeUnit maxLatencyUnit, int queueCapacity) { if (itemPusher == null || maxLatencyUnit == null) { throw new NullPointerException(); } if (maxBatchSize < 1) { throw new IllegalArgumentException("maxBatchSize must be positive"); } this.itemPusher = itemPusher; this.maxBatchSize = maxBatchSize; this.maxLatency = maxLatency; this.maxLatencyUnit = maxLatencyUnit; this.queue = new ArrayBlockingQueue<DocIdSender.Item>(queueCapacity); } /** * Enqueue {@code item} to be sent by worker. If the queue is full, then the * item will be dropped and a warning will be logged. * * @return {@code true} if the item was accepted, {@code false} otherwise */ @Override public boolean asyncPushItem(final DocIdSender.Item item) { if (!queue.offer(item)) { log.log(Level.WARNING, "Failed to queue item: {0}", item); return false; } return true; } @Override public boolean pushDocId(DocId docId) { return asyncPushItem(new DocIdPusher.Record.Builder(docId).build()); } @Override public boolean pushRecord(DocIdPusher.Record record) { return asyncPushItem(record); } @Override public boolean pushNamedResource(DocId docId, Acl acl) { return asyncPushItem(new DocIdSender.AclItem(docId, null, acl)); } public Runnable worker() { return worker; } private class WorkerRunnable implements Runnable { @Override public void run() { Set<DocIdSender.Item> items = new LinkedHashSet<DocIdSender.Item>(); try { while (true) { BlockingQueueBatcher.take( queue, items, maxBatchSize, maxLatency, maxLatencyUnit); itemPusher.pushItems(items.iterator(), null); items.clear(); } } catch (InterruptedException ex) { log.log(Level.FINE, "AsyncDocIdSender worker shutting down", ex); try { // We are shutting down, but there are likely items that haven't been // sent because of maxLatency, so we try to send those now. // If we were interrupted between calls to take(), then take() may // have interrupted itself before draining the queue; might as well // send everything that was put on the queue. queue.drainTo(items); itemPusher.pushItems(items.iterator(), ExceptionHandlers.noRetryHandler()); } catch (InterruptedException ex2) { // Ignore, because we are going to interrupt anyway. This should // actually not happen because of the ExceptionHandler we are using, // but the precise behavior of pushItems() may change in the future. } finally { log.log(Level.FINE, "AsyncDocIdSender worker shutdown", ex); Thread.currentThread().interrupt(); } } catch (Throwable t) { log.log(Level.SEVERE, "Unexpected termination of asynchronous pusher " + "worker thread.", t); } } } public interface ItemPusher { /** * Send {@code items} using {@code handler} to manage errors. * * @returns {@code null} for success, or the first item that failed if not * all items were sent */ public <T extends DocIdSender.Item> T pushItems(Iterator<T> items, ExceptionHandler handler) throws InterruptedException; } }
googlegsa/library
src/com/google/enterprise/adaptor/AsyncDocIdSender.java
Java
apache-2.0
5,307
/* * Copyright 2008 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.ImmutableList; import com.google.javascript.rhino.Node; import com.google.protobuf.TextFormat; import java.io.IOException; import java.util.List; /** * Tests for {@link InstrumentFunctions} * */ public final class InstrumentFunctionsTest extends CompilerTestCase { private String instrumentationPb; public InstrumentFunctionsTest() { this.instrumentationPb = null; } @Override protected void setUp() { super.enableLineNumberCheck(false); this.instrumentationPb = null; } @Override protected CompilerPass getProcessor(Compiler compiler) { return new NameAndInstrumentFunctions(compiler); } @Override protected int getNumRepetitions() { // This pass is not idempotent. return 1; } public void testInstrument() { final String kPreamble = "var $$toRemoveDefinition1, $$notToRemove;\n" + "var $$toRemoveDefinition2, $$toRemoveDefinition3;\n"; // build instrumentation template and init code strings for use in // tests below. List<String> initCodeList = ImmutableList.of( "var $$Table = [];", "function $$TestDefine(id) {", " $$Table[id] = 0;", "};", "function $$TestInstrument(id) {", " $$Table[id]++;", "};"); StringBuilder initCodeBuilder = new StringBuilder(); StringBuilder pbBuilder = new StringBuilder(); for (String line : initCodeList) { initCodeBuilder.append(line).append("\n"); pbBuilder.append("init: \"").append(line).append("\"\n"); } pbBuilder.append("report_call: \"$$testInstrument\"") .append("report_defined: \"$$testDefine\"") .append("declaration_to_remove: \"$$toRemoveDefinition1\"") .append("declaration_to_remove: \"$$toRemoveDefinition2\"") .append("declaration_to_remove: \"$$toRemoveDefinition3\""); final String initCode = initCodeBuilder.toString(); this.instrumentationPb = pbBuilder.toString(); // Test basic instrumentation test("function a(){b}", initCode + "$$testDefine(0);" + "function a(){$$testInstrument(0);b}"); // Test declaration_to_remove test(kPreamble + "function a(){b}", initCode + "$$testDefine(0);" + "var $$notToRemove;" + "function a(){$$testInstrument(0);b}"); // Test object literal declarations test(kPreamble + "var a = { b: function(){c} }", initCode + "var $$notToRemove;" + "$$testDefine(0);" + "var a = { b: function(){$$testInstrument(0);c} }"); // Test multiple object literal declarations test(kPreamble + "var a = { b: function(){c}, d: function(){e} }", initCode + "var $$notToRemove;" + "$$testDefine(0);" + "$$testDefine(1);" + "var a={b:function(){$$testInstrument(0);c}," + "d:function(){$$testInstrument(1);e}}"); // Test recursive object literal declarations test(kPreamble + "var a = { b: { f: function(){c} }, d: function(){e} }", initCode + "var $$notToRemove;" + "$$testDefine(0);" + "$$testDefine(1);" + "var a={b:{f:function(){$$testInstrument(0);c}}," + "d:function(){$$testInstrument(1);e}}"); } public void testEmpty() { this.instrumentationPb = ""; test("function a(){b}", "function a(){b}"); } public void testAppNameSetter() { this.instrumentationPb = "app_name_setter: \"setAppName\""; test("function a(){b}", "setAppName(\"testfile.js\");function a(){b}"); } public void testInit() { this.instrumentationPb = "init: \"var foo = 0;\"\n" + "init: \"function f(){g();}\"\n"; test("function a(){b}", "var foo = 0;function f(){g()}function a(){b}"); } public void testDeclare() { this.instrumentationPb = "report_defined: \"$$testDefine\""; test("function a(){b}", "$$testDefine(0);function a(){b}"); } public void testCall() { this.instrumentationPb = "report_call: \"$$testCall\""; test("function a(){b}", "function a(){$$testCall(0);b}"); } public void testNested() { this.instrumentationPb = "report_call: \"$$testCall\"\n" + "report_defined: \"$$testDefine\""; test("function a(){ function b(){}}", "$$testDefine(1);$$testDefine(0);" + "function a(){$$testCall(1);function b(){$$testCall(0)}}"); } public void testExitPaths() { this.instrumentationPb = "report_exit: \"$$testExit\""; test("function a(){return}", "function a(){return $$testExit(0)}"); test("function b(){return 5}", "function b(){return $$testExit(0, 5)}"); test("function a(){if(2 != 3){return}else{return 5}}", "function a(){if(2!=3){return $$testExit(0)}" + "else{return $$testExit(0,5)}}"); test("function a(){if(2 != 3){return}else{return 5}}b()", "function a(){if(2!=3){return $$testExit(0)}" + "else{return $$testExit(0,5)}}b()"); test("function a(){if(2 != 3){return}else{return 5}}", "function a(){if(2!=3){return $$testExit(0)}" + "else{return $$testExit(0,5)}}"); } public void testExitNoReturn() { this.instrumentationPb = "report_exit: \"$$testExit\""; test("function a(){}", "function a(){$$testExit(0);}"); test("function a(){b()}", "function a(){b();$$testExit(0);}"); } public void testPartialExitPaths() { this.instrumentationPb = "report_exit: \"$$testExit\""; test("function a(){if (2 != 3) {return}}", "function a(){if (2 != 3){return $$testExit(0)}$$testExit(0)}"); } public void testExitTry() { this.instrumentationPb = "report_exit: \"$$testExit\""; test("function a(){try{return}catch(err){}}", "function a(){try{return $$testExit(0)}catch(err){}$$testExit(0)}"); test("function a(){try{}catch(err){return}}", "function a(){try{}catch(err){return $$testExit(0)}$$testExit(0)}"); test("function a(){try{return}finally{}}", "function a(){try{return $$testExit(0)}finally{}$$testExit(0)}"); test("function a(){try{return}catch(err){}finally{}}", "function a(){try{return $$testExit(0)}catch(err){}finally{}" + "$$testExit(0)}"); test("function a(){try{return 1}catch(err){return 2}}", "function a(){try{return $$testExit(0, 1)}" + "catch(err){return $$testExit(0,2)}}"); test("function a(){try{return 1}catch(err){return 2}finally{}}", "function a(){try{return $$testExit(0, 1)}" + "catch(err){return $$testExit(0,2)}" + "finally{}$$testExit(0)}"); test("function a(){try{return 1}catch(err){return 2}finally{return}}", "function a(){try{return $$testExit(0, 1)}" + "catch(err){return $$testExit(0,2)}finally{return $$testExit(0)}}"); test("function a(){try{}catch(err){}finally{return}}", "function a(){try{}catch(err){}finally{return $$testExit(0)}}"); } public void testNestedExit() { this.instrumentationPb = "report_exit: \"$$testExit\"\n" + "report_defined: \"$$testDefine\""; test("function a(){ return function(){ return c;}}", "$$testDefine(1);function a(){$$testDefine(0);" + "return $$testExit(1, function(){return $$testExit(0, c);});}"); } private class NameAndInstrumentFunctions implements CompilerPass { private final Compiler compiler; NameAndInstrumentFunctions(Compiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { FunctionNames functionNames = new FunctionNames(compiler); functionNames.process(externs, root); Instrumentation.Builder builder = Instrumentation.newBuilder(); try { TextFormat.merge(instrumentationPb, builder); } catch (IOException e) { e.printStackTrace(); } InstrumentFunctions instrumentation = new InstrumentFunctions( compiler, functionNames, builder.build(), "testfile.js"); instrumentation.process(externs, root); } } }
mbebenita/closure-compiler
test/com/google/javascript/jscomp/InstrumentFunctionsTest.java
Java
apache-2.0
8,759
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.bloomfilter; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import org.testng.annotations.Test; import java.util.Date; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; public class TestBloomFilterSerialization { @Test public void testBloomFilterCreate() { // Fresh instance BloomFilter bf = BloomFilter.newInstance(); // Add a little bit of data bf.put(Slices.wrappedBuffer("robin".getBytes())); // Serialize Slice ser = bf.serialize(); // Validate not empty assertNotNull(ser); assertTrue(ser.length() > 0); // Deserialize BloomFilter bf2 = BloomFilter.newInstance(ser); // Validate assertTrue(bf2.mightContain(Slices.wrappedBuffer("robin".getBytes()))); assertFalse(bf2.mightContain(Slices.wrappedBuffer("not-in-here".getBytes()))); } @Test public void testBloomFilterPerformanceSerialize() { BloomFilter bf = BloomFilter.newInstance(); long start = new Date().getTime(); bf.put(Slices.wrappedBuffer("robin".getBytes())); for (int i = 0; i < 10; i++) { // @todo Check optimize, seems to take about 20ms bf.serialize(); } long took = new Date().getTime() - start; assertTrue(took < 10000L); } @Test public void testBloomFilterPerformanceDeserialize() { BloomFilter bf = BloomFilter.newInstance(); long start = new Date().getTime(); bf.put(Slices.wrappedBuffer("robin".getBytes())); Slice ser = bf.serialize(); for (int i = 0; i < 10; i++) { // @todo Check optimize, seems to take about 20ms BloomFilter.newInstance(ser); } long took = new Date().getTime() - start; assertTrue(took < 10000L); } }
RobinUS2/presto-bloomfilter
src/test/java/com/facebook/presto/bloomfilter/TestBloomFilterSerialization.java
Java
apache-2.0
2,529
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deleidos.rtws.webapp.register.util; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; public class RtwsrcProperties { private static final Logger logger = Logger.getLogger(RtwsrcProperties.class); public static final String RTWS_ACCESS_KEY = "RTWS_ACCESS_KEY"; public static final String RTWS_ACCT_ID = "RTWS_ACCT_ID"; public static final String RTWS_AVAILABILITY_ZONE = "RTWS_AVAILABILITY_ZONE"; public static final String RTWS_HOSTED_ZONE = "RTWS_HOSTED_ZONE"; public static final String RTWS_IAAS_REGION = "RTWS_IAAS_REGION"; public static final String RTWS_RAID_DEVICES = "RTWS_RAID_DEVICES"; public static final String RTWS_SECRET_KEY = "RTWS_SECRET_KEY"; public static final String RTWS_STORAGE_ENDPOINT = "RTWS_STORAGE_ENDPOINT"; public static final String RTWS_TMS_DNS= "RTWS_TMS_DNS"; public static final String RTWS_VPC_ENABLED = "RTWS_VPC_ENABLED"; public static final String RTWS_FQDN = "RTWS_FQDN"; public static final String RTWS_SW_VERSION = "RTWS_SW_VERSION"; private Properties props = new Properties(); private static class RtwsrcPropertiesSingletonHolder { static final RtwsrcProperties instance = new RtwsrcProperties(); } public static RtwsrcProperties getInstance() { return RtwsrcPropertiesSingletonHolder.instance; } private RtwsrcProperties() { FileInputStream fis = null; try { fis = new FileInputStream("/etc/rtwsrc"); props.load(fis); } catch (IOException e) { logger.error("Failed to load user data from /etc/rtwsrc", e); }finally{ if(fis!=null) try { fis.close(); } catch (IOException e) {}//eh, whatever } } public String getString(String propertyName) { String value = props.getProperty(propertyName); if (value == null || value.trim().length() == 0) { logger.warn("Property Name: " + propertyName + " not found in /etc/rtwsrc"); } return value; } }
deleidos/digitaledge-platform
webapp-register/src/main/java/com/deleidos/rtws/webapp/register/util/RtwsrcProperties.java
Java
apache-2.0
13,909
package org.drools.reteoo; import org.drools.KnowledgeBase; import org.drools.RuleBase; import org.drools.common.BaseNode; import org.drools.impl.InternalKnowledgeBase; import org.drools.impl.KnowledgeBaseImpl; import org.drools.runtime.KnowledgeRuntime; import org.drools.runtime.StatefulKnowledgeSession; import java.util.Collection; public class ReteDumper { private ReteDumper() { } public static void dumpRete(KnowledgeBase kbase) { dumpRete(((InternalKnowledgeBase) kbase).getRuleBase()); } public static void dumpRete(KnowledgeRuntime session) { dumpRete(((KnowledgeBaseImpl)session.getKnowledgeBase()).getRuleBase()); } public static void dumpRete(RuleBase ruleBase) { dumpRete(((ReteooRuleBase)ruleBase).getRete()); } public static void dumpRete(Rete rete) { for (EntryPointNode entryPointNode : rete.getEntryPointNodes().values()) { dumpNode( entryPointNode, "" ); } } private static void dumpNode(BaseNode node, String ident) { System.out.println(ident + node); Sink[] sinks = null; if (node instanceof EntryPointNode) { EntryPointNode source = (EntryPointNode) node; Collection<ObjectTypeNode> otns = source.getObjectTypeNodes().values(); sinks = otns.toArray(new Sink[otns.size()]); } else if (node instanceof ObjectSource) { ObjectSource source = (ObjectSource) node; sinks = source.getSinkPropagator().getSinks(); } else if (node instanceof LeftTupleSource) { LeftTupleSource source = (LeftTupleSource) node; sinks = source.getSinkPropagator().getSinks(); } if (sinks != null) { for (Sink sink : sinks) { if (sink instanceof BaseNode) { dumpNode((BaseNode)sink, ident + " "); } } } } }
pperboires/PocDrools
drools-core/src/test/java/org/drools/reteoo/ReteDumper.java
Java
apache-2.0
1,933
package com.ctrip.xpipe.redis.meta.server.dcchange.exception; import com.ctrip.xpipe.redis.meta.server.exception.MetaServerRuntimeException; /** * @author wenchao.meng * * Dec 12, 2016 */ public class MakeRedisMasterFailException extends MetaServerRuntimeException{ private static final long serialVersionUID = 1L; public MakeRedisMasterFailException(String message, Throwable th) { super(message, th); } }
Yiiinsh/x-pipe
redis/redis-meta/src/main/java/com/ctrip/xpipe/redis/meta/server/dcchange/exception/MakeRedisMasterFailException.java
Java
apache-2.0
425
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.jooq; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link NoDslContextBeanFailureAnalyzer}. * * @author Andy Wilkinson */ class NoDslContextBeanFailureAnalyzerTests { private final NoDslContextBeanFailureAnalyzer failureAnalyzer = new NoDslContextBeanFailureAnalyzer(); @Test void noAnalysisWithoutR2dbcAutoConfiguration() { new ApplicationContextRunner().run((context) -> { this.failureAnalyzer.setBeanFactory(context.getBeanFactory()); assertThat(this.failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))).isNull(); }); } @Test void analysisWithR2dbcAutoConfiguration() { new ApplicationContextRunner().withConfiguration(AutoConfigurations.of(R2dbcAutoConfiguration.class)) .run((context) -> { this.failureAnalyzer.setBeanFactory(context.getBeanFactory()); assertThat(this.failureAnalyzer.analyze(new NoSuchBeanDefinitionException(DSLContext.class))) .isNotNull(); }); } }
mdeinum/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/NoDslContextBeanFailureAnalyzerTests.java
Java
apache-2.0
2,009
// Copyright 2014 Cybozu // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cybozu.kintone.database; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.cybozu.kintone.database.exception.ParseException; /** * Bulk request. * */ public class BulkRequest { List<BulkRequestData> requests = new ArrayList<BulkRequestData>(); /** * Constructor */ public BulkRequest() { } /** * Adds bulk request for insert. * * @param app * application id * @param record * The Record object to be inserted */ public void insert(long app, Record record) { List<Record> list = new ArrayList<Record>(); list.add(record); insert(app, list); } /** * Adds bulk request for insert. * * @param app * application id * @param records * The array of Record objects to be inserted */ public void insert(long app, List<Record> records) { JsonParser parser = new JsonParser(); String json; try { json = parser.recordsToJsonForInsert(app, records); } catch (IOException e) { throw new ParseException("failed to encode to json"); } BulkRequestData request = new BulkRequestData("POST", "/k/v1/records.json", json); requests.add(request); } /** * Adds bulk request for update (deprecated). * * @param app * application id * @param id * record number of the updated record * @param record * updated record object */ public void update(long app, long id, Record record) { List<Long> list = new ArrayList<Long>(); list.add(id); update(app, list, record); } /** * Adds bulk request for update. * * @param app * application id * @param record * updated record object */ public void updateByRecord(long app, Record record) { List<Record> list = new ArrayList<Record>(); list.add(record); updateByRecords(app, list); } /** * Adds bulk request for update * * @param app * application id * @param ids * an array of record numbers of the updated records * @param record * updated record object */ public void update(long app, List<Long> ids, Record record) { JsonParser parser = new JsonParser(); String json; try { json = parser.recordsToJsonForUpdate(app, ids, record); } catch (IOException e) { throw new ParseException("failed to encode to json"); } BulkRequestData request = new BulkRequestData("PUT", "/k/v1/records.json", json); requests.add(request); } /** * Adds bulk request for update * * @param app * application id * @param records * an array of the updated record object */ public void updateByRecords(long app, List<Record> records) { JsonParser parser = new JsonParser(); String json; try { json = parser.recordsToJsonForUpdate(app, records); } catch (IOException e) { throw new ParseException("failed to encode to json"); } BulkRequestData request = new BulkRequestData("PUT", "/k/v1/records.json", json); requests.add(request); } /** * Adds bulk request for delete * * @param app * application id * @param id * record number to be deleted */ public void delete(long app, long id) { List<Long> list = new ArrayList<Long>(); list.add(id); delete(app, list); } /** * Adds bulk request for delete * * @param app * application id * @param record * a record object to be deleted */ public void deleteByRecord(long app, Record record) { List<Record> list = new ArrayList<Record>(); list.add(record); deleteByRecords(app, list); } /** * Adds bulk request for delete * * @param app * application id * @param records * a list of the record object to be deleted */ public void deleteByRecords(long app, List<Record> records) { JsonParser parser = new JsonParser(); String json; try { json = parser.recordsToJsonForDelete(app, records); } catch (IOException e) { throw new ParseException("failed to encode to json"); } BulkRequestData request = new BulkRequestData("DELETE", "/k/v1/records.json", json); requests.add(request); } /** * Adds bulk request for delete * @param app * application id * @param ids * a list of record numbers to be deleted */ public void delete(long app, List<Long> ids) { List<Record> records = new ArrayList<Record>(); for (Long id : ids) { Record record = new Record(); record.setId(id); records.add(record); } deleteByRecords(app, records); } public String getJson() { StringBuilder sb = new StringBuilder(); sb.append("{\"requests\":["); int i = 0; for (BulkRequestData request: requests) { if (i > 0) { sb.append(","); } sb.append("{"); sb.append("\"method\": \"" + request.getMethod() + "\","); sb.append("\"api\": \"" + request.getApi() + "\","); sb.append("\"payload\": " + request.getPayload()); sb.append("}"); i++; } sb.append("]}"); return sb.toString(); } }
ryokdy/java-sdk
kintone-sdk/src/main/java/com/cybozu/kintone/database/BulkRequest.java
Java
apache-2.0
6,596
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.uninverting; import static org.apache.lucene.index.SortedSetDocValues.NO_MORE_ORDS; import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.BinaryDocValuesField; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.document.StringField; import org.apache.lucene.index.BinaryDocValues; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.index.TermsEnum.SeekStatus; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Constants; import org.apache.lucene.util.TestUtil; import org.apache.solr.SolrTestCase; import org.apache.solr.index.SlowCompositeReaderWrapper; public class TestFieldCacheVsDocValues extends SolrTestCase { @Override public void setUp() throws Exception { super.setUp(); assumeFalse( "test unsupported on J9 temporarily, see https://issues.apache.org/jira/browse/LUCENE-6522", Constants.JAVA_VENDOR.startsWith("IBM")); } public void testByteMissingVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestMissingVsFieldCache(Byte.MIN_VALUE, Byte.MAX_VALUE); } } public void testShortMissingVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestMissingVsFieldCache(Short.MIN_VALUE, Short.MAX_VALUE); } } public void testIntMissingVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestMissingVsFieldCache(Integer.MIN_VALUE, Integer.MAX_VALUE); } } public void testLongMissingVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestMissingVsFieldCache(Long.MIN_VALUE, Long.MAX_VALUE); } } public void testSortedFixedLengthVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { int fixedLength = TestUtil.nextInt(random(), 1, 10); doTestSortedVsFieldCache(fixedLength, fixedLength); } } public void testSortedVariableLengthVsFieldCache() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestSortedVsFieldCache(1, 10); } } public void testSortedSetFixedLengthVsUninvertedField() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { int fixedLength = TestUtil.nextInt(random(), 1, 10); doTestSortedSetVsUninvertedField(fixedLength, fixedLength); } } public void testSortedSetVariableLengthVsUninvertedField() throws Exception { int numIterations = atLeast(1); for (int i = 0; i < numIterations; i++) { doTestSortedSetVsUninvertedField(1, 10); } } // LUCENE-4853 public void testHugeBinaryValues() throws Exception { Analyzer analyzer = new MockAnalyzer(random()); // FSDirectory because SimpleText will consume gobbs of // space when storing big binary values: try (Directory d = newFSDirectory(createTempDir("hugeBinaryValues"))) { boolean doFixed = random().nextBoolean(); int numDocs; int fixedLength = 0; if (doFixed) { // Sometimes make all values fixed length since some // codecs have different code paths for this: numDocs = TestUtil.nextInt(random(), 10, 20); fixedLength = TestUtil.nextInt(random(), 65537, 256 * 1024); } else { numDocs = TestUtil.nextInt(random(), 100, 200); } try (IndexWriter w = new IndexWriter(d, newIndexWriterConfig(analyzer))) { List<byte[]> docBytes = new ArrayList<>(); long totalBytes = 0; for (int docID = 0; docID < numDocs; docID++) { // we don't use RandomIndexWriter because it might add // more docvalues than we expect !!!! // Must be > 64KB in size to ensure more than 2 pages in // PagedBytes would be needed: int numBytes; if (doFixed) { numBytes = fixedLength; } else if (docID == 0 || random().nextInt(5) == 3) { numBytes = TestUtil.nextInt(random(), 65537, 3 * 1024 * 1024); } else { numBytes = TestUtil.nextInt(random(), 1, 1024 * 1024); } totalBytes += numBytes; if (totalBytes > 5 * 1024 * 1024) { break; } byte[] bytes = new byte[numBytes]; random().nextBytes(bytes); docBytes.add(bytes); Document doc = new Document(); BytesRef b = new BytesRef(bytes); b.length = bytes.length; doc.add(new BinaryDocValuesField("field", b)); doc.add(new StringField("id", "" + docID, Field.Store.YES)); w.addDocument(doc); } DirectoryReader r = DirectoryReader.open(w); try (LeafReader ar = SlowCompositeReaderWrapper.wrap(r)) { TestUtil.checkReader(ar); BinaryDocValues s = FieldCache.DEFAULT.getTerms(ar, "field"); for (int docID = 0; docID < docBytes.size(); docID++) { Document doc = ar.document(docID); assertEquals(docID, s.nextDoc()); BytesRef bytes = s.binaryValue(); byte[] expected = docBytes.get(Integer.parseInt(doc.get("id"))); assertEquals(expected.length, bytes.length); assertEquals(new BytesRef(expected), bytes); } } } } } private void doTestSortedVsFieldCache(int minLength, int maxLength) throws Exception { Directory dir = newDirectory(); IndexWriterConfig conf = newIndexWriterConfig(new MockAnalyzer(random())); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf); Document doc = new Document(); Field idField = new StringField("id", "", Field.Store.NO); Field indexedField = new StringField("indexed", "", Field.Store.NO); Field dvField = new SortedDocValuesField("dv", new BytesRef()); doc.add(idField); doc.add(indexedField); doc.add(dvField); // index some docs int numDocs = atLeast(300); for (int i = 0; i < numDocs; i++) { idField.setStringValue(Integer.toString(i)); final int length; if (minLength == maxLength) { length = minLength; // fixed length } else { length = TestUtil.nextInt(random(), minLength, maxLength); } String value = TestUtil.randomSimpleString(random(), length); indexedField.setStringValue(value); dvField.setBytesValue(new BytesRef(value)); writer.addDocument(doc); if (random().nextInt(31) == 0) { writer.commit(); } } // delete some docs int numDeletions = random().nextInt(numDocs / 10); for (int i = 0; i < numDeletions; i++) { int id = random().nextInt(numDocs); writer.deleteDocuments(new Term("id", Integer.toString(id))); } writer.close(); // compare DirectoryReader ir = DirectoryReader.open(dir); for (LeafReaderContext context : ir.leaves()) { LeafReader r = context.reader(); SortedDocValues expected = FieldCache.DEFAULT.getTermsIndex(r, "indexed"); SortedDocValues actual = r.getSortedDocValues("dv"); assertEquals(r.maxDoc(), expected, actual); } ir.close(); dir.close(); } private void doTestSortedSetVsUninvertedField(int minLength, int maxLength) throws Exception { Directory dir = newDirectory(); IndexWriterConfig conf = new IndexWriterConfig(new MockAnalyzer(random())); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf); // index some docs int numDocs = atLeast(300); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); Field idField = new StringField("id", Integer.toString(i), Field.Store.NO); doc.add(idField); final int length = TestUtil.nextInt(random(), minLength, maxLength); int numValues = random().nextInt(17); // create a random list of strings List<String> values = new ArrayList<>(); for (int v = 0; v < numValues; v++) { values.add(TestUtil.randomSimpleString(random(), minLength, length)); } // add in any order to the indexed field ArrayList<String> unordered = new ArrayList<>(values); Collections.shuffle(unordered, random()); for (String v : values) { doc.add(newStringField("indexed", v, Field.Store.NO)); } // add in any order to the dv field ArrayList<String> unordered2 = new ArrayList<>(values); Collections.shuffle(unordered2, random()); for (String v : unordered2) { doc.add(new SortedSetDocValuesField("dv", new BytesRef(v))); } writer.addDocument(doc); if (random().nextInt(31) == 0) { writer.commit(); } } // delete some docs int numDeletions = random().nextInt(numDocs / 10); for (int i = 0; i < numDeletions; i++) { int id = random().nextInt(numDocs); writer.deleteDocuments(new Term("id", Integer.toString(id))); } // compare per-segment DirectoryReader ir = writer.getReader(); for (LeafReaderContext context : ir.leaves()) { LeafReader r = context.reader(); SortedSetDocValues expected = FieldCache.DEFAULT.getDocTermOrds(r, "indexed", null); SortedSetDocValues actual = r.getSortedSetDocValues("dv"); assertEquals(r.maxDoc(), expected, actual); } ir.close(); writer.forceMerge(1); // now compare again after the merge ir = writer.getReader(); LeafReader ar = getOnlyLeafReader(ir); SortedSetDocValues expected = FieldCache.DEFAULT.getDocTermOrds(ar, "indexed", null); SortedSetDocValues actual = ar.getSortedSetDocValues("dv"); assertEquals(ir.maxDoc(), expected, actual); ir.close(); writer.close(); dir.close(); } private void doTestMissingVsFieldCache(LongProducer longs) throws Exception { Directory dir = newDirectory(); IndexWriterConfig conf = newIndexWriterConfig(new MockAnalyzer(random())); RandomIndexWriter writer = new RandomIndexWriter(random(), dir, conf); Field idField = new StringField("id", "", Field.Store.NO); Field indexedField = newStringField("indexed", "", Field.Store.NO); Field dvField = new NumericDocValuesField("dv", 0); // index some docs int numDocs = atLeast(300); // numDocs should be always > 256 so that in case of a codec that optimizes // for numbers of values <= 256, all storage layouts are tested assert numDocs > 256; for (int i = 0; i < numDocs; i++) { idField.setStringValue(Integer.toString(i)); long value = longs.next(); indexedField.setStringValue(Long.toString(value)); dvField.setLongValue(value); Document doc = new Document(); doc.add(idField); // 1/4 of the time we neglect to add the fields if (random().nextInt(4) > 0) { doc.add(indexedField); doc.add(dvField); } writer.addDocument(doc); if (random().nextInt(31) == 0) { writer.commit(); } } // delete some docs int numDeletions = random().nextInt(numDocs / 10); for (int i = 0; i < numDeletions; i++) { int id = random().nextInt(numDocs); writer.deleteDocuments(new Term("id", Integer.toString(id))); } // merge some segments and ensure that at least one of them has more than // 256 values writer.forceMerge(numDocs / 256); writer.close(); // compare DirectoryReader ir = DirectoryReader.open(dir); for (LeafReaderContext context : ir.leaves()) { LeafReader r = context.reader(); Bits expected = FieldCache.DEFAULT.getDocsWithField(r, "indexed", null); Bits actual = FieldCache.DEFAULT.getDocsWithField(r, "dv", null); assertEquals(expected, actual); } ir.close(); dir.close(); } private void doTestMissingVsFieldCache(final long minValue, final long maxValue) throws Exception { doTestMissingVsFieldCache( new LongProducer() { @Override long next() { return TestUtil.nextLong(random(), minValue, maxValue); } }); } abstract static class LongProducer { abstract long next(); } private void assertEquals(Bits expected, Bits actual) throws Exception { assertEquals(expected.length(), actual.length()); for (int i = 0; i < expected.length(); i++) { assertEquals(expected.get(i), actual.get(i)); } } private void assertEquals(int maxDoc, SortedDocValues expected, SortedDocValues actual) throws Exception { // can be null for the segment if no docs actually had any SortedDocValues // in this case FC.getDocTermsOrds returns EMPTY if (actual == null) { assertEquals(expected.getValueCount(), 0); return; } assertEquals(expected.getValueCount(), actual.getValueCount()); // compare ord lists while (true) { int docID = expected.nextDoc(); if (docID == NO_MORE_DOCS) { assertEquals(NO_MORE_DOCS, actual.nextDoc()); break; } assertEquals(docID, actual.nextDoc()); assertEquals(expected.ordValue(), actual.ordValue()); assertEquals(expected.lookupOrd(expected.ordValue()), actual.lookupOrd(actual.ordValue())); } // compare ord dictionary for (long i = 0; i < expected.getValueCount(); i++) { final BytesRef expectedBytes = BytesRef.deepCopyOf(expected.lookupOrd((int) i)); final BytesRef actualBytes = actual.lookupOrd((int) i); assertEquals(expectedBytes, actualBytes); } // compare termsenum assertEquals(expected.getValueCount(), expected.termsEnum(), actual.termsEnum()); } private void assertEquals(int maxDoc, SortedSetDocValues expected, SortedSetDocValues actual) throws Exception { // can be null for the segment if no docs actually had any SortedDocValues // in this case FC.getDocTermsOrds returns EMPTY if (actual == null) { assertEquals(expected.getValueCount(), 0); return; } assertEquals(expected.getValueCount(), actual.getValueCount()); while (true) { int docID = expected.nextDoc(); assertEquals(docID, actual.nextDoc()); if (docID == NO_MORE_DOCS) { break; } long expectedOrd; while ((expectedOrd = expected.nextOrd()) != NO_MORE_ORDS) { assertEquals(expectedOrd, actual.nextOrd()); } assertEquals(NO_MORE_ORDS, actual.nextOrd()); } // compare ord dictionary for (long i = 0; i < expected.getValueCount(); i++) { final BytesRef expectedBytes = BytesRef.deepCopyOf(expected.lookupOrd(i)); final BytesRef actualBytes = actual.lookupOrd(i); assertEquals(expectedBytes, actualBytes); } // compare termsenum assertEquals(expected.getValueCount(), expected.termsEnum(), actual.termsEnum()); } private void assertEquals(long numOrds, TermsEnum expected, TermsEnum actual) throws Exception { BytesRef ref; // sequential next() through all terms while ((ref = expected.next()) != null) { assertEquals(ref, actual.next()); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } assertNull(actual.next()); // sequential seekExact(ord) through all terms for (long i = 0; i < numOrds; i++) { expected.seekExact(i); actual.seekExact(i); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } // sequential seekExact(BytesRef) through all terms for (long i = 0; i < numOrds; i++) { expected.seekExact(i); assertTrue(actual.seekExact(expected.term())); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } // sequential seekCeil(BytesRef) through all terms for (long i = 0; i < numOrds; i++) { expected.seekExact(i); assertEquals(SeekStatus.FOUND, actual.seekCeil(expected.term())); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } // random seekExact(ord) for (long i = 0; i < numOrds; i++) { long randomOrd = TestUtil.nextLong(random(), 0, numOrds - 1); expected.seekExact(randomOrd); actual.seekExact(randomOrd); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } // random seekExact(BytesRef) for (long i = 0; i < numOrds; i++) { long randomOrd = TestUtil.nextLong(random(), 0, numOrds - 1); expected.seekExact(randomOrd); actual.seekExact(expected.term()); assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } // random seekCeil(BytesRef) for (long i = 0; i < numOrds; i++) { BytesRef target = new BytesRef(TestUtil.randomUnicodeString(random())); SeekStatus expectedStatus = expected.seekCeil(target); assertEquals(expectedStatus, actual.seekCeil(target)); if (expectedStatus != SeekStatus.END) { assertEquals(expected.ord(), actual.ord()); assertEquals(expected.term(), actual.term()); } } } }
apache/solr
solr/core/src/test/org/apache/solr/uninverting/TestFieldCacheVsDocValues.java
Java
apache-2.0
19,021
/* * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.datamapper.engine.core; import org.apache.avro.Schema; import org.apache.avro.Schema.Type; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericData.Array; import org.mozilla.javascript.NativeJavaArray; import org.mozilla.javascript.Scriptable; public class AvroAwareNativeJavaArray extends NativeJavaArray { private Array<Object> recordArray; private static final long serialVersionUID = 1625850167152425723L; public AvroAwareNativeJavaArray(Scriptable scope, Object array,Array<Object> recordArray) { super(scope, array); this.recordArray = recordArray; } @Override public void put(int index, Scriptable start, Object value) { Schema elementType = recordArray.getSchema().getElementType(); if(elementType.getType().equals(Type.RECORD)){ GenericRecord record = new GenericData.Record(elementType); recordArray.add(record); } else{ recordArray.add(value); } //super.put(index, start, value); } @Override public void put(String id, Scriptable start, Object value) { // TODO Auto-generated method stub super.put(id, start, value); } @Override public Object get(int index, Scriptable start) { Schema elementType = recordArray.getSchema().getElementType(); if(elementType.getType().equals(Type.RECORD)){ if((recordArray.size() -1) < index){ recordArray.add(new GenericData.Record(elementType)); } return new ScriptableObjectFactory((GenericRecord)recordArray.get(index)); } else{ return recordArray.get(index); } //return super.get(index, start); } }
chanakaudaya/developer-studio
datamapper/org.wso2.datamapper.engine/src/main/java/org/wso2/datamapper/engine/core/AvroAwareNativeJavaArray.java
Java
apache-2.0
2,384
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testFramework; import com.intellij.ProjectTopics; import com.intellij.codeInsight.completion.CompletionProgressIndicator; import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.InspectionProfileImpl; import com.intellij.codeInspection.ex.InspectionToolRegistrar; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.ide.startup.impl.StartupManagerImpl; import com.intellij.idea.IdeaLogger; import com.intellij.idea.IdeaTestApplication; import com.intellij.mock.MockApplication; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.impl.UndoManagerImpl; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.impl.EditorFactoryImpl; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.EmptyModuleType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.ModuleAdapter; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.project.impl.ProjectManagerImpl; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingManagerImpl; import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleSchemes; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.impl.DocumentCommitThread; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.UnindexedFilesUpdater; import com.intellij.util.lang.CompoundRuntimeException; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; import junit.framework.TestCase; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @author yole */ public abstract class LightPlatformTestCase extends UsefulTestCase implements DataProvider { @NonNls public static final String PROFILE = "Configurable"; @NonNls private static final String LIGHT_PROJECT_MARK = "Light project: "; private static IdeaTestApplication ourApplication; protected static Project ourProject; private static Module ourModule; private static PsiManager ourPsiManager; private static boolean ourAssertionsInTestDetected; private static VirtualFile ourSourceRoot; private static TestCase ourTestCase; public static Thread ourTestThread; private static LightProjectDescriptor ourProjectDescriptor; private static boolean ourHaveShutdownHook; private ThreadTracker myThreadTracker; /** * @return Project to be used in tests for example for project components retrieval. */ public static Project getProject() { return ourProject; } /** * @return Module to be used in tests for example for module components retrieval. */ public static Module getModule() { return ourModule; } /** * Shortcut to PsiManager.getInstance(getProject()) */ @NotNull public static PsiManager getPsiManager() { if (ourPsiManager == null) { ourPsiManager = PsiManager.getInstance(ourProject); } return ourPsiManager; } @NotNull public static IdeaTestApplication initApplication() { ourApplication = IdeaTestApplication.getInstance(); return ourApplication; } @TestOnly public static void disposeApplication() { if (ourApplication != null) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { Disposer.dispose(ourApplication); } }); ourApplication = null; } } public static IdeaTestApplication getApplication() { return ourApplication; } @SuppressWarnings("UseOfSystemOutOrSystemErr") public static void reportTestExecutionStatistics() { System.out.println("----- TEST STATISTICS -----"); UsefulTestCase.logSetupTeardownCosts(); System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.appInstancesCreated' value='%d']", MockApplication.INSTANCES_CREATED)); System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.projectInstancesCreated' value='%d']", ProjectManagerImpl.TEST_PROJECTS_CREATED)); long totalGcTime = 0; for (GarbageCollectorMXBean mxBean : ManagementFactory.getGarbageCollectorMXBeans()) { totalGcTime += mxBean.getCollectionTime(); } System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.gcTimeMs' value='%d']", totalGcTime)); System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.classesLoaded' value='%d']", ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount())); } protected void resetAllFields() { resetClassFields(getClass()); } private void resetClassFields(@NotNull Class<?> aClass) { try { UsefulTestCase.clearDeclaredFields(this, aClass); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (aClass == LightPlatformTestCase.class) return; resetClassFields(aClass.getSuperclass()); } private static void cleanPersistedVFSContent() { ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents(); } private static void initProject(@NotNull final LightProjectDescriptor descriptor) throws Exception { ourProjectDescriptor = descriptor; AccessToken token = WriteAction.start(); try { if (ourProject != null) { closeAndDeleteProject(); } else { cleanPersistedVFSContent(); } } finally { token.finish(); } final File projectFile = FileUtil.createTempFile("light_temp_", ProjectFileType.DOT_DEFAULT_EXTENSION); LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); new Throwable(projectFile.getPath()).printStackTrace(new PrintStream(buffer)); ourProject = PlatformTestCase.createProject(projectFile, LIGHT_PROJECT_MARK + buffer); ourPathToKeep = projectFile.getPath(); if (!ourHaveShutdownHook) { ourHaveShutdownHook = true; registerShutdownHook(); } ourPsiManager = null; ourProjectDescriptor.setUpProject(ourProject, new LightProjectDescriptor.SetupHandler() { @Override public void moduleCreated(@NotNull Module module) { //noinspection AssignmentToStaticFieldFromInstanceMethod ourModule = module; } @Override public void sourceRootCreated(@NotNull VirtualFile sourceRoot) { //noinspection AssignmentToStaticFieldFromInstanceMethod ourSourceRoot = sourceRoot; } }); // project creation may make a lot of pointers, do not regard them as leak ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).storePointers(); } /** * @return The only source root */ public static VirtualFile getSourceRoot() { return ourSourceRoot; } @Override protected void setUp() throws Exception { EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() { @Override public void run() throws Exception { LightPlatformTestCase.super.setUp(); initApplication(); ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest()); ourApplication.setDataProvider(LightPlatformTestCase.this); LightProjectDescriptor descriptor = new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()); doSetup(descriptor, configureLocalInspectionTools(), getTestRootDisposable()); InjectedLanguageManagerImpl.pushInjectors(getProject()); storeSettings(); myThreadTracker = new ThreadTracker(); ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots(); VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance(); filePointerManager.storePointers(); } }); } public static void doSetup(@NotNull LightProjectDescriptor descriptor, @NotNull LocalInspectionTool[] localInspectionTools, @NotNull Disposable parentDisposable) throws Exception { assertNull("Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.", ourTestCase); IdeaLogger.ourErrorsOccurred = null; ApplicationManager.getApplication().assertIsDispatchThread(); boolean reusedProject = true; if (ourProject == null || ourProjectDescriptor == null || !ourProjectDescriptor.equals(descriptor)) { initProject(descriptor); reusedProject = false; } ProjectManagerEx projectManagerEx = ProjectManagerEx.getInstanceEx(); projectManagerEx.openTestProject(ourProject); if (reusedProject) { DumbService.getInstance(ourProject).queueTask(new UnindexedFilesUpdater(ourProject, false)); } MessageBusConnection connection = ourProject.getMessageBus().connect(parentDisposable); connection.subscribe(ProjectTopics.MODULES, new ModuleAdapter() { @Override public void moduleAdded(@NotNull Project project, @NotNull Module module) { fail("Adding modules is not permitted in LightIdeaTestCase."); } }); clearUncommittedDocuments(getProject()); CodeInsightTestFixtureImpl.configureInspections(localInspectionTools, getProject(), Collections.<String>emptyList(), parentDisposable); assertFalse(getPsiManager().isDisposed()); Boolean passed = null; try { passed = StartupManagerEx.getInstanceEx(getProject()).startupActivityPassed(); } catch (Exception ignored) { } assertTrue("open: " + getProject().isOpen() + "; disposed:" + getProject().isDisposed() + "; startup passed:" + passed + "; all open projects: " + Arrays.asList(ProjectManager.getInstance().getOpenProjects()), getProject().isInitialized()); CodeStyleSettingsManager.getInstance(getProject()).setTemporarySettings(new CodeStyleSettings()); final FileDocumentManager manager = FileDocumentManager.getInstance(); if (manager instanceof FileDocumentManagerImpl) { Document[] unsavedDocuments = manager.getUnsavedDocuments(); manager.saveAllDocuments(); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments(); } }); assertEmpty("There are unsaved documents", Arrays.asList(unsavedDocuments)); } UIUtil.dispatchAllInvocationEvents(); // startup activities ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); } // todo: use Class<? extends InspectionProfileEntry> once on Java 7 protected void enableInspectionTools(@NotNull Class<?>... classes) { final InspectionProfileEntry[] tools = new InspectionProfileEntry[classes.length]; final List<InspectionEP> eps = ContainerUtil.newArrayList(); ContainerUtil.addAll(eps, Extensions.getExtensions(LocalInspectionEP.LOCAL_INSPECTION)); ContainerUtil.addAll(eps, Extensions.getExtensions(InspectionEP.GLOBAL_INSPECTION)); next: for (int i = 0; i < classes.length; i++) { for (InspectionEP ep : eps) { if (classes[i].getName().equals(ep.implementationClass)) { tools[i] = ep.instantiateTool(); continue next; } } throw new IllegalArgumentException("Unable to find extension point for " + classes[i].getName()); } enableInspectionTools(tools); } protected void enableInspectionTools(@NotNull InspectionProfileEntry... tools) { for (InspectionProfileEntry tool : tools) { enableInspectionTool(tool); } } protected void enableInspectionTool(@NotNull InspectionToolWrapper toolWrapper) { enableInspectionTool(getProject(), toolWrapper); } protected void enableInspectionTool(@NotNull InspectionProfileEntry tool) { InspectionToolWrapper toolWrapper = InspectionToolRegistrar.wrapTool(tool); enableInspectionTool(getProject(), toolWrapper); } public static void enableInspectionTool(@NotNull final Project project, @NotNull final InspectionToolWrapper toolWrapper) { final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); final String shortName = toolWrapper.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); if (key == null) { HighlightDisplayKey.register(shortName, toolWrapper.getDisplayName(), toolWrapper.getID()); } InspectionProfileImpl.initAndDo(new Computable() { @Override public Object compute() { InspectionProfileImpl impl = (InspectionProfileImpl)profile; InspectionToolWrapper existingWrapper = impl.getInspectionTool(shortName, project); if (existingWrapper == null || existingWrapper.isInitialized() != toolWrapper.isInitialized() || toolWrapper.isInitialized() && toolWrapper.getTool() != existingWrapper.getTool()) { impl.addTool(project, toolWrapper, new THashMap<String, List<String>>()); } impl.enableTool(shortName, project); return null; } }); } @NotNull protected LocalInspectionTool[] configureLocalInspectionTools() { return LocalInspectionTool.EMPTY_ARRAY; } @Override protected void tearDown() throws Exception { Project project = getProject(); CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(); List<Throwable> errors = new SmartList<Throwable>(); try { checkForSettingsDamage(errors); doTearDown(project, ourApplication, true, errors); } catch (Throwable e) { errors.add(e); } try { //noinspection SuperTearDownInFinally super.tearDown(); } catch (Throwable e) { errors.add(e); } try { myThreadTracker.checkLeak(); InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project); ((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersAreDisposed(); } catch (Throwable e) { errors.add(e); } finally { CompoundRuntimeException.throwIfNotEmpty(errors); } } public static void doTearDown(@NotNull final Project project, @NotNull IdeaTestApplication application, boolean checkForEditors, @NotNull List<Throwable> exceptions) throws Exception { PsiDocumentManagerImpl documentManager; try { ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); DocumentCommitThread.getInstance().clearQueue(); CodeStyleSettingsManager.getInstance(project).dropTemporarySettings(); checkAllTimersAreDisposed(exceptions); UsefulTestCase.doPostponedFormatting(project); LookupManager lookupManager = LookupManager.getInstance(project); if (lookupManager != null) { lookupManager.hideActiveLookup(); } ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest(); InspectionProfileManager.getInstance().deleteProfile(PROFILE); if (ProjectManager.getInstance() == null) { exceptions.add(new AssertionError("Application components damaged")); } ContainerUtil.addIfNotNull(exceptions, new WriteCommandAction.Simple(project) { @Override protected void run() throws Throwable { if (ourSourceRoot != null) { try { final VirtualFile[] children = ourSourceRoot.getChildren(); for (VirtualFile child : children) { child.delete(this); } } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } EncodingManager encodingManager = EncodingManager.getInstance(); if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue(); FileDocumentManager manager = FileDocumentManager.getInstance(); ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any. manager.saveAllDocuments(); if (manager instanceof FileDocumentManagerImpl) { ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments(); } } }.execute().getThrowable()); assertFalse(PsiManager.getInstance(project).isDisposed()); if (!ourAssertionsInTestDetected) { if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } documentManager = clearUncommittedDocuments(project); ((HintManagerImpl)HintManager.getInstance()).cleanup(); DocumentCommitThread.getInstance().clearQueue(); EdtTestUtil.runInEdtAndWait(new Runnable() { @Override public void run() { ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests(); ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests(); UIUtil.dispatchAllInvocationEvents(); } }); TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest(); } finally { ProjectManagerEx.getInstanceEx().closeTestProject(project); application.setDataProvider(null); ourTestCase = null; ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest(); CompletionProgressIndicator.cleanupForNextTest(); } if (checkForEditors) { checkEditorsReleased(exceptions); } documentManager.clearUncommittedDocuments(); if (ourTestCount++ % 100 == 0) { // some tests are written in Groovy, and running all of them may result in some 40M of memory wasted on bean infos // so let's clear the cache every now and then to ensure it doesn't grow too large GCUtil.clearBeanInfoCache(); } } private static int ourTestCount; public static PsiDocumentManagerImpl clearUncommittedDocuments(@NotNull Project project) { PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(project); documentManager.clearUncommittedDocuments(); ProjectManagerImpl projectManager = (ProjectManagerImpl)ProjectManager.getInstance(); if (projectManager.isDefaultProjectInitialized()) { Project defaultProject = projectManager.getDefaultProject(); ((PsiDocumentManagerImpl)PsiDocumentManager.getInstance(defaultProject)).clearUncommittedDocuments(); } return documentManager; } public static void checkEditorsReleased(@NotNull List<Throwable> exceptions) { Editor[] allEditors = EditorFactory.getInstance().getAllEditors(); if (allEditors.length == 0) { return; } for (Editor editor : allEditors) { try { EditorFactoryImpl.throwNotReleasedError(editor); } catch (Throwable e) { exceptions.add(e); } finally { EditorFactory.getInstance().releaseEditor(editor); } } try { ((EditorImpl)allEditors[0]).throwDisposalError("Unreleased editors: " + allEditors.length); } catch (Throwable e) { exceptions.add(e); } } @Override public final void runBare() throws Throwable { if (!shouldRunTest()) { return; } TestRunnerUtil.replaceIdeEventQueueSafely(); EdtTestUtil.runInEdtAndWait(new ThrowableRunnable<Throwable>() { @Override public void run() throws Throwable { try { ourTestThread = Thread.currentThread(); startRunAndTear(); } finally { ourTestThread = null; try { Application application = ApplicationManager.getApplication(); if (application instanceof ApplicationEx) { PlatformTestCase.cleanupApplicationCaches(ourProject); } resetAllFields(); } catch (Throwable e) { e.printStackTrace(); } } } }); // just to make sure all deferred Runnables to finish SwingUtilities.invokeAndWait(EmptyRunnable.getInstance()); if (IdeaLogger.ourErrorsOccurred != null) { throw IdeaLogger.ourErrorsOccurred; } } private void startRunAndTear() throws Throwable { setUp(); try { ourAssertionsInTestDetected = true; runTest(); ourAssertionsInTestDetected = false; } finally { //try{ tearDown(); //} //catch(Throwable th){ // noinspection CallToPrintStackTrace //th.printStackTrace(); //} } } @Override public Object getData(String dataId) { return ourProject == null || ourProject.isDisposed() ? null : new TestDataProvider(ourProject).getData(dataId); } protected Sdk getProjectJDK() { return null; } @NotNull protected ModuleType getModuleType() { return EmptyModuleType.getInstance(); } /** * Creates dummy source file. One is not placed under source root so some PSI functions like resolve to external classes * may not work. Though it works significantly faster and yet can be used if you need to create some PSI structures for * test purposes * * @param fileName - name of the file to create. Extension is used to choose what PSI should be created like java, jsp, aj, xml etc. * @param text - file text. * @return dummy psi file. * @throws IncorrectOperationException * */ @NotNull protected static PsiFile createFile(@NonNls @NotNull String fileName, @NonNls @NotNull String text) throws IncorrectOperationException { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName); return PsiFileFactory.getInstance(getProject()) .createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), true, false); } @NotNull protected static PsiFile createLightFile(@NonNls @NotNull String fileName, @NotNull String text) throws IncorrectOperationException { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(fileName); return PsiFileFactory.getInstance(getProject()) .createFileFromText(fileName, fileType, text, LocalTimeCounter.currentTime(), false, false); } /** * Convenient conversion of testSomeTest -> someTest | SomeTest where testSomeTest is the name of current test. * * @param lowercaseFirstLetter - whether first letter after test should be lowercased. */ @Override protected String getTestName(boolean lowercaseFirstLetter) { String name = getName(); assertTrue("Test name should start with 'test': " + name, name.startsWith("test")); name = name.substring("test".length()); if (!name.isEmpty() && lowercaseFirstLetter && !UsefulTestCase.isAllUppercaseName(name)) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } return name; } protected static void commitDocument(@NotNull Document document) { PsiDocumentManager.getInstance(getProject()).commitDocument(document); } protected static void commitAllDocuments() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); } @Override protected CodeStyleSettings getCurrentCodeStyleSettings() { if (CodeStyleSchemes.getInstance().getCurrentScheme() == null) return new CodeStyleSettings(); return CodeStyleSettingsManager.getSettings(getProject()); } protected static Document getDocument(@NotNull PsiFile file) { return PsiDocumentManager.getInstance(getProject()).getDocument(file); } @SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext") public static synchronized void closeAndDeleteProject() { if (ourProject != null) { ApplicationManager.getApplication().assertWriteAccessAllowed(); if (!ourProject.isDisposed()) { File ioFile = new File(ourProject.getProjectFilePath()); Disposer.dispose(ourProject); if (ioFile.exists()) { File dir = ioFile.getParentFile(); if (dir.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) { FileUtil.delete(dir); } else { FileUtil.delete(ioFile); } } } ProjectManagerEx.getInstanceEx().closeAndDispose(ourProject); // project may be disposed but empty folder may still be there if (ourPathToKeep != null) { File parent = new File(ourPathToKeep).getParentFile(); if (parent.getName().startsWith(UsefulTestCase.TEMP_DIR_MARKER)) { parent.delete(); // delete only empty folders } } ourProject = null; ourPathToKeep = null; } } private static void registerShutdownHook() { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { ShutDownTracker.invokeAndWait(true, true, new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { closeAndDeleteProject(); } }); } }); } }); } private static class SimpleLightProjectDescriptor extends LightProjectDescriptor { @NotNull private final ModuleType myModuleType; @Nullable private final Sdk mySdk; SimpleLightProjectDescriptor(@NotNull ModuleType moduleType, @Nullable Sdk sdk) { myModuleType = moduleType; mySdk = sdk; } @NotNull @Override public ModuleType getModuleType() { return myModuleType; } @Nullable @Override public Sdk getSdk() { return mySdk; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleLightProjectDescriptor that = (SimpleLightProjectDescriptor)o; if (!myModuleType.equals(that.myModuleType)) return false; return areJdksEqual(that.getSdk()); } @Override public int hashCode() { return myModuleType.hashCode(); } private boolean areJdksEqual(final Sdk newSdk) { if (mySdk == null || newSdk == null) return mySdk == newSdk; final String[] myUrls = mySdk.getRootProvider().getUrls(OrderRootType.CLASSES); final String[] newUrls = newSdk.getRootProvider().getUrls(OrderRootType.CLASSES); return ContainerUtil.newHashSet(myUrls).equals(ContainerUtil.newHashSet(newUrls)); } } }
blademainer/intellij-community
platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
Java
apache-2.0
30,738
/* Copyright 2017 Goldman Sachs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kata.test; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.set.primitive.IntSet; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.factory.primitive.IntSets; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.test.Verify; import com.gs.collections.impl.tuple.Tuples; import com.gs.fw.common.mithra.MithraManager; import kata.domain.Customer; import kata.domain.CustomerFinder; import kata.domain.CustomerList; import org.junit.Assert; import org.junit.Test; public class ExercisesCrud extends AbstractMithraTest { @Override protected String[] getTestDataFilenames() { return new String[]{"testdata/data_Customer.txt"}; // Look into this file to see the test data being used } //-------------- Question 1 ------------------------------------------------------ // Get customer with a particular ID. public Customer getCustomer(int customerId) { Assert.fail("Implement this functionality to make the test pass"); return null; } @Test public void testQ1() { Customer customer = this.getCustomer(0); Assert.assertEquals("Hiro Tanaka", customer.getName()); Assert.assertEquals("JPN", customer.getCountry()); } //---------- Question 2 ----------------------------------------------------- // Get all customers from a particular country // // Quiz: At which point does mithra actually evaluate the list by going to the database? // Is it when you create the list or when you use it? // Answer: Only when you use it. This typically means when you call .get(), .iterator(), .size(), // but there are a couple other methods that will also cause the fetch query to be executed. // Feel free to experiment to see how this works public CustomerList getCustomersFrom(String country) { Assert.fail("Implement this functionality to make the test pass"); return null; } @Test public void testQ2() { CustomerList customer = getCustomersFrom("JPN"); Verify.assertSize(4, customer); } //------------ Question 3 ------------------------------------------------------ // Get all customers: // from a particular country // AND whose customer names start with particular String public CustomerList getCustomersFromACountryWhoseNamesStartWith(String country, String startWith) { Assert.fail("Implement this functionality to make the test pass"); return null; } @Test public void testQ3() { CustomerList list = getCustomersFromACountryWhoseNamesStartWith("JPN", "Yu"); list.setOrderBy(CustomerFinder.name().ascendingOrderBy().and(CustomerFinder.customerId().descendingOrderBy())); Verify.assertSize(3, list); Assert.assertEquals("Yuki Suzuki", list.get(0).getName()); Assert.assertEquals("Yuri Clark", list.get(1).getName()); Assert.assertEquals("Yusuke Sato", list.get(2).getName()); } //----------------- Question 4 ---------------------------------------------- // Add new customer and return the customer ID. // Hint! How are you going to create a new customerID? Can Mithra create it for you? // You might need to change something in the Customer.xml file. public int addNewCustomer(String name, String country) { Verify.fail("Implement this functionality to make the test pass"); return 0; } @Test public void testQ4() { Customer kenny = CustomerFinder.findOne(CustomerFinder.name().eq("Kenny Rogers")); Assert.assertNull(kenny); int newId = addNewCustomer("Kenny Rogers", "USA"); Assert.assertTrue(newId != 0); Customer newKenny = CustomerFinder.findOne(CustomerFinder.name().eq("Kenny Rogers")); Assert.assertNotNull(newKenny); Assert.assertEquals(newId, newKenny.getCustomerId()); Assert.assertEquals("USA", newKenny.getCountry()); } //------------------- Question 5 ----------------------------------------------- // Update the country of a list of Customers. // You can assume that the list is one that arrives in the <code>customers</code> parameter. public void updateCountry(CustomerList customers, String newCountry) { Assert.fail("Implement this functionality to make the test pass"); } @Test public void testQ5() { IntSet testIds = IntSets.immutable.of(1, 2); CustomerList customers = new CustomerList(CustomerFinder.customerId().in(testIds)); this.updateCountry(customers, "UK"); MithraManager.getInstance().clearAllQueryCaches(); Customer c1 = CustomerFinder.findOne(CustomerFinder.customerId().eq(1)); Customer c2 = CustomerFinder.findOne(CustomerFinder.customerId().eq(2)); //check that the two got updated Assert.assertEquals("UK", c1.getCountry()); Assert.assertEquals("UK", c2.getCountry()); //check that nobody else got updated. Verify.assertSize(2, new CustomerList(CustomerFinder.country().eq("UK"))); Verify.assertSize(3, new CustomerList(CustomerFinder.country().notEq("UK"))); } //------------------- Question 6 ----------------------------------------------- // Change the country of all customers from one value to another. public void updateCountryFromTo(String from, String to) { Assert.fail("Implement this functionality to make the test pass"); } @Test public void testQ6() { updateCountryFromTo("JPN", "JP"); CustomerList jpn = new CustomerList(CustomerFinder.country().eq("JPN")); Verify.assertSize(0, jpn); CustomerList jp = new CustomerList(CustomerFinder.country().eq("JP")); Verify.assertSize(4, jp); } //------------------- Question 7 ----------------------------------------------- // Add two customers in one go. Both will have the same country. // Because of legal requirements, either both must be added, or if there is a problem, // then neither get added. // You'll need to use a "transaction" to achieve this functionality. // Use the supplied method <code>possiblySimulateProblem(String country)</code> // as a way of sometimes simulating a "problem" occurring, by putting it // between the first and second inserts. public void addTwoCustomers(final String name1, final String name2, final String country) { Assert.fail("Implement this functionality to make the test pass"); // your code here to insert first customer possiblySimulateProblem(country); // your code here to insert second customer } private void possiblySimulateProblem(String country) { if (country.equals("XX")) { throw new RuntimeException("Simulated problem"); } } @Test public void testQ7() { int countBefore = CustomerFinder.findMany(CustomerFinder.all()).count(); Verify.assertThrows(RuntimeException.class, new Runnable() { public void run() { addTwoCustomers("Romulus", "Remus", "XX"); } }); Assert.assertEquals(countBefore, CustomerFinder.findMany(CustomerFinder.all()).count()); this.addTwoCustomers("Tweedle-Dee", "Tweedle-Dum", "DE"); Assert.assertEquals(countBefore + 2, CustomerFinder.findMany(CustomerFinder.all()).count()); } //------------------- Question 8 ----------------------------------------------- // Add new customers in a batch given {"name", "country"} pairs. // You can assume that none of the new customers exist. public void addNewCustomers(MutableList<Pair<String, String>> newCustomerInfo) { Assert.fail("Implement this functionality to make the test pass"); } @Test public void testQ8() { int sizeBefore = CustomerFinder.findMany(CustomerFinder.all()).size(); Pair<String, String> customer1 = Tuples.pair("John Courage", "UK"); Pair<String, String> customer2 = Tuples.pair("Tony Jackson", "USA"); this.addNewCustomers(FastList.newListWith(customer1, customer2)); int sizeAfter = CustomerFinder.findMany(CustomerFinder.all()).size(); Assert.assertEquals(2, sizeAfter - sizeBefore); Assert.assertNotNull(CustomerFinder.findOne(CustomerFinder.name().eq("John Courage"))); Assert.assertNotNull(CustomerFinder.findMany(CustomerFinder.name().eq("Tony Jackson"))); } //------------------- Question 9 ----------------------------------------------- // Delete a Customer given the customerId. public void deleteCustomer(int customerId) { Assert.fail("Implement this functionality to make the test pass"); } @Test public void testQ10() { int sizeBefore = CustomerFinder.findMany(CustomerFinder.all()).size(); deleteCustomer(1); int sizeAfter = CustomerFinder.findMany(CustomerFinder.all()).size(); Assert.assertEquals(-1, sizeAfter - sizeBefore); } //------------------- Question 11 ----------------------------------------------- // Delete a list of customers. // Try to do it in a batch, not one by one. public void deleteCustomers(IntSet customers) { Assert.fail("Implement this functionality to make the test pass"); } @Test public void testQ11() { int sizeBefore = CustomerFinder.findMany(CustomerFinder.all()).size(); IntSet customerIds = IntSets.immutable.of(1, 2); deleteCustomers(customerIds); int sizeAfter = CustomerFinder.findMany(CustomerFinder.all()).size(); Assert.assertEquals(-2, sizeAfter - sizeBefore); } //------------------- Question 12 ----------------------------------------------- // Add a unique index on Customer name, using Mithra. Call it "nameIndex". // Hint: This can be done in the Mithra object XML... @Test public void testQ12() { // Hard to test, since the MithraTestResource doesn't apply a "unique index" to the H2 DB for us ... try { Assert.assertNotNull(CustomerFinder.class.getDeclaredMethod("findByNameIndex", String.class)); } catch (NoSuchMethodException e) { Assert.fail("Implement a unique index on the Customer object to make this test pass"); } } //------------------- Question 13 ----------------------------------------------- // Use your new index to easily look up information given a Customers unique name. public Customer getByCustomerName(String customerName) { Assert.fail("Implement this functionality to make the test pass"); return null; } @Test public void testQ13() { Assert.assertEquals(2, this.getByCustomerName("Yusuke Sato").getCustomerId()); Assert.assertEquals(1, this.getByCustomerName("John Smith").getCustomerId()); } }
gs-rezaem/reladomo-kata
main-kata/src/test/java/kata/test/ExercisesCrud.java
Java
apache-2.0
11,542
package info.fedora.definitions._1._0.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="purged" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "purged" }) @XmlRootElement(name = "purgeRelationshipResponse") public class PurgeRelationshipResponse { protected boolean purged; /** * Gets the value of the purged property. * */ public boolean isPurged() { return purged; } /** * Sets the value of the purged property. * */ public void setPurged(boolean value) { this.purged = value; } }
DAASI/HyperImage3
hi3-editor/src/main/java/info/fedora/definitions/_1/_0/types/PurgeRelationshipResponse.java
Java
apache-2.0
1,243
// Copyright 2013 Daniel de Kok // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package eu.danieldk.dictomaton; import java.util.BitSet; /** * A finite state dictionary with perfect hashing, that puts right language cardinalities in states. * Dictionaries of this type can are constructed using * {@link eu.danieldk.dictomaton.DictionaryBuilder#buildPerfectHash()}. * * @author Daniel de Kok */ class PerfectHashDictionaryStateCard extends DictionaryImpl implements PerfectHashDictionary { private static final long serialVersionUID = 2L; private final CompactIntArray d_stateNSuffixes; /** * Compute the perfect hash code of the given character sequence. * * @param seq * @return */ public int number(CharSequence seq) { StateInfo info = getStateInfo(seq); return info.isInFinalState() ? info.getHash() : -1; } public StateInfo getStateInfo(CharSequence seq) { return getStateInfo(seq, null); } public StateInfo getStateInfo(CharSequence seq, StateInfo startInfo) { StateInfo info; if (startInfo != null) { if (!startInfo.isInKnownState()) { throw new IllegalStateException("Cannot resume transitions from unknown state. Sequence: " + seq); } info = new StateInfo(startInfo.num, startInfo.state, startInfo.trans, startInfo.inFinalState); } else { info = new StateInfo(0, 0, -1, false); } for (int i = 0; i < seq.length(); i++) { char ch = seq.charAt(i); info.trans = findTransition(info.state, ch); if (!info.isInKnownState()) { return info; } // Count the number of preceding suffixes in the preceding transitions. for (int j = d_stateOffsets.get(info.state); j < info.trans; j++) info.num += d_stateNSuffixes.get(d_transitionTo.get(j)); // A final state is another suffix. if (d_finalStates.get(info.state)) ++info.num; info.state = d_transitionTo.get(info.trans); } info.inFinalState = d_finalStates.get(info.state); return info; } /** * Compute the sequence corresponding to the given hash code. * * @param hashCode * @return */ public String sequence(int hashCode) { if (hashCode <= 0) return null; int state = 0; // If the hash code is larger than the number of suffixes in the start state, // the hash code does not correspond to a sequence. if (hashCode > d_stateNSuffixes.get(state)) return null; StringBuilder wordBuilder = new StringBuilder(); // Stop if we are in a state where we cannot add more characters. while (d_stateOffsets.get(state) != transitionsUpperBound(state)) { // Obtain the next transition, decreasing the hash code by the number of // preceding suffixes. int trans; for (trans = d_stateOffsets.get(state); trans < transitionsUpperBound(state); ++trans) { int stateNSuffixes = d_stateNSuffixes.get(d_transitionTo.get(trans)); if (hashCode - stateNSuffixes <= 0) break; hashCode -= stateNSuffixes; } // Add the character on the given transition and move. wordBuilder.append(d_transitionChars[trans]); state = d_transitionTo.get(trans); // If we encounter a final state, decrease the hash code, since it represents a // suffix. If our hash code is reduced to zero, we have found the sequence. if (d_finalStates.get(state)) { --hashCode; if (hashCode == 0) return wordBuilder.toString(); } } // Bad luck, we cannot really get here! return null; } @Override public int size() { return d_nSeqs; } /** * Give the Graphviz dot representation of this automaton. States will also list the * number of suffixes 'under' that state. * * @return */ @Override public String toDot() { StringBuilder dotBuilder = new StringBuilder(); dotBuilder.append("digraph G {\n"); for (int state = 0; state < d_stateOffsets.size(); ++state) { for (int trans = d_stateOffsets.get(state); trans < transitionsUpperBound(state); ++trans) dotBuilder.append(String.format("%d -> %d [label=\"%c\"]\n", state, d_transitionTo.get(trans), d_transitionChars[trans])); if (d_finalStates.get(state)) dotBuilder.append(String.format("%d [peripheries=2,label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); else dotBuilder.append(String.format("%d [label=\"%d (%d)\"];\n", state, state, d_stateNSuffixes.get(state))); } dotBuilder.append("}"); return dotBuilder.toString(); } /** * @see DictionaryImpl#DictionaryImpl(CompactIntArray, char[], CompactIntArray, java.util.BitSet, int) */ protected PerfectHashDictionaryStateCard(CompactIntArray stateOffsets, char[] transitionChars, CompactIntArray transitionTo, BitSet finalStates, int nSeqs) { super(stateOffsets, transitionChars, transitionTo, finalStates, nSeqs); // Marker that indicates that the number of suffixes of a state is not yet computed. We cannot // use -1, since CompactIntArray would then require 32-bit per value. final int magicMarker = nSeqs + 1; d_stateNSuffixes = new CompactIntArray(d_stateOffsets.size(), CompactIntArray.width(magicMarker)); for (int i = 0; i < d_stateNSuffixes.size(); ++i) d_stateNSuffixes.set(i, magicMarker); computeStateSuffixes(0, magicMarker); } private int computeStateSuffixes(final int state, final int magicMarker) { int suffixes = d_stateNSuffixes.get(state); if (suffixes != magicMarker) return suffixes; suffixes = d_finalStates.get(state) ? 1 : 0; for (int trans = d_stateOffsets.get(state); trans < transitionsUpperBound(state); ++trans) suffixes += computeStateSuffixes(d_transitionTo.get(trans), magicMarker); d_stateNSuffixes.set(state, suffixes); return suffixes; } }
pkoduganty/dictomaton
src/main/java/eu/danieldk/dictomaton/PerfectHashDictionaryStateCard.java
Java
apache-2.0
7,139
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.screens.dtablexls.backend.server.conversion; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import org.drools.decisiontable.parser.xls.ExcelParser; import org.drools.template.model.Global; import org.drools.template.model.Import; import org.drools.template.parser.DataListener; import org.drools.workbench.models.datamodel.rule.ActionFieldValue; import org.drools.workbench.models.datamodel.rule.ActionInsertFact; import org.drools.workbench.models.datamodel.rule.ActionRetractFact; import org.drools.workbench.models.datamodel.rule.ActionSetField; import org.drools.workbench.models.datamodel.rule.CompositeFactPattern; import org.drools.workbench.models.datamodel.rule.FactPattern; import org.drools.workbench.models.datamodel.rule.FieldNatureType; import org.drools.workbench.models.datamodel.rule.FreeFormLine; import org.drools.workbench.models.datamodel.rule.IAction; import org.drools.workbench.models.datamodel.rule.IPattern; import org.drools.workbench.models.datamodel.rule.SingleFieldConstraint; import org.drools.workbench.models.guided.dtable.shared.conversion.ConversionMessageType; import org.drools.workbench.models.guided.dtable.shared.conversion.ConversionResult; import org.drools.workbench.models.guided.dtable.shared.model.AttributeCol52; import org.drools.workbench.models.guided.dtable.shared.model.BRLActionColumn; import org.drools.workbench.models.guided.dtable.shared.model.BRLActionVariableColumn; import org.drools.workbench.models.guided.dtable.shared.model.BRLConditionColumn; import org.drools.workbench.models.guided.dtable.shared.model.BRLConditionVariableColumn; import org.drools.workbench.models.guided.dtable.shared.model.BaseColumn; import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52; import org.drools.workbench.models.guided.dtable.shared.model.DescriptionCol52; import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52; import org.drools.workbench.models.guided.dtable.shared.model.MetadataCol52; import org.drools.workbench.models.guided.dtable.shared.model.RowNumberCol52; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.soup.project.datamodel.oracle.DataType; import org.kie.soup.project.datamodel.oracle.FieldAccessorsAndMutators; import org.kie.soup.project.datamodel.oracle.ModelField; import org.kie.soup.project.datamodel.oracle.PackageDataModelOracle; import org.kie.workbench.common.services.shared.preferences.ApplicationPreferences; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for the conversion of XLS Decision Tables to Guided Decision Tables */ @RunWith(MockitoJUnitRunner.class) public class GuidedDecisionTableGeneratorListenerTest { private PackageDataModelOracle dmo; private Map<String, ModelField[]> packageModelFields = new HashMap<String, ModelField[]>(); @BeforeClass public static void setup() { setupPreferences(); setupSystemProperties(); } private static void setupPreferences() { final Map<String, String> preferences = new HashMap<String, String>() {{ put(ApplicationPreferences.DATE_FORMAT, "dd/mm/yyyy"); }}; ApplicationPreferences.setUp(preferences); } private static void setupSystemProperties() { System.setProperty("org.uberfire.nio.git.daemon.enabled", "false"); System.setProperty("org.uberfire.nio.git.ssh.enabled", "false"); System.setProperty("org.uberfire.sys.repo.monitor.disabled", "true"); } @Before public void setupMocks() throws Exception { dmo = mock(PackageDataModelOracle.class); when(dmo.getPackageName()).thenReturn("org.test"); when(dmo.getModuleModelFields()).thenReturn(packageModelFields); } @After public void cleanUp() throws Exception { packageModelFields.clear(); } @Test public void testAttributes() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("Attributes.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("AttributesTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(12, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof AttributeCol52); assertTrue(columns.get(3) instanceof AttributeCol52); assertTrue(columns.get(4) instanceof AttributeCol52); assertTrue(columns.get(5) instanceof AttributeCol52); assertTrue(columns.get(6) instanceof AttributeCol52); assertTrue(columns.get(7) instanceof AttributeCol52); assertTrue(columns.get(8) instanceof AttributeCol52); assertTrue(columns.get(9) instanceof AttributeCol52); assertTrue(columns.get(10) instanceof AttributeCol52); assertTrue(columns.get(11) instanceof AttributeCol52); //Check individual attributes AttributeCol52 attrCol2 = ((AttributeCol52) columns.get(2)); assertEquals(GuidedDecisionTable52.SALIENCE_ATTR, attrCol2.getAttribute()); assertFalse(attrCol2.isUseRowNumber()); assertFalse(attrCol2.isReverseOrder()); AttributeCol52 attrCol3 = ((AttributeCol52) columns.get(3)); assertEquals(GuidedDecisionTable52.ACTIVATION_GROUP_ATTR, attrCol3.getAttribute()); AttributeCol52 attrCol4 = ((AttributeCol52) columns.get(4)); assertEquals(GuidedDecisionTable52.DURATION_ATTR, attrCol4.getAttribute()); AttributeCol52 attrCol5 = ((AttributeCol52) columns.get(5)); assertEquals(GuidedDecisionTable52.TIMER_ATTR, attrCol5.getAttribute()); AttributeCol52 attrCol6 = ((AttributeCol52) columns.get(6)); assertEquals(GuidedDecisionTable52.CALENDARS_ATTR, attrCol6.getAttribute()); AttributeCol52 attrCol7 = ((AttributeCol52) columns.get(7)); assertEquals(GuidedDecisionTable52.NO_LOOP_ATTR, attrCol7.getAttribute()); AttributeCol52 attrCol8 = ((AttributeCol52) columns.get(8)); assertEquals(GuidedDecisionTable52.LOCK_ON_ACTIVE_ATTR, attrCol8.getAttribute()); AttributeCol52 attrCol9 = ((AttributeCol52) columns.get(9)); assertEquals(GuidedDecisionTable52.AUTO_FOCUS_ATTR, attrCol9.getAttribute()); AttributeCol52 attrCol10 = ((AttributeCol52) columns.get(10)); assertEquals(GuidedDecisionTable52.AGENDA_GROUP_ATTR, attrCol10.getAttribute()); AttributeCol52 attrCol11 = ((AttributeCol52) columns.get(11)); assertEquals(GuidedDecisionTable52.RULEFLOW_GROUP_ATTR, attrCol11.getAttribute()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Specific rule 1", 1, "g1", 100l, "T1", "CAL1", true, true, true, "AG1", "RFG1"}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Specific rule 2", 2, "g2", 200l, "T2", "CAL2", false, false, false, "AG2", "RFG2"}, dtable.getData().get(1))); } @Test public void testSequentialSalience() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("SequentialSalience.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("SequentialSalienceTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(3, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof AttributeCol52); //Check attribute column AttributeCol52 attrCol2 = ((AttributeCol52) columns.get(2)); assertEquals(GuidedDecisionTable52.SALIENCE_ATTR, attrCol2.getAttribute()); assertTrue(attrCol2.isUseRowNumber()); assertTrue(attrCol2.isReverseOrder()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Rule 1", 2}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Rule 2", 1}, dtable.getData().get(1))); } @Test public void testSalienceWarnings() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("SalienceWarnings.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(2, result.getMessages().size()); assertEquals(ConversionMessageType.WARNING, result.getMessages().get(0).getMessageType()); assertFalse(result.getMessages().get(0).getMessage().indexOf("Priority is not an integer literal, in cell C7") == -1); assertEquals(ConversionMessageType.WARNING, result.getMessages().get(1).getMessageType()); assertFalse(result.getMessages().get(1).getMessage().indexOf("Priority is not an integer literal, in cell C8") == -1); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("SalienceWarningsTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(3, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof AttributeCol52); //Check attribute column AttributeCol52 attrCol2 = ((AttributeCol52) columns.get(2)); assertEquals(GuidedDecisionTable52.SALIENCE_ATTR, attrCol2.getAttribute()); assertFalse(attrCol2.isUseRowNumber()); assertFalse(attrCol2.isReverseOrder()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Rule 1", 0}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Rule 2", 0}, dtable.getData().get(1))); } @Test public void testDurationWarnings() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("DurationWarnings.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(2, result.getMessages().size()); assertEquals(ConversionMessageType.WARNING, result.getMessages().get(0).getMessageType()); assertFalse(result.getMessages().get(0).getMessage().indexOf("Duration is not an long literal, in cell C7") == -1); assertEquals(ConversionMessageType.WARNING, result.getMessages().get(1).getMessageType()); assertFalse(result.getMessages().get(1).getMessage().indexOf("Duration is not an long literal, in cell C8") == -1); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("DurationWarningsTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(3, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof AttributeCol52); //Check attribute column AttributeCol52 attrCol2 = ((AttributeCol52) columns.get(2)); assertEquals(GuidedDecisionTable52.DURATION_ATTR, attrCol2.getAttribute()); assertFalse(attrCol2.isUseRowNumber()); assertFalse(attrCol2.isReverseOrder()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Rule 1", 0}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Rule 2", 0}, dtable.getData().get(1))); } @Test public void testMetadata() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("Metadata.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("MetadataTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(3, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof MetadataCol52); //Check metadata column MetadataCol52 mdCol2 = ((MetadataCol52) columns.get(2)); assertEquals("cheese", mdCol2.getMetadata()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Rule 1", "cheddar"}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Rule 2", "edam"}, dtable.getData().get(1))); } @Test //https://bugzilla.redhat.com/show_bug.cgi?id=1310208 public void testGlobalsConversion() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("BZ1310208.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<Global> globals = listener.getGlobals(); assertNotNull(globals); assertEquals(1, globals.size()); final Global global = globals.get(0); assertEquals("list", global.getIdentifier()); assertEquals("List", global.getClassName()); } @Test public void testActions() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("Actions.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("ActionsTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(7, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLActionVariableColumn); assertTrue(columns.get(3) instanceof BRLActionVariableColumn); assertTrue(columns.get(4) instanceof BRLActionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); assertTrue(columns.get(6) instanceof BRLActionVariableColumn); //Check individual action columns assertEquals(4, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); assertTrue(dtable.getActionCols().get(1) instanceof BRLActionColumn); assertTrue(dtable.getActionCols().get(2) instanceof BRLActionColumn); assertTrue(dtable.getActionCols().get(3) instanceof BRLActionColumn); //Column 1 BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Multi-parameters', 'Multi-parameters']", actionCol0.getHeader()); assertEquals(2, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl = (FreeFormLine) actionCol0definition.get(0); assertEquals("policy.setBasePrice(@{param1}, @{param2});", actionCol0ffl.getText()); //Column 1 - Variable 1 BRLActionVariableColumn actionCol0param0 = actionCol0.getChildColumns().get(0); assertEquals("param1", actionCol0param0.getVarName()); assertEquals("Multi-parameters", actionCol0param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol0param0.getFieldType()); assertNull(actionCol0param0.getFactType()); assertNull(actionCol0param0.getFactField()); //Column 1 - Variable 2 BRLActionVariableColumn actionCol0param1 = actionCol0.getChildColumns().get(1); assertEquals("param2", actionCol0param1.getVarName()); assertEquals("Multi-parameters", actionCol0param1.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol0param1.getFieldType()); assertNull(actionCol0param1.getFactType()); assertNull(actionCol0param1.getFactField()); //Column 2 BRLActionColumn actionCol1 = ((BRLActionColumn) dtable.getActionCols().get(1)); assertEquals("Converted from ['Single-parameter']", actionCol1.getHeader()); assertEquals(1, actionCol1.getChildColumns().size()); List<IAction> actionCol1definition = actionCol1.getDefinition(); assertEquals(1, actionCol1definition.size()); assertTrue(actionCol1definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol1ffl = (FreeFormLine) actionCol1definition.get(0); assertEquals("policy.setSmurf(@{param3});", actionCol1ffl.getText()); //Column 2 - Variable 1 BRLActionVariableColumn actionCol1param0 = actionCol1.getChildColumns().get(0); assertEquals("param3", actionCol1param0.getVarName()); assertEquals("Single-parameter", actionCol1param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol1param0.getFieldType()); assertNull(actionCol1param0.getFactType()); assertNull(actionCol1param0.getFactField()); //Column 3 BRLActionColumn actionCol2 = ((BRLActionColumn) dtable.getActionCols().get(2)); assertEquals("Converted from ['Log-single-parameter']", actionCol2.getHeader()); assertEquals(1, actionCol2.getChildColumns().size()); List<IAction> actionCol2definition = actionCol2.getDefinition(); assertEquals(1, actionCol2definition.size()); assertTrue(actionCol2definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol2ffl = (FreeFormLine) actionCol2definition.get(0); assertEquals("System.out.println(\"@{param4}\");", actionCol2ffl.getText()); //Column 3 - Variable 1 BRLActionVariableColumn actionCol2param0 = actionCol2.getChildColumns().get(0); assertEquals("param4", actionCol2param0.getVarName()); assertEquals("Log-single-parameter", actionCol2param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol2param0.getFieldType()); assertNull(actionCol2param0.getFactType()); assertNull(actionCol2param0.getFactField()); //Column 4 BRLActionColumn actionCol3 = ((BRLActionColumn) dtable.getActionCols().get(3)); assertEquals("Converted from ['Zero-parameters']", actionCol3.getHeader()); assertEquals(1, actionCol3.getChildColumns().size()); List<IAction> actionCol3definition = actionCol3.getDefinition(); assertEquals(1, actionCol3definition.size()); assertTrue(actionCol3definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol3ffl = (FreeFormLine) actionCol3definition.get(0); assertEquals("System.out.println(\"Woot\");", actionCol3ffl.getText()); //Column 3 - Variable 1 BRLActionVariableColumn actionCol3param0 = actionCol3.getChildColumns().get(0); assertEquals("", actionCol3param0.getVarName()); assertEquals("Zero-parameters", actionCol3param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, actionCol3param0.getFieldType()); assertNull(actionCol3param0.getFactType()); assertNull(actionCol3param0.getFactField()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Row 1", "10", "20", "30", "hello", true}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Row 2", "50", "60", "70", "goodbye", false}, dtable.getData().get(1))); } @Test public void testConditions() { final List<Object[]> expectedRows = new ArrayList<Object[]>(2); expectedRows.add(new Object[]{1, "Row 1", 20, "Mike", "Brown", "BMW", "M3"}); expectedRows.add(new Object[]{2, "Row 2", 30, "Jason", "Grey", "Audi", "S4"}); conditionsTest("Conditions.xls", expectedRows); } @Test public void testConditionsIndexedParameters() { final List<Object[]> expectedRows = new ArrayList<Object[]>(2); expectedRows.add(new Object[]{1, "Row 1", 20, "Mike", "Brown", "BMW", "M3"}); expectedRows.add(new Object[]{2, "Row 2", 30, "Jason", "Grey", "", ""}); conditionsTest("Conditions-indexedParameters.xls", expectedRows); } private void conditionsTest(final String xlsFileName, final List<Object[]> expectedRows) { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); addModelField("org.test.Driver", "this", "org.test.Driver", DataType.TYPE_THIS); addModelField("org.test.Driver", "age", Integer.class.getName(), DataType.TYPE_NUMERIC_INTEGER); addModelField("org.test.Driver", "firstName", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Driver", "surname", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "this", "org.test.Vehicle", DataType.TYPE_THIS); addModelField("org.test.Vehicle", "make", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "model", String.class.getName(), DataType.TYPE_STRING); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream(xlsFileName); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("ConditionsTest", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(7, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLConditionVariableColumn); assertTrue(columns.get(6) instanceof BRLConditionVariableColumn); //Check individual condition columns assertEquals(2, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); assertTrue(dtable.getConditions().get(1) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Age of driver', 'First name', 'Surname']", conditionCol0.getHeader()); assertEquals(3, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Driver", conditionCol0fp.getFactType()); assertEquals(3, conditionCol0fp.getNumberOfConstraints()); assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("age", conditionCol0fpsfc0.getFieldName()); assertEquals(">", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc0.getFieldType()); assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("firstName", conditionCol0fpsfc1.getFieldName()); assertEquals("==", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc1.getFieldType()); assertTrue(conditionCol0fp.getConstraint(2) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc2 = (SingleFieldConstraint) conditionCol0fp.getConstraint(2); assertEquals("surname", conditionCol0fpsfc2.getFieldName()); assertEquals("==", conditionCol0fpsfc2.getOperator()); assertEquals("param3", conditionCol0fpsfc2.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc2.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc2.getFieldType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Age of driver", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param0.getFieldType()); assertEquals("Driver", conditionCol0param0.getFactType()); assertEquals("age", conditionCol0param0.getFactField()); //Column 1 - Variable 2 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("First name", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param1.getFieldType()); assertEquals("Driver", conditionCol0param1.getFactType()); assertEquals("firstName", conditionCol0param1.getFactField()); //Column 1 - Variable 3 BRLConditionVariableColumn conditionCol0param2 = conditionCol0.getChildColumns().get(2); assertEquals("param3", conditionCol0param2.getVarName()); assertEquals("Surname", conditionCol0param2.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param2.getFieldType()); assertEquals("Driver", conditionCol0param2.getFactType()); assertEquals("surname", conditionCol0param2.getFactField()); //Column 2 BRLConditionColumn conditionCol1 = ((BRLConditionColumn) dtable.getConditions().get(1)); assertEquals("Converted from ['something', 'something']", conditionCol1.getHeader()); assertEquals(2, conditionCol1.getChildColumns().size()); List<IPattern> conditionCol1definition = conditionCol1.getDefinition(); assertEquals(1, conditionCol1definition.size()); assertTrue(conditionCol1definition.get(0) instanceof FactPattern); FactPattern conditionCol1fp = (FactPattern) conditionCol1definition.get(0); assertEquals("Vehicle", conditionCol1fp.getFactType()); assertEquals(2, conditionCol1fp.getNumberOfConstraints()); assertTrue(conditionCol1fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol1fpsfc0 = (SingleFieldConstraint) conditionCol1fp.getConstraint(0); assertEquals("make", conditionCol1fpsfc0.getFieldName()); assertEquals("==", conditionCol1fpsfc0.getOperator()); assertEquals("param4", conditionCol1fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol1fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol1fpsfc0.getFieldType()); assertTrue(conditionCol1fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol1fpsfc1 = (SingleFieldConstraint) conditionCol1fp.getConstraint(1); assertEquals("model", conditionCol1fpsfc1.getFieldName()); assertEquals("==", conditionCol1fpsfc1.getOperator()); assertEquals("param5", conditionCol1fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol1fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol1fpsfc1.getFieldType()); //Column 2 - Variable 1 BRLConditionVariableColumn conditionCol1param0 = conditionCol1.getChildColumns().get(0); assertEquals("param4", conditionCol1param0.getVarName()); assertEquals("something", conditionCol1param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol1param0.getFieldType()); assertEquals("Vehicle", conditionCol1param0.getFactType()); assertEquals("make", conditionCol1param0.getFactField()); //Column 2 - Variable 2 BRLConditionVariableColumn conditionCol1param1 = conditionCol1.getChildColumns().get(1); assertEquals("param5", conditionCol1param1.getVarName()); assertEquals("something", conditionCol1param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol1param1.getFieldType()); assertEquals("Vehicle", conditionCol1param1.getFactType()); assertEquals("model", conditionCol1param1.getFactField()); //Check data assertEquals(2, dtable.getData().size()); assertNotNull(expectedRows); assertTrue(expectedRows.size() == 2); for (int i = 0; i < 2; i++) { assertTrue(isRowEquivalent(expectedRows.get(i), dtable.getData().get(i))); } } @Test public void testMultipleRuleTables() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("MultipleRuleTables.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(2, dtables.size()); GuidedDecisionTable52 dtable0 = dtables.get(0); assertEquals("Table1", dtable0.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable0.getTableFormat()); GuidedDecisionTable52 dtable1 = dtables.get(1); assertEquals("Table2", dtable1.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable1.getTableFormat()); //Check expanded columns List<BaseColumn> columns0 = dtable0.getExpandedColumns(); assertNotNull(columns0); assertEquals(5, columns0.size()); assertTrue(columns0.get(0) instanceof RowNumberCol52); assertTrue(columns0.get(1) instanceof DescriptionCol52); assertTrue(columns0.get(2) instanceof AttributeCol52); assertTrue(columns0.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns0.get(4) instanceof BRLActionVariableColumn); AttributeCol52 attrCol0_2 = ((AttributeCol52) columns0.get(2)); assertEquals(GuidedDecisionTable52.AGENDA_GROUP_ATTR, attrCol0_2.getAttribute()); //Check individual condition columns assertEquals(1, dtable0.getConditions().size()); assertTrue(dtable0.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0_0 = ((BRLConditionColumn) dtable0.getConditions().get(0)); assertEquals("Converted from ['Person's name']", conditionCol0_0.getHeader()); assertEquals(1, conditionCol0_0.getChildColumns().size()); List<IPattern> conditionCol0_0definition = conditionCol0_0.getDefinition(); assertEquals(1, conditionCol0_0definition.size()); assertTrue(conditionCol0_0definition.get(0) instanceof FactPattern); FactPattern conditionCol0_0fp = (FactPattern) conditionCol0_0definition.get(0); assertEquals("Person", conditionCol0_0fp.getFactType()); assertEquals(1, conditionCol0_0fp.getNumberOfConstraints()); assertTrue(conditionCol0_0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0_0fpsfc0 = (SingleFieldConstraint) conditionCol0_0fp.getConstraint(0); assertEquals("name", conditionCol0_0fpsfc0.getFieldName()); assertEquals("==", conditionCol0_0fpsfc0.getOperator()); assertEquals("param1", conditionCol0_0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0_0fpsfc0.getConstraintValueType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0_0param0 = conditionCol0_0.getChildColumns().get(0); assertEquals("param1", conditionCol0_0param0.getVarName()); assertEquals("Person's name", conditionCol0_0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0_0param0.getFieldType()); assertEquals("Person", conditionCol0_0param0.getFactType()); assertEquals("name", conditionCol0_0param0.getFactField()); //Column 2 BRLActionColumn actionCol0_0 = ((BRLActionColumn) dtable0.getActionCols().get(0)); assertEquals("Converted from ['Salutation']", actionCol0_0.getHeader()); assertEquals(1, actionCol0_0.getChildColumns().size()); List<IAction> actionCol0_0definition = actionCol0_0.getDefinition(); assertEquals(1, actionCol0_0definition.size()); assertTrue(actionCol0_0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0_0ffl = (FreeFormLine) actionCol0_0definition.get(0); assertEquals("System.out.println(\"@{param2}\");", actionCol0_0ffl.getText()); //Column 1 - Variable 1 BRLActionVariableColumn actionCol0_0param0 = actionCol0_0.getChildColumns().get(0); assertEquals("param2", actionCol0_0param0.getVarName()); assertEquals("Salutation", actionCol0_0param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol0_0param0.getFieldType()); assertNull(actionCol0_0param0.getFactType()); assertNull(actionCol0_0param0.getFactField()); //Check data assertEquals(2, dtable0.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Created from row 7", "AG1", "John", "Hello Sir"}, dtable0.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Row 2", "AG2", "Jane", "Hello Madam"}, dtable0.getData().get(1))); //Check expanded columns List<BaseColumn> columns1 = dtable1.getExpandedColumns(); assertNotNull(columns1); assertEquals(4, columns1.size()); assertTrue(columns1.get(0) instanceof RowNumberCol52); assertTrue(columns1.get(1) instanceof DescriptionCol52); assertTrue(columns1.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns1.get(3) instanceof BRLConditionVariableColumn); //Check individual condition columns assertEquals(1, dtable0.getConditions().size()); assertTrue(dtable0.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol1_0 = ((BRLConditionColumn) dtable1.getConditions().get(0)); assertEquals("Converted from ['Person’s name', 'Person’s age']", conditionCol1_0.getHeader()); assertEquals(2, conditionCol1_0.getChildColumns().size()); List<IPattern> conditionCol1_0definition = conditionCol1_0.getDefinition(); assertEquals(1, conditionCol1_0definition.size()); assertTrue(conditionCol1_0definition.get(0) instanceof FactPattern); FactPattern conditionCol1_0fp = (FactPattern) conditionCol1_0definition.get(0); assertEquals("Person", conditionCol1_0fp.getFactType()); assertEquals(2, conditionCol1_0fp.getNumberOfConstraints()); assertTrue(conditionCol1_0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol1_0fpsfc0 = (SingleFieldConstraint) conditionCol1_0fp.getConstraint(0); assertEquals("name", conditionCol1_0fpsfc0.getFieldName()); assertEquals("==", conditionCol1_0fpsfc0.getOperator()); assertEquals("param1", conditionCol1_0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol1_0fpsfc0.getConstraintValueType()); assertTrue(conditionCol1_0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol1_0fpsfc1 = (SingleFieldConstraint) conditionCol1_0fp.getConstraint(1); assertEquals("age", conditionCol1_0fpsfc1.getFieldName()); assertEquals("==", conditionCol1_0fpsfc1.getOperator()); assertEquals("param2", conditionCol1_0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol1_0fpsfc1.getConstraintValueType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol1_0param0 = conditionCol1_0.getChildColumns().get(0); assertEquals("param1", conditionCol1_0param0.getVarName()); assertEquals("Person’s name", conditionCol1_0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol1_0param0.getFieldType()); assertEquals("Person", conditionCol1_0param0.getFactType()); assertEquals("name", conditionCol1_0param0.getFactField()); //Column 1 - Variable 2 BRLConditionVariableColumn conditionCol1_0param1 = conditionCol1_0.getChildColumns().get(1); assertEquals("param2", conditionCol1_0param1.getVarName()); assertEquals("Person’s age", conditionCol1_0param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol1_0param1.getFieldType()); assertEquals("Person", conditionCol1_0param1.getFactType()); assertEquals("age", conditionCol1_0param1.getFactField()); //Check data assertEquals(2, dtable1.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Row 1", "John", "25"}, dtable1.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Created from row 16", "Jane", "29"}, dtable1.getData().get(1))); } @Test public void testMultipleSingleParameters() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("MultipleSingleParameters.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("MultipleSingleParameters", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(3, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Re-using single parameter']", conditionCol0.getHeader()); assertEquals(1, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine conditionCol0ffl = (FreeFormLine) conditionCol0definition.get(0); assertEquals("Driver(@{param1} != null, @{param1} == true)", conditionCol0ffl.getText()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Re-using single parameter", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, conditionCol0param0.getFieldType()); assertNull(conditionCol0param0.getFactType()); assertNull(conditionCol0param0.getFactField()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Row 1", "isQualified"}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Row 2", "isLicensed"}, dtable.getData().get(1))); } @Test public void testProperties() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("Properties.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check properties List<String> functions = listener.getFunctions(); assertNotNull(functions); assertEquals(1, functions.size()); assertEquals("function a() { }", functions.get(0)); List<Global> globals = listener.getGlobals(); assertNotNull(globals); assertEquals(1, globals.size()); assertEquals("java.util.List", globals.get(0).getClassName()); assertEquals("list", globals.get(0).getIdentifier()); List<Import> imports = listener.getImports(); assertNotNull(imports); assertEquals(2, imports.size()); assertEquals("org.yourco.model.*", imports.get(0).getClassName()); assertEquals("java.util.Date", imports.get(1).getClassName()); List<String> queries = listener.getQueries(); assertNotNull(queries); assertEquals(1, queries.size()); assertEquals("A query", queries.get(0)); List<String> types = listener.getTypeDeclarations(); assertNotNull(types); assertEquals(1, types.size()); assertEquals("declare Smurf name : String end", types.get(0)); } @Test //https://issues.jboss.org/browse/GUVNOR-2188 public void testTestNonExistentCellsFromPOI() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("GUVNOR-2188.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); final GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("IdentifyMetadataRules", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(6, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Ingest Path', 'Court Id', 'Artifact Metadata Identified']", conditionCol0.getHeader()); assertEquals(3, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("IdentifyMetadataArtifact", conditionCol0fp.getFactType()); assertEquals(3, conditionCol0fp.getNumberOfConstraints()); assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("ingestPath", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc0.getFieldType()); assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("courtId", conditionCol0fpsfc1.getFieldName()); assertEquals("==", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc1.getFieldType()); assertTrue(conditionCol0fp.getConstraint(2) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc2 = (SingleFieldConstraint) conditionCol0fp.getConstraint(2); assertEquals("artifactMetadataIdentified", conditionCol0fpsfc2.getFieldName()); assertEquals("==", conditionCol0fpsfc2.getOperator()); assertEquals("param3", conditionCol0fpsfc2.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc2.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc2.getFieldType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Ingest Path", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param0.getFieldType()); assertEquals("IdentifyMetadataArtifact", conditionCol0param0.getFactType()); assertEquals("ingestPath", conditionCol0param0.getFactField()); //Column 1 - Variable 2 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("Court Id", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param1.getFieldType()); assertEquals("IdentifyMetadataArtifact", conditionCol0param1.getFactType()); assertEquals("courtId", conditionCol0param1.getFactField()); //Column 1 - Variable 3 BRLConditionVariableColumn conditionCol0param2 = conditionCol0.getChildColumns().get(2); assertEquals("param3", conditionCol0param2.getVarName()); assertEquals("Artifact Metadata Identified", conditionCol0param2.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param2.getFieldType()); assertEquals("IdentifyMetadataArtifact", conditionCol0param2.getFactType()); assertEquals("artifactMetadataIdentified", conditionCol0param2.getFactField()); //Check individual action columns assertEquals(1, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Column 2 BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Identify Metadata Required']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof ActionSetField); ActionSetField actionCol0asf = (ActionSetField) actionCol0definition.get(0); assertEquals("fact1", actionCol0asf.getVariable()); assertEquals(1, actionCol0asf.getFieldValues().length); ActionFieldValue actionCol0asf_afv0 = actionCol0asf.getFieldValues()[0]; assertEquals("identifiedMetadataRequired", actionCol0asf_afv0.getField()); assertEquals("param4", actionCol0asf_afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol0asf_afv0.getNature()); assertEquals(DataType.TYPE_STRING, actionCol0asf_afv0.getType()); } @Test //https://issues.jboss.org/browse/GUVNOR-2030 public void testMissingTemplateKeyValues_StringFields() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("GUVNOR-2030.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("asd", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(6, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Rule disabler', 'CovenanteeId', 'blah']", conditionCol0.getHeader()); assertEquals(3, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Transaction", conditionCol0fp.getFactType()); assertEquals(3, conditionCol0fp.getNumberOfConstraints()); assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("isDisabled(\"asd\")", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals("java.lang.String", conditionCol0fpsfc0.getFieldType()); assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("getClientCovenanteeId()", conditionCol0fpsfc1.getFieldName()); assertEquals("==", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals("java.lang.String", conditionCol0fpsfc1.getFieldType()); assertTrue(conditionCol0fp.getConstraint(2) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc2 = (SingleFieldConstraint) conditionCol0fp.getConstraint(2); assertEquals("isBlacklisted(\"asd\")", conditionCol0fpsfc2.getFieldName()); assertEquals("==", conditionCol0fpsfc2.getOperator()); assertEquals("param3", conditionCol0fpsfc2.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc2.getConstraintValueType()); assertEquals("java.lang.String", conditionCol0fpsfc2.getFieldType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Rule disabler", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param0.getFieldType()); assertEquals("java.lang.String", conditionCol0param0.getFactType()); assertEquals("isDisabled(\"asd\")", conditionCol0param0.getFactField()); //Column 1 - Variable 2 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("CovenanteeId", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param1.getFieldType()); assertEquals("java.lang.String", conditionCol0param1.getFactType()); assertEquals("getClientCovenanteeId()", conditionCol0param1.getFactField()); //Column 1 - Variable 3 BRLConditionVariableColumn conditionCol0param2 = conditionCol0.getChildColumns().get(2); assertEquals("param3", conditionCol0param2.getVarName()); assertEquals("blah", conditionCol0param2.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param2.getFieldType()); assertEquals("java.lang.String", conditionCol0param2.getFactType()); assertEquals("isBlacklisted(\"asd\")", conditionCol0param2.getFactField()); //Check individual action columns assertEquals(1, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Column 2 BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Risk level']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl = (FreeFormLine) actionCol0definition.get(0); assertEquals("riskIndex.setRisk(\"asd\", @{param4});", actionCol0ffl.getText()); //Check data assertEquals(1, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "asd", "false", "", "true", "0"}, dtable.getData().get(0))); } @Test public void testRowDescriptions() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("MultipleRuleTables.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(2, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals(2, dtable.getData().size()); assertEquals("Created from row 7", dtable.getData().get(0).get(1).getStringValue()); assertEquals("Row 2", dtable.getData().get(1).get(1).getStringValue()); dtable = dtables.get(1); assertEquals(2, dtable.getData().size()); assertEquals("Row 1", dtable.getData().get(0).get(1).getStringValue()); assertEquals("Created from row 16", dtable.getData().get(1).get(1).getStringValue()); } @Test //https://issues.jboss.org/browse/GUVNOR-2030 public void testMissingTemplateKeyValues_NonStringFields() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); addModelField("org.test.Client", "this", "org.test.Client", DataType.TYPE_THIS); addModelField("org.test.Client", "monthlyTransactions", Integer.class.getName(), DataType.TYPE_NUMERIC_INTEGER); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("GUVNOR-2030 (DecisionTable).xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("Steps", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(5, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['From', 'To']", conditionCol0.getHeader()); assertEquals(2, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Client", conditionCol0fp.getFactType()); assertEquals(2, conditionCol0fp.getNumberOfConstraints()); assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("monthlyTransactions", conditionCol0fpsfc0.getFieldName()); assertEquals(">=", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc0.getFieldType()); assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("monthlyTransactions", conditionCol0fpsfc1.getFieldName()); assertEquals("<=", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc1.getFieldType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("From", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param0.getFieldType()); assertEquals("Client", conditionCol0param0.getFactType()); assertEquals("monthlyTransactions", conditionCol0param0.getFactField()); //Column 1 - Variable 2 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("To", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param1.getFieldType()); assertEquals("Client", conditionCol0param1.getFactType()); assertEquals("monthlyTransactions", conditionCol0param1.getFactField()); //Check individual action columns assertEquals(1, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Column 2 BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Step']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl = (FreeFormLine) actionCol0definition.get(0); assertEquals("if (!$c.isPricingStepCustom() && ($c.getPricingStep() == null || $c.getPricingStep().compareTo(\"@{param3}\") < 0)) { modify($c) { setPricingStep(\"@{param3}\"); } };", actionCol0ffl.getText()); //Check data assertEquals(1, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Created from row 12", 0, 100, "A1"}, dtable.getData().get(0))); } @Test //https://issues.jboss.org/browse/GUVNOR-2030 public void testMissingTemplateKeyValues_RHSInsertThenUpdate() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); addModelField("org.test.Transaction", "this", "org.test.Transaction", DataType.TYPE_THIS); addModelField("org.test.Transaction", "enabled", Boolean.class.getName(), DataType.TYPE_BOOLEAN); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("GUVNOR-2030 (RHS insert then update).xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("asd", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(6, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLActionVariableColumn); assertTrue(columns.get(4) instanceof BRLActionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); //Column 1 BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Disabled']", conditionCol0.getHeader()); assertEquals(1, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Transaction", conditionCol0fp.getFactType()); assertEquals(1, conditionCol0fp.getNumberOfConstraints()); assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("enabled", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_BOOLEAN, conditionCol0fpsfc0.getFieldType()); //Column 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Disabled", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, conditionCol0param0.getFieldType()); assertEquals("Transaction", conditionCol0param0.getFactType()); assertEquals("enabled", conditionCol0param0.getFactField()); //Check individual action columns assertEquals(3, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Column 2 BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Enable']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof ActionSetField); ActionSetField actionCol0asf0 = (ActionSetField) actionCol0definition.get(0); assertEquals("$t", actionCol0asf0.getVariable()); ActionFieldValue[] actionCol0asf0afvs = actionCol0asf0.getFieldValues(); assertEquals(1, actionCol0asf0afvs.length); ActionFieldValue actionCol0asf0afv0 = actionCol0asf0afvs[0]; assertEquals("enabled", actionCol0asf0afv0.getField()); assertEquals("param2", actionCol0asf0afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol0asf0afv0.getNature()); assertEquals(DataType.TYPE_BOOLEAN, actionCol0asf0afv0.getType()); //Column 3 BRLActionColumn actionCol1 = ((BRLActionColumn) dtable.getActionCols().get(1)); assertEquals("Converted from ['New']", actionCol1.getHeader()); assertEquals(1, actionCol1.getChildColumns().size()); List<IAction> actionCol1definition = actionCol1.getDefinition(); assertEquals(1, actionCol1definition.size()); assertTrue(actionCol1definition.get(0) instanceof ActionInsertFact); ActionInsertFact actionCol1aif0 = (ActionInsertFact) actionCol1definition.get(0); assertEquals("$t2", actionCol1aif0.getBoundName()); assertEquals("Transaction", actionCol1aif0.getFactType()); ActionFieldValue[] actionCol1aif0afvs = actionCol1aif0.getFieldValues(); assertEquals(0, actionCol1aif0afvs.length); //Column 4 BRLActionColumn actionCol2 = ((BRLActionColumn) dtable.getActionCols().get(2)); assertEquals("Converted from ['Disable']", actionCol2.getHeader()); assertEquals(1, actionCol2.getChildColumns().size()); List<IAction> actionCol2definition = actionCol2.getDefinition(); assertEquals(1, actionCol2definition.size()); assertTrue(actionCol2definition.get(0) instanceof ActionSetField); ActionSetField actionCol2asf0 = (ActionSetField) actionCol2definition.get(0); assertEquals("$t2", actionCol2asf0.getVariable()); ActionFieldValue[] actionCol2asf0afvs = actionCol2asf0.getFieldValues(); assertEquals(1, actionCol2asf0afvs.length); ActionFieldValue actionCol2asf0afv0 = actionCol2asf0afvs[0]; assertEquals("enabled", actionCol2asf0afv0.getField()); assertEquals("param3", actionCol2asf0afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol2asf0afv0.getNature()); assertEquals(DataType.TYPE_BOOLEAN, actionCol2asf0afv0.getType()); //Check data assertEquals(1, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "asd", false, true, false, false}, dtable.getData().get(0))); } @Test //https://bugzilla.redhat.com/show_bug.cgi?id=1256623 public void testEmptyCells() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<DataListener>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("EmptySpreadsheetCells.xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); final GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("ExceptionPrivateCar", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(20, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof AttributeCol52); assertTrue(columns.get(3) instanceof AttributeCol52); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLConditionVariableColumn); assertTrue(columns.get(6) instanceof BRLConditionVariableColumn); assertTrue(columns.get(7) instanceof BRLConditionVariableColumn); assertTrue(columns.get(8) instanceof BRLConditionVariableColumn); assertTrue(columns.get(9) instanceof BRLConditionVariableColumn); assertTrue(columns.get(10) instanceof BRLConditionVariableColumn); assertTrue(columns.get(11) instanceof BRLConditionVariableColumn); assertTrue(columns.get(12) instanceof BRLConditionVariableColumn); assertTrue(columns.get(13) instanceof BRLConditionVariableColumn); assertTrue(columns.get(14) instanceof BRLConditionVariableColumn); assertTrue(columns.get(15) instanceof BRLConditionVariableColumn); assertTrue(columns.get(16) instanceof BRLConditionVariableColumn); assertTrue(columns.get(17) instanceof BRLConditionVariableColumn); assertTrue(columns.get(18) instanceof BRLConditionVariableColumn); assertTrue(columns.get(19) instanceof BRLActionVariableColumn); } @Test //https://issues.jboss.org/browse/RHBPMS-856 public void correctMergedConditionColumnHeaders() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); addModelField("org.test.Vehicle", "this", "org.test.Vehicle", DataType.TYPE_THIS); addModelField("org.test.Vehicle", "subRTO", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "manufacturer", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "model", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "vehicleSegment", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Vehicle", "vehicleAge", Integer.class.getName(), DataType.TYPE_NUMERIC_INTEGER); addModelField("org.test.Vehicle", "discount", Double.class.getName(), DataType.TYPE_NUMERIC_DOUBLE); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("RHBPMS-856 (Merged condition columns).xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("VehiclePremiumDiscount", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(9, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLConditionVariableColumn); assertTrue(columns.get(6) instanceof BRLConditionVariableColumn); assertTrue(columns.get(7) instanceof BRLConditionVariableColumn); assertTrue(columns.get(8) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['RTO', 'Manufacturer', 'Model', 'Segment', 'Age Min', 'Age Max']", conditionCol0.getHeader()); assertEquals(6, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Vehicle", conditionCol0fp.getFactType()); assertEquals(6, conditionCol0fp.getNumberOfConstraints()); //Field Constraint 1 assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("subRTO", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc0.getFieldType()); //Field Constraint 2 assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("manufacturer", conditionCol0fpsfc1.getFieldName()); assertEquals("==", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc1.getFieldType()); //Field Constraint 3 assertTrue(conditionCol0fp.getConstraint(2) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc2 = (SingleFieldConstraint) conditionCol0fp.getConstraint(2); assertEquals("model", conditionCol0fpsfc2.getFieldName()); assertEquals("==", conditionCol0fpsfc2.getOperator()); assertEquals("param3", conditionCol0fpsfc2.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc2.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc2.getFieldType()); //Field Constraint 4 assertTrue(conditionCol0fp.getConstraint(3) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc3 = (SingleFieldConstraint) conditionCol0fp.getConstraint(3); assertEquals("vehicleSegment", conditionCol0fpsfc3.getFieldName()); assertEquals("==", conditionCol0fpsfc3.getOperator()); assertEquals("param4", conditionCol0fpsfc3.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc3.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc3.getFieldType()); //Field Constraint 5 assertTrue(conditionCol0fp.getConstraint(4) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc4 = (SingleFieldConstraint) conditionCol0fp.getConstraint(4); assertEquals("vehicleAge", conditionCol0fpsfc4.getFieldName()); assertEquals("<=", conditionCol0fpsfc4.getOperator()); assertEquals("param5", conditionCol0fpsfc4.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc4.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc4.getFieldType()); //Field Constraint 6 assertTrue(conditionCol0fp.getConstraint(5) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc5 = (SingleFieldConstraint) conditionCol0fp.getConstraint(5); assertEquals("vehicleAge", conditionCol0fpsfc5.getFieldName()); assertEquals(">", conditionCol0fpsfc5.getOperator()); assertEquals("param6", conditionCol0fpsfc5.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc5.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc5.getFieldType()); //Field Constraint 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("RTO", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param0.getFieldType()); assertEquals("Vehicle", conditionCol0param0.getFactType()); assertEquals("subRTO", conditionCol0param0.getFactField()); //Field Constraint 2 - Variable 2 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("Manufacturer", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param1.getFieldType()); assertEquals("Vehicle", conditionCol0param1.getFactType()); assertEquals("manufacturer", conditionCol0param1.getFactField()); //Field Constraint 3 - Variable 3 BRLConditionVariableColumn conditionCol0param2 = conditionCol0.getChildColumns().get(2); assertEquals("param3", conditionCol0param2.getVarName()); assertEquals("Model", conditionCol0param2.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param2.getFieldType()); assertEquals("Vehicle", conditionCol0param2.getFactType()); assertEquals("model", conditionCol0param2.getFactField()); //Field Constraint 4 - Variable 4 BRLConditionVariableColumn conditionCol0param3 = conditionCol0.getChildColumns().get(3); assertEquals("param4", conditionCol0param3.getVarName()); assertEquals("Segment", conditionCol0param3.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param3.getFieldType()); assertEquals("Vehicle", conditionCol0param3.getFactType()); assertEquals("vehicleSegment", conditionCol0param3.getFactField()); //Field Constraint 5 - Variable 5 BRLConditionVariableColumn conditionCol0param4 = conditionCol0.getChildColumns().get(4); assertEquals("param5", conditionCol0param4.getVarName()); assertEquals("Age Min", conditionCol0param4.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param4.getFieldType()); assertEquals("Vehicle", conditionCol0param4.getFactType()); assertEquals("vehicleAge", conditionCol0param4.getFactField()); //Field Constraint 6 - Variable 6 BRLConditionVariableColumn conditionCol0param5 = conditionCol0.getChildColumns().get(5); assertEquals("param6", conditionCol0param5.getVarName()); assertEquals("Age Max", conditionCol0param5.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param5.getFieldType()); assertEquals("Vehicle", conditionCol0param5.getFactType()); assertEquals("vehicleAge", conditionCol0param5.getFactField()); //Check individual action columns assertEquals(1, dtable.getActionCols().size()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Discount(%)']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof ActionSetField); ActionSetField actionCol0asf0 = (ActionSetField) actionCol0definition.get(0); assertEquals("v", actionCol0asf0.getVariable()); ActionFieldValue[] actionCol0asf0afvs = actionCol0asf0.getFieldValues(); assertEquals(1, actionCol0asf0afvs.length); ActionFieldValue actionCol0asf0afv0 = actionCol0asf0afvs[0]; assertEquals("discount", actionCol0asf0afv0.getField()); assertEquals("param7", actionCol0asf0afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol0asf0afv0.getNature()); assertEquals(DataType.TYPE_NUMERIC_DOUBLE, actionCol0asf0afv0.getType()); //Action 1 - Variable 1 BRLActionVariableColumn actionCol0param0 = actionCol0.getChildColumns().get(0); assertEquals("param7", actionCol0param0.getVarName()); assertEquals("Discount(%)", actionCol0param0.getHeader()); assertEquals(DataType.TYPE_NUMERIC_DOUBLE, actionCol0param0.getFieldType()); assertEquals("Vehicle", actionCol0param0.getFactType()); assertEquals("discount", actionCol0param0.getFactField()); //Check data assertEquals(4, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "1", "ALL", "XYZ", "EL", "HighEnd", 1, 0, 1.75d}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "2", "ALL", "XYZ", "EL", "HighEnd", 5, 1, 2.00d}, dtable.getData().get(1))); assertTrue(isRowEquivalent(new Object[]{3, "3", "ALL", "XYZ", "EL", "HighEnd", 7, 5, 2.00d}, dtable.getData().get(2))); assertTrue(isRowEquivalent(new Object[]{4, "4", "ALL", "XYZ", "EL", "HighEnd", 10, 7, 1.00d}, dtable.getData().get(3))); } @Test //https://issues.jboss.org/browse/RHBRMS-2055 public void conversionWithEnumerationsInCells() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); addModelField("org.test.Message", "this", "org.test.Message", DataType.TYPE_THIS); addModelField("org.test.Message", "status", Integer.class.getName(), DataType.TYPE_NUMERIC_INTEGER); addModelField("org.test.Message", "message", String.class.getName(), DataType.TYPE_STRING); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("RHBRMS-2055 (Decision table with enums).xls"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(3, result.getMessages().size()); assertTrue(result.getMessages().get(0).getMessage().contains("C11")); assertTrue(result.getMessages().get(1).getMessage().contains("C12")); assertTrue(result.getMessages().get(2).getMessage().contains("F11")); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("HelloWorld1", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(6, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLActionVariableColumn); assertTrue(columns.get(4) instanceof BRLActionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Status']", conditionCol0.getHeader()); assertEquals(1, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Message", conditionCol0fp.getFactType()); assertEquals(1, conditionCol0fp.getNumberOfConstraints()); //Field Constraint 1 assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("status", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc0.getFieldType()); //Field Constraint 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Status", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param0.getFieldType()); assertEquals("Message", conditionCol0param0.getFactType()); assertEquals("status", conditionCol0param0.getFactField()); //Check individual action columns assertEquals(2, dtable.getActionCols().size()); //Action 1 assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Print out message?']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl0 = (FreeFormLine) actionCol0definition.get(0); assertEquals("System.out.println(m.getMessage());", actionCol0ffl0.getText()); //Action 2 BRLActionColumn actionCol1 = ((BRLActionColumn) dtable.getActionCols().get(1)); assertEquals("Converted from ['Set message', 'Set status']", actionCol1.getHeader()); assertEquals(2, actionCol1.getChildColumns().size()); List<IAction> actionCol1definition = actionCol1.getDefinition(); assertEquals(1, actionCol1definition.size()); assertTrue(actionCol1definition.get(0) instanceof ActionSetField); ActionSetField actionCol1asf0 = (ActionSetField) actionCol1definition.get(0); assertEquals("m", actionCol1asf0.getVariable()); ActionFieldValue[] actionCol1asf0afvs = actionCol1asf0.getFieldValues(); assertEquals(2, actionCol1asf0afvs.length); ActionFieldValue actionCol1asf0afv0 = actionCol1asf0afvs[0]; assertEquals("message", actionCol1asf0afv0.getField()); assertEquals("param2", actionCol1asf0afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol1asf0afv0.getNature()); assertEquals(DataType.TYPE_STRING, actionCol1asf0afv0.getType()); ActionFieldValue actionCol1asf0afv1 = actionCol1asf0afvs[1]; assertEquals("status", actionCol1asf0afv1.getField()); assertEquals("param3", actionCol1asf0afv1.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol1asf0afv1.getNature()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, actionCol1asf0afv1.getType()); //Action 1 - Variable 1 BRLActionVariableColumn actionCol0param0 = actionCol0.getChildColumns().get(0); assertEquals("", actionCol0param0.getVarName()); assertEquals("Print out message?", actionCol0param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, actionCol0param0.getFieldType()); assertNull(actionCol0param0.getFactType()); assertNull(actionCol0param0.getFactField()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Action 2 - Variable 1 BRLActionVariableColumn actionCol1param0 = actionCol1.getChildColumns().get(0); assertEquals("param2", actionCol1param0.getVarName()); assertEquals("Set message", actionCol1param0.getHeader()); assertEquals(DataType.TYPE_STRING, actionCol1param0.getFieldType()); assertEquals("Message", actionCol1param0.getFactType()); assertEquals("message", actionCol1param0.getFactField()); //Action 2 - Variable 2 BRLActionVariableColumn actionCol1param1 = actionCol1.getChildColumns().get(1); assertEquals("param3", actionCol1param1.getVarName()); assertEquals("Set status", actionCol1param1.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, actionCol1param1.getFieldType()); assertEquals("Message", actionCol1param1.getFactType()); assertEquals("status", actionCol1param1.getFactField()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Hello World", null, false, "Goodbye cruel world", null}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Goodbye", null, false, "", null}, dtable.getData().get(1))); } @Test //https://issues.jboss.org/browse/GUVNOR-2888 public void conversionWithRetract() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); addModelField("org.test.Employee", "this", "org.test.Employee", DataType.TYPE_THIS); addModelField("org.test.Employee", "yearsOfService", Integer.class.getName(), DataType.TYPE_NUMERIC_INTEGER); addModelField("org.test.Employee", "name", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Employee", "bigAbsence", Boolean.class.getName(), DataType.TYPE_BOOLEAN); addModelField("org.test.Bonus", "this", "org.test.Bonus", DataType.TYPE_THIS); addModelField("org.test.Bonus", "amount", Double.class.getName(), DataType.TYPE_NUMERIC_DOUBLE); addModelField("org.test.Bonus", "employee", "org.test.Employee", DataType.TYPE_OBJECT); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("GUVNOR-2888.xlsx"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } //Check conversion results assertEquals(1, result.getMessages().size()); assertTrue(result.getMessages().get(0).getMessage().contains("I13")); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("bonus_program", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(11, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLConditionVariableColumn); assertTrue(columns.get(4) instanceof BRLConditionVariableColumn); assertTrue(columns.get(5) instanceof BRLConditionVariableColumn); assertTrue(columns.get(6) instanceof BRLConditionVariableColumn); assertTrue(columns.get(7) instanceof BRLConditionVariableColumn); assertTrue(columns.get(8) instanceof BRLActionVariableColumn); assertTrue(columns.get(9) instanceof BRLActionVariableColumn); assertTrue(columns.get(10) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(3, dtable.getConditions().size()); //Pattern 0 assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Served between', 'Served between', 'Served more', 'absence']", conditionCol0.getHeader()); assertEquals(4, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Employee", conditionCol0fp.getFactType()); assertEquals(4, conditionCol0fp.getNumberOfConstraints()); //Pattern 0 - Field Constraint 0 assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("yearsOfService", conditionCol0fpsfc0.getFieldName()); assertEquals(">=", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc0.getFieldType()); //Pattern 0 - Field Constraint 0 - Variable 0 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Served between", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param0.getFieldType()); assertEquals("Employee", conditionCol0param0.getFactType()); assertEquals("yearsOfService", conditionCol0param0.getFactField()); //Pattern 0 - Field Constraint 1 assertTrue(conditionCol0fp.getConstraint(1) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc1 = (SingleFieldConstraint) conditionCol0fp.getConstraint(1); assertEquals("yearsOfService", conditionCol0fpsfc1.getFieldName()); assertEquals("<", conditionCol0fpsfc1.getOperator()); assertEquals("param2", conditionCol0fpsfc1.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc1.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc1.getFieldType()); //Pattern 0 - Field Constraint 1 - Variable 0 BRLConditionVariableColumn conditionCol0param1 = conditionCol0.getChildColumns().get(1); assertEquals("param2", conditionCol0param1.getVarName()); assertEquals("Served between", conditionCol0param1.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param1.getFieldType()); assertEquals("Employee", conditionCol0param1.getFactType()); assertEquals("yearsOfService", conditionCol0param1.getFactField()); //Pattern 0 - Field Constraint 2 assertTrue(conditionCol0fp.getConstraint(2) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc2 = (SingleFieldConstraint) conditionCol0fp.getConstraint(2); assertEquals("yearsOfService", conditionCol0fpsfc2.getFieldName()); assertEquals(">", conditionCol0fpsfc2.getOperator()); assertEquals("param3", conditionCol0fpsfc2.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc2.getConstraintValueType()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0fpsfc2.getFieldType()); //Pattern 0 - Field Constraint 2 - Variable 0 BRLConditionVariableColumn conditionCol0param2 = conditionCol0.getChildColumns().get(2); assertEquals("param3", conditionCol0param2.getVarName()); assertEquals("Served more", conditionCol0param2.getHeader()); assertEquals(DataType.TYPE_NUMERIC_INTEGER, conditionCol0param2.getFieldType()); assertEquals("Employee", conditionCol0param2.getFactType()); assertEquals("yearsOfService", conditionCol0param2.getFactField()); //Pattern 0 - Field Constraint 3 assertTrue(conditionCol0fp.getConstraint(3) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc3 = (SingleFieldConstraint) conditionCol0fp.getConstraint(3); assertEquals("bigAbsence", conditionCol0fpsfc3.getFieldName()); assertEquals("==", conditionCol0fpsfc3.getOperator()); assertEquals("param4", conditionCol0fpsfc3.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc3.getConstraintValueType()); assertEquals(DataType.TYPE_BOOLEAN, conditionCol0fpsfc3.getFieldType()); //Pattern 0 - Field Constraint 3 - Variable 0 BRLConditionVariableColumn conditionCol0param3 = conditionCol0.getChildColumns().get(3); assertEquals("param4", conditionCol0param3.getVarName()); assertEquals("absence", conditionCol0param3.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, conditionCol0param3.getFieldType()); assertEquals("Employee", conditionCol0param3.getFactType()); assertEquals("bigAbsence", conditionCol0param3.getFactField()); //Pattern 1 assertTrue(dtable.getConditions().get(1) instanceof BRLConditionColumn); BRLConditionColumn conditionCol1 = ((BRLConditionColumn) dtable.getConditions().get(1)); assertEquals("Converted from ['bonus for employee']", conditionCol1.getHeader()); assertEquals(1, conditionCol1.getChildColumns().size()); List<IPattern> conditionCol1definition = conditionCol1.getDefinition(); assertEquals(1, conditionCol1definition.size()); assertTrue(conditionCol1definition.get(0) instanceof FactPattern); FactPattern conditionCol1fp = (FactPattern) conditionCol1definition.get(0); assertEquals("Bonus", conditionCol1fp.getFactType()); assertEquals(1, conditionCol1fp.getNumberOfConstraints()); //Pattern 1 - Field Constraint 0 assertTrue(conditionCol1fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol1fpsfc0 = (SingleFieldConstraint) conditionCol1fp.getConstraint(0); assertEquals("employee", conditionCol1fpsfc0.getFieldName()); assertEquals("==", conditionCol1fpsfc0.getOperator()); assertEquals("param5", conditionCol1fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol1fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_OBJECT, conditionCol1fpsfc0.getFieldType()); //Pattern 1 - Field Constraint 0 - Variable 0 BRLConditionVariableColumn conditionCol1param0 = conditionCol1.getChildColumns().get(0); assertEquals("param5", conditionCol1param0.getVarName()); assertEquals("bonus for employee", conditionCol1param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, conditionCol1param0.getFieldType()); assertEquals("Bonus", conditionCol1param0.getFactType()); assertEquals("employee", conditionCol1param0.getFactField()); //Pattern 2 assertTrue(dtable.getConditions().get(2) instanceof BRLConditionColumn); BRLConditionColumn conditionCol2 = ((BRLConditionColumn) dtable.getConditions().get(2)); assertEquals("Converted from ['no bonus for employee']", conditionCol2.getHeader()); assertEquals(1, conditionCol2.getChildColumns().size()); List<IPattern> conditionCol2definition = conditionCol2.getDefinition(); assertEquals(1, conditionCol2definition.size()); assertTrue(conditionCol2definition.get(0) instanceof CompositeFactPattern); CompositeFactPattern conditionCol2cfp = (CompositeFactPattern) conditionCol2definition.get(0); assertEquals(CompositeFactPattern.COMPOSITE_TYPE_NOT, conditionCol2cfp.getType()); assertEquals(1, conditionCol2cfp.getPatterns().length); assertTrue(conditionCol2cfp.getPatterns()[0] instanceof FactPattern); FactPattern conditionCol2fp = (FactPattern) conditionCol2cfp.getPatterns()[0]; assertEquals("Bonus", conditionCol2fp.getFactType()); assertEquals(1, conditionCol2fp.getNumberOfConstraints()); //Pattern 2 - Field Constraint 0 assertTrue(conditionCol2fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol2fpsfc0 = (SingleFieldConstraint) conditionCol2fp.getConstraint(0); assertEquals("employee", conditionCol2fpsfc0.getFieldName()); assertEquals("==", conditionCol2fpsfc0.getOperator()); assertEquals("param6", conditionCol2fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol2fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_OBJECT, conditionCol2fpsfc0.getFieldType()); //Pattern 2 - Field Constraint 0 - Variable 0 BRLConditionVariableColumn conditionCol2param0 = conditionCol2.getChildColumns().get(0); assertEquals("param6", conditionCol2param0.getVarName()); assertEquals("no bonus for employee", conditionCol2param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, conditionCol2param0.getFieldType()); assertEquals("Bonus", conditionCol2param0.getFactType()); assertEquals("employee", conditionCol2param0.getFactField()); //Check individual action columns assertEquals(3, dtable.getActionCols().size()); //Action 0 assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Inser bonus of amount']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl0 = (FreeFormLine) actionCol0definition.get(0); assertEquals("Bonus $b = new Bonus(); $b.setAmount((double)@{param7}); $b.setEmployee($e); insert($b);", actionCol0ffl0.getText()); //Action 0 - Variable 0 BRLActionVariableColumn actionCol0param0 = actionCol0.getChildColumns().get(0); assertEquals("param7", actionCol0param0.getVarName()); assertEquals("Inser bonus of amount", actionCol0param0.getHeader()); assertEquals(DataType.TYPE_OBJECT, actionCol0param0.getFieldType()); //Action 1 BRLActionColumn actionCol1 = ((BRLActionColumn) dtable.getActionCols().get(1)); assertEquals("Converted from ['retract']", actionCol1.getHeader()); assertEquals(1, actionCol1.getChildColumns().size()); List<IAction> actionCol1definition = actionCol1.getDefinition(); assertEquals(1, actionCol1definition.size()); assertTrue(actionCol1definition.get(0) instanceof ActionRetractFact); ActionRetractFact actionCol1arf = (ActionRetractFact) actionCol1definition.get(0); assertEquals("$bonus", actionCol1arf.getVariableName()); assertTrue(dtable.getActionCols().get(1) instanceof BRLActionColumn); //Action 1 - Variable 0 BRLActionVariableColumn actionCol1param0 = actionCol1.getChildColumns().get(0); assertEquals("param8", actionCol1param0.getVarName()); assertEquals("retract", actionCol1param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, actionCol1param0.getFieldType()); //Action 2 BRLActionColumn actionCol2 = ((BRLActionColumn) dtable.getActionCols().get(2)); assertEquals("Converted from ['retract2']", actionCol2.getHeader()); assertEquals(1, actionCol2.getChildColumns().size()); List<IAction> actionCol2definition = actionCol2.getDefinition(); assertEquals(1, actionCol2definition.size()); assertTrue(actionCol2definition.get(0) instanceof ActionRetractFact); ActionRetractFact actionCol2arf = (ActionRetractFact) actionCol2definition.get(0); assertEquals("$b", actionCol2arf.getVariableName()); assertTrue(dtable.getActionCols().get(2) instanceof BRLActionColumn); //Action 2 - Variable 1 BRLActionVariableColumn actionCol2param0 = actionCol2.getChildColumns().get(0); assertEquals("", actionCol2param0.getVarName()); assertEquals("retract2", actionCol2param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, actionCol2param0.getFieldType()); //Check data assertEquals(4, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Lowest bonus", 0, 2, null, false, "", "$e", "400", false, false}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Middle bonus", 2, 6, null, false, "", "$e", "800", false, false}, dtable.getData().get(1))); assertTrue(isRowEquivalent(new Object[]{3, "High bonus", null, null, 6, false, "", "", "1000", false, false}, dtable.getData().get(2))); assertTrue(isRowEquivalent(new Object[]{4, "Big absence", null, null, null, true, "$e", "", "", true, true}, dtable.getData().get(3))); } @Test //https://issues.jboss.org/browse/RHBPMS-4737 public void conversionWithBigDecimals() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); addModelField("org.test.Message", "this", "org.test.Message", DataType.TYPE_THIS); addModelField("org.test.Message", "status", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Message", "message", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Message", "rate", BigDecimal.class.getName(), DataType.TYPE_NUMERIC_BIGDECIMAL); addModelField("org.test.Reply", "this", "org.test.Reply", DataType.TYPE_THIS); addModelField("org.test.Reply", "message", String.class.getName(), DataType.TYPE_STRING); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("RHBPMS-4737 (BigDecimal).xlsx"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } checkConversionWithBigMaths(result, listener, () -> DataType.TYPE_NUMERIC_BIGDECIMAL, () -> new BigDecimal("10.00"), () -> new BigDecimal("20.00")); } @Test //https://issues.jboss.org/browse/RHBPMS-4737 public void conversionWithBigDecimalsWithoutDMO() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("RHBPMS-4737 (No DMO).xlsx"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } checkConversionWithBigMaths(result, listener, () -> DataType.TYPE_NUMERIC, () -> new BigDecimal("10.00"), () -> new BigDecimal("20.00")); } @Test //https://issues.jboss.org/browse/RHBPMS-4737 public void conversionWithBigIntegers() { final ConversionResult result = new ConversionResult(); final List<DataListener> listeners = new ArrayList<>(); addModelField("org.test.Message", "this", "org.test.Message", DataType.TYPE_THIS); addModelField("org.test.Message", "status", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Message", "message", String.class.getName(), DataType.TYPE_STRING); addModelField("org.test.Message", "rate", BigDecimal.class.getName(), DataType.TYPE_NUMERIC_BIGINTEGER); addModelField("org.test.Reply", "this", "org.test.Reply", DataType.TYPE_THIS); addModelField("org.test.Reply", "message", String.class.getName(), DataType.TYPE_STRING); final GuidedDecisionTableGeneratorListener listener = new GuidedDecisionTableGeneratorListener(result, dmo); listeners.add(listener); //Convert final ExcelParser parser = new ExcelParser(listeners); final InputStream is = this.getClass().getResourceAsStream("RHBPMS-4737 (BigInteger).xlsx"); try { parser.parseFile(is); } finally { try { is.close(); } catch (IOException ioe) { fail(ioe.getMessage()); } } checkConversionWithBigMaths(result, listener, () -> DataType.TYPE_NUMERIC_BIGINTEGER, () -> new BigInteger("10"), () -> new BigInteger("20")); } private void checkConversionWithBigMaths(final ConversionResult result, final GuidedDecisionTableGeneratorListener listener, final Supplier<String> expectedDataType, final Supplier<Object> expectedDataValueRow0, final Supplier<Object> expectedDataValueRow1) { //Check conversion results assertEquals(0, result.getMessages().size()); //Check basics final List<GuidedDecisionTable52> dtables = listener.getGuidedDecisionTables(); assertNotNull(dtables); assertEquals(1, dtables.size()); GuidedDecisionTable52 dtable = dtables.get(0); assertEquals("HelloWorld1", dtable.getTableName()); assertEquals(GuidedDecisionTable52.TableFormat.EXTENDED_ENTRY, dtable.getTableFormat()); //Check expanded columns List<BaseColumn> columns = dtable.getExpandedColumns(); assertNotNull(columns); assertEquals(8, columns.size()); assertTrue(columns.get(0) instanceof RowNumberCol52); assertTrue(columns.get(1) instanceof DescriptionCol52); assertTrue(columns.get(2) instanceof BRLConditionVariableColumn); assertTrue(columns.get(3) instanceof BRLActionVariableColumn); assertTrue(columns.get(4) instanceof BRLActionVariableColumn); assertTrue(columns.get(5) instanceof BRLActionVariableColumn); assertTrue(columns.get(6) instanceof BRLActionVariableColumn); assertTrue(columns.get(7) instanceof BRLActionVariableColumn); //Check individual condition columns assertEquals(1, dtable.getConditions().size()); assertTrue(dtable.getConditions().get(0) instanceof BRLConditionColumn); BRLConditionColumn conditionCol0 = ((BRLConditionColumn) dtable.getConditions().get(0)); assertEquals("Converted from ['Status']", conditionCol0.getHeader()); assertEquals(1, conditionCol0.getChildColumns().size()); List<IPattern> conditionCol0definition = conditionCol0.getDefinition(); assertEquals(1, conditionCol0definition.size()); assertTrue(conditionCol0definition.get(0) instanceof FactPattern); FactPattern conditionCol0fp = (FactPattern) conditionCol0definition.get(0); assertEquals("Message", conditionCol0fp.getFactType()); assertEquals(1, conditionCol0fp.getNumberOfConstraints()); //Field Constraint 1 assertTrue(conditionCol0fp.getConstraint(0) instanceof SingleFieldConstraint); final SingleFieldConstraint conditionCol0fpsfc0 = (SingleFieldConstraint) conditionCol0fp.getConstraint(0); assertEquals("status", conditionCol0fpsfc0.getFieldName()); assertEquals("==", conditionCol0fpsfc0.getOperator()); assertEquals("param1", conditionCol0fpsfc0.getValue()); assertEquals(SingleFieldConstraint.TYPE_TEMPLATE, conditionCol0fpsfc0.getConstraintValueType()); assertEquals(DataType.TYPE_STRING, conditionCol0fpsfc0.getFieldType()); //Field Constraint 1 - Variable 1 BRLConditionVariableColumn conditionCol0param0 = conditionCol0.getChildColumns().get(0); assertEquals("param1", conditionCol0param0.getVarName()); assertEquals("Status", conditionCol0param0.getHeader()); assertEquals(DataType.TYPE_STRING, conditionCol0param0.getFieldType()); assertEquals("Message", conditionCol0param0.getFactType()); assertEquals("status", conditionCol0param0.getFactField()); //Check individual action columns assertEquals(3, dtable.getActionCols().size()); //Action 1 assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); BRLActionColumn actionCol0 = ((BRLActionColumn) dtable.getActionCols().get(0)); assertEquals("Converted from ['Print out message?']", actionCol0.getHeader()); assertEquals(1, actionCol0.getChildColumns().size()); List<IAction> actionCol0definition = actionCol0.getDefinition(); assertEquals(1, actionCol0definition.size()); assertTrue(actionCol0definition.get(0) instanceof FreeFormLine); FreeFormLine actionCol0ffl0 = (FreeFormLine) actionCol0definition.get(0); assertEquals("System.out.println(m.getMessage());", actionCol0ffl0.getText()); //Action 2 BRLActionColumn actionCol1 = ((BRLActionColumn) dtable.getActionCols().get(1)); assertEquals("Converted from ['Set message', 'Set status', 'Set rate']", actionCol1.getHeader()); assertEquals(3, actionCol1.getChildColumns().size()); List<IAction> actionCol1definition = actionCol1.getDefinition(); assertEquals(1, actionCol1definition.size()); assertTrue(actionCol1definition.get(0) instanceof ActionSetField); ActionSetField actionCol1asf0 = (ActionSetField) actionCol1definition.get(0); assertEquals("m", actionCol1asf0.getVariable()); ActionFieldValue[] actionCol1asf0afvs = actionCol1asf0.getFieldValues(); assertEquals(3, actionCol1asf0afvs.length); ActionFieldValue actionCol1asf0afv0 = actionCol1asf0afvs[0]; assertEquals("message", actionCol1asf0afv0.getField()); assertEquals("param2", actionCol1asf0afv0.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol1asf0afv0.getNature()); assertEquals(DataType.TYPE_STRING, actionCol1asf0afv0.getType()); ActionFieldValue actionCol1asf0afv1 = actionCol1asf0afvs[1]; assertEquals("status", actionCol1asf0afv1.getField()); assertEquals("param3", actionCol1asf0afv1.getValue()); assertEquals(FieldNatureType.TYPE_TEMPLATE, actionCol1asf0afv1.getNature()); assertEquals(DataType.TYPE_STRING, actionCol1asf0afv1.getType()); //Action 1 - Variable 1 BRLActionVariableColumn actionCol0param0 = actionCol0.getChildColumns().get(0); assertEquals("", actionCol0param0.getVarName()); assertEquals("Print out message?", actionCol0param0.getHeader()); assertEquals(DataType.TYPE_BOOLEAN, actionCol0param0.getFieldType()); assertNull(actionCol0param0.getFactType()); assertNull(actionCol0param0.getFactField()); assertTrue(dtable.getActionCols().get(0) instanceof BRLActionColumn); //Action 2 - Variable 1 BRLActionVariableColumn actionCol1param0 = actionCol1.getChildColumns().get(0); assertEquals("param2", actionCol1param0.getVarName()); assertEquals("Set message", actionCol1param0.getHeader()); assertEquals(DataType.TYPE_STRING, actionCol1param0.getFieldType()); assertEquals("Message", actionCol1param0.getFactType()); assertEquals("message", actionCol1param0.getFactField()); //Action 2 - Variable 2 BRLActionVariableColumn actionCol1param1 = actionCol1.getChildColumns().get(1); assertEquals("param3", actionCol1param1.getVarName()); assertEquals("Set status", actionCol1param1.getHeader()); assertEquals(DataType.TYPE_STRING, actionCol1param1.getFieldType()); assertEquals("Message", actionCol1param1.getFactType()); assertEquals("status", actionCol1param1.getFactField()); //Action 2 - Variable 3 BRLActionVariableColumn actionCol1param2 = actionCol1.getChildColumns().get(2); assertEquals("param4", actionCol1param2.getVarName()); assertEquals("Set rate", actionCol1param2.getHeader()); assertEquals(expectedDataType.get(), actionCol1param2.getFieldType()); assertEquals("Message", actionCol1param2.getFactType()); assertEquals("rate", actionCol1param2.getFactField()); //Check data assertEquals(2, dtable.getData().size()); assertTrue(isRowEquivalent(new Object[]{1, "Hello World", "Message.HELLO", false, "Goodbye cruel world", "Message.GOODBYE", expectedDataValueRow0.get(), "m"}, dtable.getData().get(0))); assertTrue(isRowEquivalent(new Object[]{2, "Goodbye", "Message.GOODBYE", false, "", "", expectedDataValueRow1.get(), "m"}, dtable.getData().get(1))); } private boolean isRowEquivalent(Object[] expected, List<DTCellValue52> actual) { //Sizes should match if (expected.length != actual.size()) { return false; } //Column values for (int i = 0; i < expected.length; i++) { DTCellValue52 dcv = actual.get(i); switch (dcv.getDataType()) { case NUMERIC: final BigDecimal numeric = (BigDecimal) dcv.getNumericValue(); if (!assertValues(expected[i], numeric)) { return false; } break; case NUMERIC_BIGDECIMAL: final BigDecimal numericBigDecimal = (BigDecimal) dcv.getNumericValue(); if (!assertValues(expected[i], numericBigDecimal)) { return false; } break; case NUMERIC_BIGINTEGER: final BigInteger numericBigInteger = (BigInteger) dcv.getNumericValue(); if (!assertValues(expected[i], numericBigInteger)) { return false; } break; case NUMERIC_BYTE: final Byte numericByte = (Byte) dcv.getNumericValue(); if (!assertValues(expected[i], numericByte)) { return false; } break; case NUMERIC_DOUBLE: final Double numericDouble = (Double) dcv.getNumericValue(); if (!assertValues(expected[i], numericDouble)) { return false; } break; case NUMERIC_FLOAT: final Float numericFloat = (Float) dcv.getNumericValue(); if (!assertValues(expected[i], numericFloat)) { return false; } break; case NUMERIC_INTEGER: final Integer numericInteger = (Integer) dcv.getNumericValue(); if (!assertValues(expected[i], numericInteger)) { return false; } break; case NUMERIC_LONG: final Long numericLong = (Long) dcv.getNumericValue(); if (!assertValues(expected[i], numericLong)) { return false; } break; case NUMERIC_SHORT: final Short numericShort = (Short) dcv.getNumericValue(); if (!assertValues(expected[i], numericShort)) { return false; } break; case BOOLEAN: if (!assertValues(expected[i], dcv.getBooleanValue())) { return false; } break; default: if (!assertValues(expected[i], dcv.getStringValue())) { return false; } } } return true; } private boolean assertValues(final Object expected, final Object actual) { if (expected == null) { return actual == null; } return expected.equals(actual); } private void addModelField(final String factName, final String fieldName, final String clazz, final String type) { ModelField[] modelFields = new ModelField[1]; modelFields[0] = new ModelField(fieldName, clazz, ModelField.FIELD_CLASS_TYPE.TYPE_DECLARATION_CLASS, ModelField.FIELD_ORIGIN.DECLARED, FieldAccessorsAndMutators.BOTH, type); if (packageModelFields.containsKey(factName)) { final List<ModelField> existingModelFields = new ArrayList<ModelField>(Arrays.asList(packageModelFields.get(factName))); existingModelFields.add(modelFields[0]); modelFields = existingModelFields.toArray(modelFields); } packageModelFields.put(factName, modelFields); } }
etirelli/drools-wb
drools-wb-screens/drools-wb-dtable-xls-editor/drools-wb-dtable-xls-editor-backend/src/test/java/org/drools/workbench/screens/dtablexls/backend/server/conversion/GuidedDecisionTableGeneratorListenerTest.java
Java
apache-2.0
161,992
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dlp.v2.model; /** * A collection of conditions. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Data Loss Prevention (DLP) API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GooglePrivacyDlpV2Conditions extends com.google.api.client.json.GenericJson { /** * A collection of conditions. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GooglePrivacyDlpV2Condition> conditions; static { // hack to force ProGuard to consider GooglePrivacyDlpV2Condition used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GooglePrivacyDlpV2Condition.class); } /** * A collection of conditions. * @return value or {@code null} for none */ public java.util.List<GooglePrivacyDlpV2Condition> getConditions() { return conditions; } /** * A collection of conditions. * @param conditions conditions or {@code null} for none */ public GooglePrivacyDlpV2Conditions setConditions(java.util.List<GooglePrivacyDlpV2Condition> conditions) { this.conditions = conditions; return this; } @Override public GooglePrivacyDlpV2Conditions set(String fieldName, Object value) { return (GooglePrivacyDlpV2Conditions) super.set(fieldName, value); } @Override public GooglePrivacyDlpV2Conditions clone() { return (GooglePrivacyDlpV2Conditions) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dlp/v2/1.31.0/com/google/api/services/dlp/v2/model/GooglePrivacyDlpV2Conditions.java
Java
apache-2.0
2,547
/* * Copyright 2005 MH-Software-Entwicklung. All rights reserved. * Use is subject to license terms. */ package com.jtattoo.plaf.graphite; import javax.swing.*; import com.jtattoo.plaf.*; /** * @author Michael Hagen */ public class GraphiteIconFactory implements AbstractIconFactory { private static GraphiteIconFactory instance = null; private GraphiteIconFactory() { } public static synchronized GraphiteIconFactory getInstance() { if (instance == null) instance = new GraphiteIconFactory(); return instance; } public Icon getOptionPaneErrorIcon() { return GraphiteIcons.getOptionPaneErrorIcon(); } public Icon getOptionPaneWarningIcon() { return GraphiteIcons.getOptionPaneWarningIcon(); } public Icon getOptionPaneInformationIcon() { return GraphiteIcons.getOptionPaneInformationIcon(); } public Icon getOptionPaneQuestionIcon() { return GraphiteIcons.getOptionPaneQuestionIcon(); } public Icon getFileChooserDetailViewIcon() { return GraphiteIcons.getFileChooserDetailViewIcon(); } public Icon getFileChooserHomeFolderIcon() { return GraphiteIcons.getFileChooserHomeFolderIcon(); } public Icon getFileChooserListViewIcon() { return GraphiteIcons.getFileChooserListViewIcon(); } public Icon getFileChooserNewFolderIcon() { return GraphiteIcons.getFileChooserNewFolderIcon(); } public Icon getFileChooserUpFolderIcon() { return GraphiteIcons.getFileChooserUpFolderIcon(); } public Icon getMenuIcon() { return GraphiteIcons.getMenuIcon(); } public Icon getIconIcon() { return GraphiteIcons.getIconIcon(); } public Icon getMaxIcon() { return GraphiteIcons.getMaxIcon(); } public Icon getMinIcon() { return GraphiteIcons.getMinIcon(); } public Icon getCloseIcon() { return GraphiteIcons.getCloseIcon(); } public Icon getPaletteCloseIcon() { return GraphiteIcons.getPaletteCloseIcon(); } public Icon getRadioButtonIcon() { return GraphiteIcons.getRadioButtonIcon(); } public Icon getCheckBoxIcon() { return GraphiteIcons.getCheckBoxIcon(); } public Icon getComboBoxIcon() { return GraphiteIcons.getComboBoxIcon(); } public Icon getTreeComputerIcon() { return GraphiteIcons.getTreeComputerIcon(); } public Icon getTreeFloppyDriveIcon() { return GraphiteIcons.getTreeFloppyDriveIcon(); } public Icon getTreeHardDriveIcon() { return GraphiteIcons.getTreeHardDriveIcon(); } public Icon getTreeFolderIcon() { return GraphiteIcons.getTreeFolderIcon(); } public Icon getTreeLeafIcon() { return GraphiteIcons.getTreeLeafIcon(); } public Icon getTreeCollapsedIcon() { return GraphiteIcons.getTreeControlIcon(true); } public Icon getTreeExpandedIcon() { return GraphiteIcons.getTreeControlIcon(false); } public Icon getMenuArrowIcon() { return GraphiteIcons.getMenuArrowIcon(); } public Icon getMenuCheckBoxIcon() { return GraphiteIcons.getMenuCheckBoxIcon(); } public Icon getMenuRadioButtonIcon() { return GraphiteIcons.getMenuRadioButtonIcon(); } public Icon getUpArrowIcon() { return GraphiteIcons.getUpArrowIcon(); } public Icon getDownArrowIcon() { return GraphiteIcons.getDownArrowIcon(); } public Icon getLeftArrowIcon() { return GraphiteIcons.getLeftArrowIcon(); } public Icon getRightArrowIcon() { return GraphiteIcons.getRightArrowIcon(); } public Icon getSplitterDownArrowIcon() { return GraphiteIcons.getSplitterDownArrowIcon(); } public Icon getSplitterHorBumpIcon() { return GraphiteIcons.getSplitterHorBumpIcon(); } public Icon getSplitterLeftArrowIcon() { return GraphiteIcons.getSplitterLeftArrowIcon(); } public Icon getSplitterRightArrowIcon() { return GraphiteIcons.getSplitterRightArrowIcon(); } public Icon getSplitterUpArrowIcon() { return GraphiteIcons.getSplitterUpArrowIcon(); } public Icon getSplitterVerBumpIcon() { return GraphiteIcons.getSplitterVerBumpIcon(); } public Icon getThumbHorIcon() { return GraphiteIcons.getThumbHorIcon(); } public Icon getThumbVerIcon() { return GraphiteIcons.getThumbVerIcon(); } public Icon getThumbHorIconRollover() { return GraphiteIcons.getThumbHorIconRollover(); } public Icon getThumbVerIconRollover() { return GraphiteIcons.getThumbVerIconRollover(); } }
joshuairl/toothchat-client
src/jtattoo/src/com/jtattoo/plaf/graphite/GraphiteIconFactory.java
Java
apache-2.0
4,513
/* * Copyright 2015 herd contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finra.herd.service.helper; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; import org.finra.herd.model.ObjectNotFoundException; import org.finra.herd.model.jpa.NotificationRegistrationStatusEntity; import org.finra.herd.service.AbstractServiceTest; public class NotificationRegistrationStatusDaoHelperTest extends AbstractServiceTest { @Test public void testGetNotificationRegistrationStatusAssertReturnEntityWhenEntityExists() { NotificationRegistrationStatusEntity notificationRegistrationStatus = notificationRegistrationStatusDaoHelper.getNotificationRegistrationStatusEntity("ENABLED"); assertNotNull(notificationRegistrationStatus); assertEquals("ENABLED", notificationRegistrationStatus.getCode()); } @Test public void testGetNotificationRegistrationStatusAssertThrowWhenEntityNotExist() { try { notificationRegistrationStatusDaoHelper.getNotificationRegistrationStatusEntity("DOES_NOT_EXIST"); fail(); } catch (Exception e) { assertEquals(ObjectNotFoundException.class, e.getClass()); assertEquals("The notification registration status \"DOES_NOT_EXIST\" doesn't exist.", e.getMessage()); } } }
FINRAOS/herd
herd-code/herd-service/src/test/java/org/finra/herd/service/helper/NotificationRegistrationStatusDaoHelperTest.java
Java
apache-2.0
1,974
package com.holidaystudios.kngtz; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Arrays; import java.util.Enumeration; class WifiServerNetworkInterface implements com.holidaystudios.kngt.networking.ServerNetworkInterface { private android.net.wifi.WifiManager.MulticastLock lock; private final Context context; private Enumeration<InetAddress> getWifiInetAddresses(final Context _context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo wifiInfo = wifiManager.getConnectionInfo(); final String macAddress = wifiInfo.getMacAddress(); final String[] macParts = macAddress.split(":"); final byte[] macBytes = new byte[macParts.length]; for (int i = 0; i< macParts.length; i++) { macBytes[i] = (byte)Integer.parseInt(macParts[i], 16); } try { final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { final NetworkInterface networkInterface = e.nextElement(); if (Arrays.equals(networkInterface.getHardwareAddress(), macBytes)) { return networkInterface.getInetAddresses(); } } } catch (SocketException e) { Log.wtf("WIFIIP", "Unable to NetworkInterface.getNetworkInterfaces()"); } return null; } @SuppressWarnings("unchecked") private <T extends InetAddress> T getWifiInetAddress(final Context context, final Class<T> inetClass) { final Enumeration<InetAddress> e = getWifiInetAddresses(context); while (e.hasMoreElements()) { final InetAddress inetAddress = e.nextElement(); if (inetAddress.getClass() == inetClass) { return (T)inetAddress; } } return null; } public WifiServerNetworkInterface(Context _context) { context = _context; android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(android.content.Context.WIFI_SERVICE); lock = wifi.createMulticastLock("mylockthereturn"); lock.setReferenceCounted(true); } @Override public void acquire() { lock.acquire(); } @Override public void release() { lock.release(); } @Override public String getIp() throws SocketException { final Inet4Address inet4Address = getWifiInetAddress(context, Inet4Address.class); final Inet6Address inet6Address = getWifiInetAddress(context, Inet6Address.class); if(inet6Address != null) return inet6Address.getHostAddress(); if(inet4Address != null) return inet4Address.getHostAddress(); throw new SocketException("No local network address found."); } }
tedbjorling/kngtz
android/src/com/holidaystudios/kngtz/WifiServerNetworkInterface.java
Java
apache-2.0
3,125
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.vmplugin.v7; import groovy.lang.AdaptingMetaClass; import groovy.lang.Closure; import groovy.lang.ExpandoMetaClass; import groovy.lang.GroovyInterceptable; import groovy.lang.GroovyObject; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovySystem; import groovy.lang.MetaClass; import groovy.lang.MetaClassImpl; import groovy.lang.MetaClassImpl.MetaConstructor; import groovy.lang.MetaMethod; import groovy.lang.MetaProperty; import groovy.lang.MissingMethodException; import groovy.transform.Internal; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.reflection.CachedField; import org.codehaus.groovy.reflection.CachedMethod; import org.codehaus.groovy.reflection.ClassInfo; import org.codehaus.groovy.reflection.GeneratedMetaMethod; import org.codehaus.groovy.reflection.stdclasses.CachedSAMClass; import org.codehaus.groovy.runtime.GeneratedClosure; import org.codehaus.groovy.runtime.GroovyCategorySupport; import org.codehaus.groovy.runtime.GroovyCategorySupport.CategoryMethod; import org.codehaus.groovy.runtime.NullObject; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMetaMethod; import org.codehaus.groovy.runtime.metaclass.ClosureMetaClass; import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl; import org.codehaus.groovy.runtime.metaclass.MethodMetaProperty; import org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod; import org.codehaus.groovy.runtime.metaclass.NewStaticMetaMethod; import org.codehaus.groovy.runtime.metaclass.ReflectionMetaMethod; import org.codehaus.groovy.runtime.wrappers.Wrapper; import org.codehaus.groovy.vmplugin.v7.IndyInterface.CALL_TYPES; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.ARRAYLIST_CONSTRUCTOR; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.BEAN_CONSTRUCTOR_PROPERTY_SETTER; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.BOOLEAN_IDENTITY; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.CLASS_FOR_NAME; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.DTT_CAST_TO_TYPE; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.EQUALS; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.GROOVY_CAST_EXCEPTION; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.GROOVY_OBJECT_GET_PROPERTY; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.GROOVY_OBJECT_INVOKER; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.HASHSET_CONSTRUCTOR; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.HAS_CATEGORY_IN_CURRENT_THREAD_GUARD; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.INTERCEPTABLE_INVOKER; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.IS_NULL; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.META_CLASS_INVOKE_STATIC_METHOD; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.META_METHOD_INVOKER; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.META_PROPERTY_GETTER; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.MOP_GET; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.MOP_INVOKE_CONSTRUCTOR; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.MOP_INVOKE_METHOD; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.NULL_REF; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.SAME_CLASS; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.SAME_MC; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.SAM_CONVERSION; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.UNWRAP_EXCEPTION; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.UNWRAP_METHOD; import static org.codehaus.groovy.vmplugin.v7.IndyGuardsFiltersAndSignatures.unwrap; import static org.codehaus.groovy.vmplugin.v7.IndyInterface.LOG; import static org.codehaus.groovy.vmplugin.v7.IndyInterface.LOG_ENABLED; import static org.codehaus.groovy.vmplugin.v7.IndyInterface.LOOKUP; import static org.codehaus.groovy.vmplugin.v7.IndyInterface.makeFallBack; import static org.codehaus.groovy.vmplugin.v7.IndyInterface.switchPoint; public abstract class Selector { public Object[] args, originalArguments; public MetaMethod method; public MethodType targetType,currentType; public String name; public MethodHandle handle; public boolean useMetaClass = false, cache = true; public MutableCallSite callSite; public Class sender; public boolean isVargs; public boolean safeNavigation, safeNavigationOrig, spread; public boolean skipSpreadCollector; public boolean thisCall; public Class selectionBase; public boolean catchException = true; public CALL_TYPES callType; /** Cache values for read-only access */ private static final CALL_TYPES[] CALL_TYPES_VALUES = CALL_TYPES.values(); /** * Returns the Selector */ public static Selector getSelector(MutableCallSite callSite, Class sender, String methodName, int callID, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) { CALL_TYPES callType = CALL_TYPES_VALUES[callID]; switch (callType) { case INIT: return new InitSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case METHOD: return new MethodSelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case GET: return new PropertySelector(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); case SET: throw new GroovyBugError("your call tried to do a property set, which is not supported."); case CAST: return new CastSelector(callSite, arguments); default: throw new GroovyBugError("unexpected call type"); } } abstract void setCallSiteTarget(); /** * Helper method to transform the given arguments, consisting of the receiver * and the actual arguments in an Object[], into a new Object[] consisting * of the receiver and the arguments directly. Before the size of args was * always 2, the returned Object[] will have a size of 1+n, where n is the * number arguments. */ private static Object[] spread(Object[] args, boolean spreadCall) { if (!spreadCall) return args; Object[] normalArguments = (Object[]) args[1]; Object[] ret = new Object[normalArguments.length+1]; ret[0] = args[0]; System.arraycopy(normalArguments, 0, ret, 1, ret.length-1); return ret; } private static class CastSelector extends MethodSelector { private final Class<?> staticSourceType, staticTargetType; public CastSelector(MutableCallSite callSite, Object[] arguments) { super(callSite, Selector.class, "", CALL_TYPES.CAST, false, false, false, arguments); this.staticSourceType = callSite.type().parameterType(0); this.staticTargetType = callSite.type().returnType(); } @Override public void setCallSiteTarget() { // targetTypes String, Enum and Class are handled // by the compiler already // Boolean / boolean handleBoolean(); handleNullWithoutBoolean(); // !! from here on args[0] is always not null !! handleInstanceCase(); // targetType is abstract Collection fitting for HashSet or ArrayList // and object is Collection or array handleCollections(); handleSAM(); // will handle : // * collection case where argument is an array // * array transformation (staticTargetType.isArray()) // * constructor invocation // * final GroovyCastException castToTypeFallBack(); if (!handle.type().equals(callSite.type())) castAndSetGuards(); } private void castAndSetGuards() { handle = MethodHandles.explicitCastArguments(handle,targetType); setGuards(args[0]); doCallSiteTargetSet(); } private void handleNullWithoutBoolean() { if (handle!=null || args[0]!=null) return; if (staticTargetType.isPrimitive()) { handle = MethodHandles.insertArguments(GROOVY_CAST_EXCEPTION,1,staticTargetType); // need to call here here because we used the static target type // it won't be done otherwise because handle.type() == callSite.type() castAndSetGuards(); } else { handle = MethodHandles.identity(staticSourceType); } } private void handleInstanceCase() { if (handle!=null) return; if (staticTargetType.isAssignableFrom(args[0].getClass())) { handle = MethodHandles.identity(staticSourceType); } } private static boolean isAbstractClassOf(Class toTest, Class givenOnCallSite) { if (!toTest.isAssignableFrom(givenOnCallSite)) return false; if (givenOnCallSite.isInterface()) return true; return Modifier.isAbstract(givenOnCallSite.getModifiers()); } private void handleCollections() { if (handle!=null) return; if (!(args[0] instanceof Collection)) return; if (isAbstractClassOf(HashSet.class, staticTargetType)) { handle = HASHSET_CONSTRUCTOR; } else if (isAbstractClassOf(ArrayList.class, staticTargetType)) { handle = ARRAYLIST_CONSTRUCTOR; } } private void handleSAM() { if (handle!=null) return; if (!(args[0] instanceof Closure)) return; Method m = CachedSAMClass.getSAMMethod(staticTargetType); if (m==null) return; //TODO: optimize: add guard based on type Closure handle = MethodHandles.insertArguments(SAM_CONVERSION, 1, m, staticTargetType); } private void castToTypeFallBack() { if (handle!=null) return; // generic fallback to castToType handle = MethodHandles.insertArguments(DTT_CAST_TO_TYPE, 1, staticTargetType); } private void handleBoolean() { if (handle!=null) return; // boolean->boolean, Boolean->boolean, boolean->Boolean // is handled by compiler // that leaves (T)Z and (T)Boolean, where T is the static type // but runtime type of T might be Boolean boolean primitive = staticTargetType==boolean.class; if (!primitive && staticTargetType!=Boolean.class) return; if (args[0]==null) { if (primitive) { handle = MethodHandles.constant(boolean.class, false); handle = MethodHandles.dropArguments(handle, 0, staticSourceType); } else { handle = BOOLEAN_IDENTITY; } } else if (args[0] instanceof Boolean) { // give value through or unbox handle = BOOLEAN_IDENTITY; } else { //call asBoolean name = "asBoolean"; super.setCallSiteTarget(); } } } private static class PropertySelector extends MethodSelector { private boolean insertName = false; public PropertySelector(MutableCallSite callSite, Class sender, String methodName, CALL_TYPES callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) { super(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); } /** * We never got the interceptor path with a property get */ @Override public boolean setInterceptor() { return false; } /** * this method chooses a property from the meta class. */ @Override public void chooseMeta(MetaClassImpl mci) { Object receiver = getCorrectedReceiver(); if (receiver instanceof GroovyObject) { Class aClass = receiver.getClass(); Method reflectionMethod = null; try { reflectionMethod = aClass.getMethod("getProperty", String.class); if (!reflectionMethod.isSynthetic() && !isMarkedInternal(reflectionMethod)) { handle = MethodHandles.insertArguments(GROOVY_OBJECT_GET_PROPERTY, 1, name); return; } } catch (ReflectiveOperationException e) {} } else if (receiver instanceof Class) { handle = MOP_GET; handle = MethodHandles.insertArguments(handle, 2, name); handle = MethodHandles.insertArguments(handle, 0, this.mc); return; } if (method!=null || mci==null) return; Class chosenSender = this.sender; if (mci.getTheClass()!= chosenSender && GroovyCategorySupport.hasCategoryInCurrentThread()) { chosenSender = mci.getTheClass(); } MetaProperty res = mci.getEffectiveGetMetaProperty(chosenSender, receiver, name, false); if (res instanceof MethodMetaProperty) { MethodMetaProperty mmp = (MethodMetaProperty) res; method = mmp.getMetaMethod(); insertName = true; } else if (res instanceof CachedField) { CachedField cf = (CachedField) res; Field f = cf.field; try { handle = LOOKUP.unreflectGetter(f); if (Modifier.isStatic(f.getModifiers())) { // normally we would do the following // handle = MethodHandles.dropArguments(handle,0,Class.class); // but because there is a bug in invokedynamic in all jdk7 versions // maybe use Unsafe.ensureClassInitialized handle = META_PROPERTY_GETTER.bindTo(res); } } catch (IllegalAccessException iae) { throw new GroovyBugError(iae); } } else { handle = META_PROPERTY_GETTER.bindTo(res); } } private boolean isMarkedInternal(Method reflectionMethod) { return reflectionMethod.getAnnotation(Internal.class) != null; } /** * Additionally to the normal {@link MethodSelector#setHandleForMetaMethod()} * task we have to also take care of generic getter methods, that depend * one the name. */ @Override public void setHandleForMetaMethod() { if (handle!=null) return; super.setHandleForMetaMethod(); if (handle != null && insertName && handle.type().parameterCount()==2) { handle = MethodHandles.insertArguments(handle, 1, name); } } /** * The MOP requires all get property operations to go through * {@link GroovyObject#getProperty(String)}. We do this in case * no property was found before. */ @Override public void setMetaClassCallHandleIfNedded(boolean standardMetaClass) { if (handle!=null) return; useMetaClass = true; if (LOG_ENABLED) LOG.info("set meta class invocation path for property get."); handle = MethodHandles.insertArguments(MOP_GET, 2, this.name); handle = MethodHandles.insertArguments(handle, 0, mc); } } private static class InitSelector extends MethodSelector { private boolean beanConstructor; public InitSelector(MutableCallSite callSite, Class sender, String methodName, CALL_TYPES callType, boolean safeNavigation, boolean thisCall, boolean spreadCall, Object[] arguments) { super(callSite, sender, methodName, callType, safeNavigation, thisCall, spreadCall, arguments); } /** * Constructor calls are not intercepted, thus always returns false. */ @Override public boolean setInterceptor() { return false; } /** * For a constructor call we always use the static meta class from the registry */ @Override public void getMetaClass() { Object receiver = args[0]; mc = GroovySystem.getMetaClassRegistry().getMetaClass((Class) receiver); } /** * This method chooses a constructor from the meta class. */ @Override public void chooseMeta(MetaClassImpl mci) { if (mci==null) return; if (LOG_ENABLED) LOG.info("getting constructor"); Object[] newArgs = removeRealReceiver(args); method = mci.retrieveConstructor(newArgs); if (method instanceof MetaConstructor) { MetaConstructor mcon = (MetaConstructor) method; if (mcon.isBeanConstructor()) { if (LOG_ENABLED) LOG.info("do beans constructor"); beanConstructor = true; } } } /** * Adds {@link MetaConstructor} handling. */ @Override public void setHandleForMetaMethod() { if (method==null) return; if (method instanceof MetaConstructor) { if (LOG_ENABLED) LOG.info("meta method is MetaConstructor instance"); MetaConstructor mc = (MetaConstructor) method; isVargs = mc.isVargsMethod(); Constructor con = mc.getCachedConstrcutor().cachedConstructor; try { handle = LOOKUP.unreflectConstructor(con); if (LOG_ENABLED) LOG.info("successfully unreflected constructor"); } catch (IllegalAccessException e) { throw new GroovyBugError(e); } } else { super.setHandleForMetaMethod(); } if (beanConstructor) { // we have handle that takes no arguments to create the bean, // we have to use its return value to call #setBeanProperties with it // and the meta class. // to do this we first bind the values to #setBeanProperties MethodHandle con = BEAN_CONSTRUCTOR_PROPERTY_SETTER.bindTo(mc); // inner class case MethodType foldTargetType = MethodType.methodType(Object.class); if (args.length==3) { con = MethodHandles.dropArguments(con, 1, targetType.parameterType(1)); foldTargetType = foldTargetType.insertParameterTypes(0, targetType.parameterType(1)); } handle = MethodHandles.foldArguments(con, handle.asType(foldTargetType)); } if (method instanceof MetaConstructor) { handle = MethodHandles.dropArguments(handle, 0, Class.class); } } /** * In case of a bean constructor we don't do any varags or implicit null argument * transformations. Otherwise we do the same as for {@link MethodSelector#correctParameterLength()} */ @Override public void correctParameterLength() { if (beanConstructor) return; super.correctParameterLength(); } /** * In case of a bean constructor we don't do any coercion, otherwise * we do the same as for {@link MethodSelector#correctCoerce()} */ @Override public void correctCoerce() { if (beanConstructor) return; super.correctCoerce(); } /** * Set MOP based constructor invocation path. */ @Override public void setMetaClassCallHandleIfNedded(boolean standardMetaClass) { if (handle!=null) return; useMetaClass = true; if (LOG_ENABLED) LOG.info("set meta class invocation path"); handle = MOP_INVOKE_CONSTRUCTOR.bindTo(mc); handle = handle.asCollector(Object[].class, targetType.parameterCount()-1); handle = MethodHandles.dropArguments(handle, 0, Class.class); if (LOG_ENABLED) LOG.info("create collector for arguments"); } } /** * Method invocation based {@link Selector}. * This Selector is called for method invocations and is base for cosntructor * calls as well as getProperty calls. */ private static class MethodSelector extends Selector { protected MetaClass mc; private boolean isCategoryMethod; public MethodSelector(MutableCallSite callSite, Class sender, String methodName, CALL_TYPES callType, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object[] arguments) { this.callType = callType; this.targetType = callSite.type(); this.name = methodName; this.originalArguments = arguments; this.args = spread(arguments, spreadCall); this.callSite = callSite; this.sender = sender; this.safeNavigationOrig = safeNavigation; this.safeNavigation = safeNavigation && arguments[0]==null; this.thisCall = thisCall; this.spread = spreadCall; this.cache = !spread; if (LOG_ENABLED) { StringBuilder msg = new StringBuilder("----------------------------------------------------" + "\n\t\tinvocation of method '" + methodName + "'" + "\n\t\tinvocation type: " + callType + "\n\t\tsender: " + sender + "\n\t\ttargetType: " + targetType + "\n\t\tsafe navigation: " + safeNavigation + "\n\t\tthisCall: " + thisCall + "\n\t\tspreadCall: " + spreadCall + "\n\t\twith " + arguments.length + " arguments"); for (int i=0; i<arguments.length; i++) { msg.append("\n\t\t\targument[").append(i).append("] = "); if (arguments[i] == null) { msg.append("null"); } else { msg.append(arguments[i].getClass().getName()).append("@").append(Integer.toHexString(System.identityHashCode(arguments[i]))); } } LOG.info(msg.toString()); } } /** * Sets the null constant for safe navigation. * In case of foo?.bar() and foo being null, we don't call the method, * instead we simply return null. This produces a handle, which will * return the constant. */ public boolean setNullForSafeNavigation() { if (!safeNavigation) return false; handle = MethodHandles.dropArguments(NULL_REF,0,targetType.parameterArray()); if (LOG_ENABLED) LOG.info("set null returning handle for safe navigation"); return true; } /** * Gives the meta class to an Object. */ public void getMetaClass() { Object receiver = args[0]; if (receiver == null) { mc = NullObject.getNullObject().getMetaClass(); } else if (receiver instanceof GroovyObject) { mc = ((GroovyObject) receiver).getMetaClass(); } else if (receiver instanceof Class) { Class c = (Class) receiver; ClassLoader cl = c.getClassLoader(); try { Class.forName(c.getName(), true, cl); } catch (ClassNotFoundException e) {} mc = GroovySystem.getMetaClassRegistry().getMetaClass(c); this.cache &= !ClassInfo.getClassInfo(c).hasPerInstanceMetaClasses(); } else { mc = ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(receiver); this.cache &= !ClassInfo.getClassInfo(receiver.getClass()).hasPerInstanceMetaClasses(); } mc.initialize(); } /** * Uses the meta class to get a meta method for a method call. * There will be no meta method selected, if the meta class is no MetaClassImpl * or the meta class is an AdaptingMetaClass. */ public void chooseMeta(MetaClassImpl mci) { if (mci==null) return; Object receiver = getCorrectedReceiver(); Object[] newArgs = removeRealReceiver(args); if (receiver instanceof Class) { if (LOG_ENABLED) LOG.info("receiver is a class"); if (!mci.hasCustomStaticInvokeMethod()) method = mci.retrieveStaticMethod(name, newArgs); } else { String changedName = name; if (receiver instanceof GeneratedClosure && changedName.equals("call")) {changedName = "doCall";} if (!mci.hasCustomInvokeMethod()) method = mci.getMethodWithCaching(selectionBase, changedName, newArgs, false); } if (LOG_ENABLED) LOG.info("retrieved method from meta class: "+method); } /** * Creates a MethodHandle using a before selected MetaMethod. * If the MetaMethod has reflective information available, then * we will use that information to create the target MethodHandle. * If that is not the case we will produce a handle, which will use the * MetaMethod itself for invocation. */ public void setHandleForMetaMethod() { MetaMethod metaMethod = method; isCategoryMethod = method instanceof CategoryMethod; if ( metaMethod instanceof NumberNumberMetaMethod || (method instanceof GeneratedMetaMethod && (name.equals("next") || name.equals("previous"))) ) { if (LOG_ENABLED) LOG.info("meta method is number method"); if (IndyMath.chooseMathMethod(this, metaMethod)) { catchException = false; if (LOG_ENABLED) LOG.info("indy math successful"); return; } } boolean isCategoryTypeMethod = metaMethod instanceof NewInstanceMetaMethod; if (LOG_ENABLED) LOG.info("meta method is category type method: "+isCategoryTypeMethod); boolean isStaticCategoryTypeMethod = metaMethod instanceof NewStaticMetaMethod; if (LOG_ENABLED) LOG.info("meta method is static category type method: "+isCategoryTypeMethod); if (metaMethod instanceof ReflectionMetaMethod) { if (LOG_ENABLED) LOG.info("meta method is reflective method"); ReflectionMetaMethod rmm = (ReflectionMetaMethod) metaMethod; metaMethod = rmm.getCachedMethod(); } if (metaMethod instanceof CachedMethod) { if (LOG_ENABLED) LOG.info("meta method is CachedMethod instance"); CachedMethod cm = (CachedMethod) metaMethod; isVargs = cm.isVargsMethod(); try { Method m = cm.getCachedMethod(); handle = correctClassForNameAndUnReflectOtherwise(m); if (LOG_ENABLED) LOG.info("successfully unreflected method"); if (isStaticCategoryTypeMethod) { handle = MethodHandles.insertArguments(handle, 0, new Object[]{null}); handle = MethodHandles.dropArguments(handle, 0, targetType.parameterType(0)); } else if (!isCategoryTypeMethod && isStatic(m)) { // we drop the receiver, which might be a Class (invocation on Class) // or it might be an object (static method invocation on instance) // Object.class handles both cases at once handle = MethodHandles.dropArguments(handle, 0, Object.class); } } catch (IllegalAccessException e) { throw new GroovyBugError(e); } } else if (method != null) { if (LOG_ENABLED) LOG.info("meta method is dgm helper"); // generic meta method invocation path handle = META_METHOD_INVOKER; handle = handle.bindTo(method); if (spread) { args = originalArguments; skipSpreadCollector = true; } else { // wrap arguments from call site in Object[] handle = handle.asCollector(Object[].class, targetType.parameterCount()-1); } currentType = removeWrapper(targetType); if (LOG_ENABLED) LOG.info("bound method name to META_METHOD_INVOKER"); } } private MethodHandle correctClassForNameAndUnReflectOtherwise(Method m) throws IllegalAccessException { if (m.getDeclaringClass()==Class.class && m.getName().equals("forName") && m.getParameterTypes().length==1) { return MethodHandles.insertArguments(CLASS_FOR_NAME, 1, true, sender.getClassLoader()); } else { return LOOKUP.unreflect(m); } } /** * Helper method to manipulate the given type to replace Wrapper with Object. */ private MethodType removeWrapper(MethodType targetType) { Class[] types = targetType.parameterArray(); for (int i=0; i<types.length; i++) { if (types[i]==Wrapper.class) { targetType = targetType.changeParameterType(i, Object.class); } } return targetType; } /** * Creates a MethodHandle, which will use the meta class path. * This method is called only if no handle has been created before. This * is usually the case if the method selection failed. */ public void setMetaClassCallHandleIfNedded(boolean standardMetaClass) { if (handle!=null) return; useMetaClass = true; if (LOG_ENABLED) LOG.info("set meta class invocation path"); Object receiver = getCorrectedReceiver(); if (receiver instanceof Class) { handle = META_CLASS_INVOKE_STATIC_METHOD.bindTo(mc); if (LOG_ENABLED) LOG.info("use invokeStaticMethod with bound meta class"); } else { handle = MOP_INVOKE_METHOD.bindTo(mc); if (LOG_ENABLED) LOG.info("use invokeMethod with bound meta class"); if (receiver instanceof GroovyObject) { // if the meta class call fails we may still want to fall back to call // GroovyObject#invokeMethod if the receiver is a GroovyObject if (LOG_ENABLED) LOG.info("add MissingMethod handler for GrooObject#invokeMethod fallback path"); handle = MethodHandles.catchException(handle, MissingMethodException.class, GROOVY_OBJECT_INVOKER); } } handle = MethodHandles.insertArguments(handle, 1, name); if (!spread) handle = handle.asCollector(Object[].class, targetType.parameterCount()-1); if (LOG_ENABLED) LOG.info("bind method name and create collector for arguments"); } /** * Corrects method argument wrapping. * In cases in which we want to force a certain method selection * we use Wrapper classes to transport the static type information. * This method will be used to undo the wrapping. */ public void correctWrapping() { if (useMetaClass) return; Class[] pt = handle.type().parameterArray(); if (currentType!=null) pt = currentType.parameterArray(); for (int i=1; i<args.length; i++) { if (args[i] instanceof Wrapper) { Class type = pt[i]; MethodType mt = MethodType.methodType(type, Wrapper.class); handle = MethodHandles.filterArguments(handle, i, UNWRAP_METHOD.asType(mt)); if (LOG_ENABLED) LOG.info("added filter for Wrapper for argument at pos "+i); } } } /** * Handles cases in which we have to correct the length of arguments * using the parameters. This might be needed for vargs and for one * parameter calls without arguments (null is used then). */ public void correctParameterLength() { if (handle==null) return; Class[] params = handle.type().parameterArray(); if (currentType!=null) params = currentType.parameterArray(); if (!isVargs) { if (spread && useMetaClass) return; if (params.length==2 && args.length==1) { //TODO: this Object[] can be constant handle = MethodHandles.insertArguments(handle, 1, new Object[]{null}); } return; } Class lastParam = params[params.length-1]; Object lastArg = unwrapIfWrapped(args[args.length-1]); if (params.length == args.length) { // may need rewrap if (lastArg == null) return; if (lastParam.isInstance(lastArg)) return; if (lastArg.getClass().isArray()) return; // arg is not null and not assignment compatible // so we really need to rewrap handle = handle.asCollector(lastParam, 1); } else if (params.length > args.length) { // we depend on the method selection having done a good // job before already, so the only case for this here is, that // we have no argument for the array, meaning params.length is // args.length+1. In that case we have to fill in an empty array handle = MethodHandles.insertArguments(handle, params.length-1, Array.newInstance(lastParam.getComponentType(), 0)); if (LOG_ENABLED) LOG.info("added empty array for missing vargs part"); } else { //params.length < args.length // we depend on the method selection having done a good // job before already, so the only case for this here is, that // all trailing arguments belong into the vargs array handle = handle.asCollector( lastParam, args.length - params.length + 1); if (LOG_ENABLED) LOG.info("changed surplus arguments to be collected for vargs call"); } } /** * There are some conversions we have to do explicitly. * These are GString to String, Number to Byte and Number to BigInteger * conversions. */ public void correctCoerce() { if (useMetaClass) return; Class[] parameters = handle.type().parameterArray(); if (currentType!=null) parameters = currentType.parameterArray(); if (args.length != parameters.length) { throw new GroovyBugError("At this point argument array length and parameter array length should be the same"); } for (int i=0; i<args.length; i++) { if (parameters[i]==Object.class) continue; Object arg = unwrapIfWrapped(args[i]); // we have to handle here different cases in which we do no // transformations. We depend on our method selection to have // selected only a compatible method, that means for a null // argument we don't have to do anything. Same of course is if // the argument is an instance of the parameter type. We also // exclude boxing, since the MethodHandles will do that part // already for us. Another case is the conversion of a primitive // to another primitive or of the wrappers, or a combination of // these. This is also handled already. What is left is the // GString conversion and the number conversions. if (arg==null) continue; Class got = arg.getClass(); // equal class, nothing to do if (got==parameters[i]) continue; Class wrappedPara = TypeHelper.getWrapperClass(parameters[i]); // equal class with one maybe a primitive, the later explicitCastArguments will solve this case if (wrappedPara==TypeHelper.getWrapperClass(got)) continue; // equal in terms of an assignment in Java. That means according to Java widening rules, or // a subclass, interface, superclass relation, this case then handles also // primitive to primitive conversion. Those case are also solved by explicitCastArguments. if (parameters[i].isAssignableFrom(got)) continue; // to aid explicitCastArguments we convert to the wrapper type to let is only unbox handle = TypeTransformers.addTransformer(handle, i, arg, wrappedPara); if (LOG_ENABLED) LOG.info("added transformer at pos "+i+" for type "+got+" to type "+wrappedPara); } } /** * Gives a replacement receiver for null. * In case of the receiver being null we want to do the method * invocation on NullObject instead. */ public void correctNullReceiver() { if (args[0]!=null) return; handle = handle.bindTo(NullObject.getNullObject()); handle = MethodHandles.dropArguments(handle, 0, targetType.parameterType(0)); if (LOG_ENABLED) LOG.info("binding null object receiver and dropping old receiver"); } public void correctSpreading() { if (!spread || useMetaClass || skipSpreadCollector) return; handle = handle.asSpreader(Object[].class, args.length-1); } /** * Adds the standard exception handler. */ public void addExceptionHandler() { //TODO: if we would know exactly which paths require the exceptions // and which paths not, we can sometimes save this guard if (handle==null || !catchException) return; Class returnType = handle.type().returnType(); if (returnType!=Object.class) { MethodType mtype = MethodType.methodType(returnType, GroovyRuntimeException.class); handle = MethodHandles.catchException(handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION.asType(mtype)); } else { handle = MethodHandles.catchException(handle, GroovyRuntimeException.class, UNWRAP_EXCEPTION); } if (LOG_ENABLED) LOG.info("added GroovyRuntimeException unwrapper"); } /** * Sets all argument and receiver guards. */ public void setGuards (Object receiver) { if (handle==null) return; if (!cache) return; MethodHandle fallback = makeFallBack(callSite, sender, name, callType.ordinal(), targetType, safeNavigationOrig, thisCall, spread); // special guards for receiver if (receiver instanceof GroovyObject) { GroovyObject go = (GroovyObject) receiver; MetaClass mc = (MetaClass) go.getMetaClass(); MethodHandle test = SAME_MC.bindTo(mc); // drop dummy receiver test = test.asType(MethodType.methodType(boolean.class,targetType.parameterType(0))); handle = MethodHandles.guardWithTest(test, handle, fallback); if (LOG_ENABLED) LOG.info("added meta class equality check"); } else if (receiver instanceof Class) { MethodHandle test = EQUALS.bindTo(receiver); test = test.asType(MethodType.methodType(boolean.class,targetType.parameterType(0))); handle = MethodHandles.guardWithTest(test, handle, fallback); if (LOG_ENABLED) LOG.info("added class equality check"); } if (!useMetaClass && isCategoryMethod) { // category method needs Thread check // cases: // (1) method is a category method // We need to check if the category in the current thread is still active. // Since we invalidate on leaving the category checking for it being // active directly is good enough. // (2) method is in use scope, but not from category // Since entering/leaving a category will invalidate, there is no need for any special check // (3) method is not in use scope /and not from category // Since entering/leaving a category will invalidate, there is no need for any special check if (method instanceof NewInstanceMetaMethod) { handle = MethodHandles.guardWithTest(HAS_CATEGORY_IN_CURRENT_THREAD_GUARD, handle, fallback); if (LOG_ENABLED) LOG.info("added category-in-current-thread-guard for category method"); } } // handle constant meta class and category changes handle = switchPoint.guardWithTest(handle, fallback); if (LOG_ENABLED) LOG.info("added switch point guard"); // guards for receiver and parameter Class[] pt = handle.type().parameterArray(); for (int i=0; i<args.length; i++) { Object arg = args[i]; MethodHandle test = null; if (arg==null) { test = IS_NULL.asType(MethodType.methodType(boolean.class, pt[i])); if (LOG_ENABLED) LOG.info("added null argument check at pos "+i); } else { Class argClass = arg.getClass(); if (pt[i].isPrimitive()) continue; //if (Modifier.isFinal(argClass.getModifiers()) && TypeHelper.argumentClassIsParameterClass(argClass,pt[i])) continue; test = SAME_CLASS. bindTo(argClass). asType(MethodType.methodType(boolean.class, pt[i])); if (LOG_ENABLED) LOG.info("added same class check at pos "+i); } Class[] drops = new Class[i]; System.arraycopy(pt, 0, drops, 0, drops.length); test = MethodHandles.dropArguments(test, 0, drops); handle = MethodHandles.guardWithTest(test, handle, fallback); } } /** * do the actual call site target set, if the call is supposed to be cached */ public void doCallSiteTargetSet() { if (!cache) { if (LOG_ENABLED) LOG.info("call site stays uncached"); } else { callSite.setTarget(handle); if (LOG_ENABLED) LOG.info("call site target set, preparing outside invocation"); } } /** * Sets the selection base. */ public void setSelectionBase() { if (thisCall) { selectionBase = sender; } else if (args[0]==null) { selectionBase = NullObject.class; } else { selectionBase = mc.getTheClass(); } if (LOG_ENABLED) LOG.info("selection base set to "+selectionBase); } /** * Sets a handle to call {@link GroovyInterceptable#invokeMethod(String, Object)} */ public boolean setInterceptor() { if (!(this.args[0] instanceof GroovyInterceptable)) return false; handle = MethodHandles.insertArguments(INTERCEPTABLE_INVOKER, 1, this.name); handle = handle.asCollector(Object[].class, targetType.parameterCount()-1); handle = handle.asType(targetType); return true; } /** * setting a call site target consists of the following steps: * # get the meta class * # select a method/constructor/property from it, if it is a MetaClassImpl * # make a handle out of the selection * # if nothing could be selected select a path through the given MetaClass or the GroovyObject * # apply transformations for vargs, implicit null argument, coercion, wrapping, null receiver and spreading */ @Override public void setCallSiteTarget() { if (!setNullForSafeNavigation() && !setInterceptor()) { getMetaClass(); if (LOG_ENABLED) LOG.info("meta class is "+mc); setSelectionBase(); MetaClassImpl mci = getMetaClassImpl(mc, callType != CALL_TYPES.GET); chooseMeta(mci); setHandleForMetaMethod(); setMetaClassCallHandleIfNedded(mci!=null); correctParameterLength(); correctCoerce(); correctWrapping(); correctNullReceiver(); correctSpreading(); if (LOG_ENABLED) LOG.info("casting explicit from "+handle.type()+" to "+targetType); handle = MethodHandles.explicitCastArguments(handle,targetType); addExceptionHandler(); } setGuards(args[0]); doCallSiteTargetSet(); } } /** * Unwraps the given object from a {@link Wrapper}. If not * wrapped, the given object is returned. */ private static Object unwrapIfWrapped(Object object) { if (object instanceof Wrapper) return unwrap(object); return object; } /** * Returns {@link NullObject#getNullObject()} if the receiver * (args[0]) is null. If it is not null, the recevier itself * is returned. */ public Object getCorrectedReceiver() { Object receiver = args[0]; if (receiver==null) { if (LOG_ENABLED) LOG.info("receiver is null"); receiver = NullObject.getNullObject(); } return receiver; } /** * Returns if a method is static */ private static boolean isStatic(Method m) { int mods = m.getModifiers(); return (mods & Modifier.STATIC) != 0; } /** * Returns the MetaClassImpl if the given MetaClass is one of * MetaClassImpl, AdaptingMetaClass or ClosureMetaClass. If * none of these cases matches, this method returns null. */ private static MetaClassImpl getMetaClassImpl(MetaClass mc, boolean includeEMC) { Class mcc = mc.getClass(); boolean valid = mcc == MetaClassImpl.class || mcc == AdaptingMetaClass.class || mcc == ClosureMetaClass.class || (includeEMC && mcc == ExpandoMetaClass.class); if (!valid) { if (LOG_ENABLED) LOG.info("meta class is neither MetaClassImpl, nor AdoptingMetaClass, nor ClosureMetaClass, normal method selection path disabled."); return null; } if (LOG_ENABLED) LOG.info("meta class is a recognized MetaClassImpl"); return (MetaClassImpl) mc; } /** * Helper method to remove the receiver from the argument array * by producing a new array. */ private static Object[] removeRealReceiver(Object[] args) { Object[] ar = new Object[args.length-1]; System.arraycopy(args, 1, ar, 0, args.length - 1); return ar; } }
jwagenleitner/incubator-groovy
src/main/java/org/codehaus/groovy/vmplugin/v7/Selector.java
Java
apache-2.0
50,364
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import org.apache.lucene.search.MatchNoDocsQuery; import org.apache.lucene.search.Query; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.Uid; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import static org.elasticsearch.common.xcontent.ObjectParser.fromList; /** * A query that will return only documents matching specific ids (and a type). */ public class IdsQueryBuilder extends AbstractQueryBuilder<IdsQueryBuilder> { public static final String NAME = "ids"; private static final ParseField TYPE_FIELD = new ParseField("type"); private static final ParseField VALUES_FIELD = new ParseField("values"); private final Set<String> ids = new HashSet<>(); private String[] types = Strings.EMPTY_ARRAY; /** * Creates a new IdsQueryBuilder with no types specified upfront */ public IdsQueryBuilder() { // nothing to do } /** * Read from a stream. */ public IdsQueryBuilder(StreamInput in) throws IOException { super(in); types = in.readStringArray(); Collections.addAll(ids, in.readStringArray()); } @Override protected void doWriteTo(StreamOutput out) throws IOException { out.writeStringArray(types); out.writeStringArray(ids.toArray(new String[ids.size()])); } /** * Add types to query */ // TODO: Remove public IdsQueryBuilder types(String... types) { if (types == null) { throw new IllegalArgumentException("[" + NAME + "] types cannot be null"); } this.types = types; return this; } /** * Returns the types used in this query */ public String[] types() { return this.types; } /** * Adds ids to the query. */ public IdsQueryBuilder addIds(String... ids) { if (ids == null) { throw new IllegalArgumentException("[" + NAME + "] ids cannot be null"); } Collections.addAll(this.ids, ids); return this; } /** * Returns the ids for the query. */ public Set<String> ids() { return this.ids; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.array(TYPE_FIELD.getPreferredName(), types); builder.startArray(VALUES_FIELD.getPreferredName()); for (String value : ids) { builder.value(value); } builder.endArray(); printBoostAndQueryName(builder); builder.endObject(); } private static ObjectParser<IdsQueryBuilder, Void> PARSER = new ObjectParser<>(NAME, () -> new IdsQueryBuilder()); static { PARSER.declareStringArray(fromList(String.class, IdsQueryBuilder::types), IdsQueryBuilder.TYPE_FIELD); PARSER.declareStringArray(fromList(String.class, IdsQueryBuilder::addIds), IdsQueryBuilder.VALUES_FIELD); declareStandardFields(PARSER); } public static IdsQueryBuilder fromXContent(XContentParser parser) { try { return PARSER.apply(parser, null); } catch (IllegalArgumentException e) { throw new ParsingException(parser.getTokenLocation(), e.getMessage(), e); } } @Override public String getWriteableName() { return NAME; } @Override protected Query doToQuery(QueryShardContext context) throws IOException { MappedFieldType idField = context.fieldMapper(IdFieldMapper.NAME); if (idField == null) { return new MatchNoDocsQuery("No mappings"); } if (this.ids.isEmpty()) { return Queries.newMatchNoDocsQuery("Missing ids in \"" + this.getName() + "\" query."); } else { Collection<String> typesForQuery; if (types.length == 0) { typesForQuery = context.queryTypes(); } else if (types.length == 1 && MetaData.ALL.equals(types[0])) { typesForQuery = context.getMapperService().types(); } else { typesForQuery = new HashSet<>(); Collections.addAll(typesForQuery, types); } final Collection<String> mappingTypes = context.getMapperService().types(); assert mappingTypes.size() == 1; if (typesForQuery.contains(mappingTypes.iterator().next())) { return idField.termsQuery(new ArrayList<>(ids), context); } else { return new MatchNoDocsQuery("Type mismatch"); } } } @Override protected int doHashCode() { return Objects.hash(ids, Arrays.hashCode(types)); } @Override protected boolean doEquals(IdsQueryBuilder other) { return Objects.equals(ids, other.ids) && Arrays.equals(types, other.types); } }
rajanm/elasticsearch
server/src/main/java/org/elasticsearch/index/query/IdsQueryBuilder.java
Java
apache-2.0
6,506
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.compiled; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiNameHelper; import com.intellij.psi.PsiReferenceList; import com.intellij.psi.impl.cache.ModifierFlags; import com.intellij.psi.impl.cache.TypeInfo; import com.intellij.psi.impl.java.stubs.*; import com.intellij.psi.impl.java.stubs.impl.*; import com.intellij.psi.stubs.PsiFileStub; import com.intellij.psi.stubs.StubElement; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.cls.ClsFormatException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.org.objectweb.asm.*; import java.lang.reflect.Array; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.List; import java.util.Map; import java.util.Set; import static com.intellij.openapi.util.Pair.pair; import static com.intellij.psi.CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION; import static com.intellij.psi.CommonClassNames.JAVA_LANG_STRING; import static com.intellij.psi.impl.compiled.ClsFileImpl.EMPTY_ATTRIBUTES; import static com.intellij.util.BitUtil.isSet; /** * @author max */ public class StubBuildingVisitor<T> extends ClassVisitor { private static final Logger LOG = Logger.getInstance(StubBuildingVisitor.class); private static final String DOUBLE_POSITIVE_INF = "1.0 / 0.0"; private static final String DOUBLE_NEGATIVE_INF = "-1.0 / 0.0"; private static final String DOUBLE_NAN = "0.0d / 0.0"; private static final String FLOAT_POSITIVE_INF = "1.0f / 0.0"; private static final String FLOAT_NEGATIVE_INF = "-1.0f / 0.0"; private static final String FLOAT_NAN = "0.0f / 0.0"; private static final String SYNTHETIC_CLASS_INIT_METHOD = "<clinit>"; private static final String SYNTHETIC_INIT_METHOD = "<init>"; private static final int ASM_API = Opcodes.ASM5; private final T mySource; private final InnerClassSourceStrategy<T> myInnersStrategy; private final StubElement myParent; private final int myAccess; private final String myShortName; private final Function<String, String> myMapping; private String myInternalName; private PsiClassStub myResult; private PsiModifierListStub myModList; public StubBuildingVisitor(T classSource, InnerClassSourceStrategy<T> innersStrategy, StubElement parent, int access, String shortName) { super(ASM_API); mySource = classSource; myInnersStrategy = innersStrategy; myParent = parent; myAccess = access; myShortName = shortName; myMapping = createMapping(classSource); } public PsiClassStub<?> getResult() { return myResult; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { myInternalName = name; String parentName = myParent instanceof PsiClassStub ? ((PsiClassStub)myParent).getQualifiedName() : myParent instanceof PsiJavaFileStub ? ((PsiJavaFileStub)myParent).getPackageName() : null; String fqn = getFqn(name, myShortName, parentName); String shortName = myShortName != null && name.endsWith(myShortName) ? myShortName : PsiNameHelper.getShortClassName(fqn); int flags = myAccess | access; boolean isDeprecated = isSet(flags, Opcodes.ACC_DEPRECATED); boolean isInterface = isSet(flags, Opcodes.ACC_INTERFACE); boolean isEnum = isSet(flags, Opcodes.ACC_ENUM); boolean isAnnotationType = isSet(flags, Opcodes.ACC_ANNOTATION); byte stubFlags = PsiClassStubImpl.packFlags(isDeprecated, isInterface, isEnum, false, false, isAnnotationType, false, false); myResult = new PsiClassStubImpl(JavaStubElementTypes.CLASS, myParent, fqn, shortName, null, stubFlags); LanguageLevel languageLevel = ClsParsingUtil.getLanguageLevelByVersion(version); if (languageLevel == null) languageLevel = LanguageLevel.HIGHEST; ((PsiClassStubImpl)myResult).setLanguageLevel(languageLevel); myModList = new PsiModifierListStubImpl(myResult, packClassFlags(flags)); ClassInfo info = null; if (signature != null) { try { info = parseClassSignature(signature); } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (info == null) { info = parseClassDescription(superName, interfaces); } PsiTypeParameterListStub typeParameterList = new PsiTypeParameterListStubImpl(myResult); for (Pair<String, String[]> parameter : info.typeParameters) { PsiTypeParameterStub parameterStub = new PsiTypeParameterStubImpl(typeParameterList, StringRef.fromString(parameter.first)); newReferenceList(JavaStubElementTypes.EXTENDS_BOUND_LIST, parameterStub, parameter.second); } if (myResult.isInterface()) { if (info.interfaceNames != null && myResult.isAnnotationType()) { info.interfaceNames.remove(JAVA_LANG_ANNOTATION_ANNOTATION); } newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.toStringArray(info.interfaceNames)); newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY); } else { if (info.superName == null || "java/lang/Object".equals(superName) || myResult.isEnum() && "java/lang/Enum".equals(superName)) { newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, ArrayUtil.EMPTY_STRING_ARRAY); } else { newReferenceList(JavaStubElementTypes.EXTENDS_LIST, myResult, new String[]{info.superName}); } newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, myResult, ArrayUtil.toStringArray(info.interfaceNames)); } } private String getFqn(@NotNull String internalName, @Nullable String shortName, @Nullable String parentName) { if (shortName == null || !internalName.endsWith(shortName)) { return myMapping.fun(internalName); } if (internalName.length() == shortName.length()) { return shortName; } if (parentName == null) { parentName = myMapping.fun(internalName.substring(0, internalName.length() - shortName.length() - 1)); } return parentName + '.' + shortName; } private ClassInfo parseClassSignature(String signature) throws ClsFormatException { ClassInfo result = new ClassInfo(); CharacterIterator iterator = new StringCharacterIterator(signature); result.typeParameters = SignatureParsing.parseTypeParametersDeclaration(iterator, myMapping); result.superName = SignatureParsing.parseTopLevelClassRefSignature(iterator, myMapping); while (iterator.current() != CharacterIterator.DONE) { String name = SignatureParsing.parseTopLevelClassRefSignature(iterator, myMapping); if (name == null) throw new ClsFormatException(); if (result.interfaceNames == null) result.interfaceNames = ContainerUtil.newSmartList(); result.interfaceNames.add(name); } return result; } private ClassInfo parseClassDescription(String superClass, String[] superInterfaces) { ClassInfo result = new ClassInfo(); result.typeParameters = ContainerUtil.emptyList(); result.superName = superClass != null ? myMapping.fun(superClass) : null; result.interfaceNames = superInterfaces == null ? null : ContainerUtil.map(superInterfaces, new Function<String, String>() { @Override public String fun(String name) { return myMapping.fun(name); } }); return result; } private static void newReferenceList(JavaClassReferenceListElementType type, StubElement parent, String[] types) { PsiReferenceList.Role role; if (type == JavaStubElementTypes.EXTENDS_LIST) role = PsiReferenceList.Role.EXTENDS_LIST; else if (type == JavaStubElementTypes.IMPLEMENTS_LIST) role = PsiReferenceList.Role.IMPLEMENTS_LIST; else if (type == JavaStubElementTypes.THROWS_LIST) role = PsiReferenceList.Role.THROWS_LIST; else if (type == JavaStubElementTypes.EXTENDS_BOUND_LIST) role = PsiReferenceList.Role.EXTENDS_BOUNDS_LIST; else throw new IllegalArgumentException("Unknown type: " + type); new PsiClassReferenceListStubImpl(type, parent, types, role); } private static int packCommonFlags(int access) { int flags = 0; if (isSet(access, Opcodes.ACC_PRIVATE)) flags |= ModifierFlags.PRIVATE_MASK; else if (isSet(access, Opcodes.ACC_PROTECTED)) flags |= ModifierFlags.PROTECTED_MASK; else if (isSet(access, Opcodes.ACC_PUBLIC)) flags |= ModifierFlags.PUBLIC_MASK; else flags |= ModifierFlags.PACKAGE_LOCAL_MASK; if (isSet(access, Opcodes.ACC_STATIC)) flags |= ModifierFlags.STATIC_MASK; if (isSet(access, Opcodes.ACC_FINAL)) flags |= ModifierFlags.FINAL_MASK; return flags; } private static int packClassFlags(int access) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_ABSTRACT)) flags |= ModifierFlags.ABSTRACT_MASK; return flags; } private static int packFieldFlags(int access) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_VOLATILE)) flags |= ModifierFlags.VOLATILE_MASK; if (isSet(access, Opcodes.ACC_TRANSIENT)) flags |= ModifierFlags.TRANSIENT_MASK; return flags; } private static int packMethodFlags(int access, boolean isInterface) { int flags = packCommonFlags(access); if (isSet(access, Opcodes.ACC_SYNCHRONIZED)) flags |= ModifierFlags.SYNCHRONIZED_MASK; if (isSet(access, Opcodes.ACC_NATIVE)) flags |= ModifierFlags.NATIVE_MASK; if (isSet(access, Opcodes.ACC_STRICT)) flags |= ModifierFlags.STRICTFP_MASK; if (isSet(access, Opcodes.ACC_ABSTRACT)) flags |= ModifierFlags.ABSTRACT_MASK; else if (isInterface && !isSet(access, Opcodes.ACC_STATIC)) flags |= ModifierFlags.DEFENDER_MASK; return flags; } @Override public void visitSource(String source, String debug) { ((PsiClassStubImpl)myResult).setSourceFileName(source); } @Override public void visitOuterClass(String owner, String name, String desc) { if (myParent instanceof PsiFileStub) { throw new OutOfOrderInnerClassException(); } } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { new PsiAnnotationStubImpl(myModList, text); } }); } @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (isSet(access, Opcodes.ACC_SYNTHETIC)) return; if (innerName == null || outerName == null) return; if (myParent instanceof PsiFileStub && myInternalName.equals(name)) { throw new OutOfOrderInnerClassException(); // our result is inner class } if (myInternalName.equals(outerName)) { T innerClass = myInnersStrategy.findInnerClass(innerName, mySource); if (innerClass != null) { myInnersStrategy.accept(innerClass, new StubBuildingVisitor<T>(innerClass, myInnersStrategy, myResult, access, innerName)); } } } @Override @Nullable public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (isSet(access, Opcodes.ACC_SYNTHETIC)) return null; if (name == null) return null; byte flags = PsiFieldStubImpl.packFlags(isSet(access, Opcodes.ACC_ENUM), isSet(access, Opcodes.ACC_DEPRECATED), false, false); TypeInfo type = fieldType(desc, signature); String initializer = constToString(value, type.text, false, myMapping); PsiFieldStub stub = new PsiFieldStubImpl(myResult, name, type, initializer, flags); PsiModifierListStub modList = new PsiModifierListStubImpl(stub, packFieldFlags(access)); return new FieldAnnotationCollectingVisitor(modList, myMapping); } private TypeInfo fieldType(String desc, String signature) { String type = null; if (signature != null) { try { type = SignatureParsing.parseTypeString(new StringCharacterIterator(signature), myMapping); } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (type == null) { type = toJavaType(Type.getType(desc), myMapping); } return TypeInfo.fromString(type, false); } private static final String[] parameterNames = {"p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"}; @Override @Nullable public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // JLS 13.1 says: Any constructs introduced by the compiler that do not have a corresponding construct in the source code // must be marked as synthetic, except for default constructors and the class initialization method. // However Scala compiler erroneously generates ACC_BRIDGE instead of ACC_SYNTHETIC flag for in-trait implementation delegation. // See IDEA-78649 if (isSet(access, Opcodes.ACC_SYNTHETIC)) return null; if (name == null) return null; if (SYNTHETIC_CLASS_INIT_METHOD.equals(name)) return null; // skip semi-synthetic enum methods boolean isEnum = myResult.isEnum(); if (isEnum) { if ("values".equals(name) && desc.startsWith("()")) return null; //noinspection SpellCheckingInspection if ("valueOf".equals(name) && desc.startsWith("(Ljava/lang/String;)")) return null; } boolean isConstructor = SYNTHETIC_INIT_METHOD.equals(name); boolean isDeprecated = isSet(access, Opcodes.ACC_DEPRECATED); boolean isVarargs = isSet(access, Opcodes.ACC_VARARGS); boolean isStatic = isSet(access, Opcodes.ACC_STATIC); boolean isAnnotationMethod = myResult.isAnnotationType(); byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false, false); String canonicalMethodName = isConstructor ? myResult.getName() : name; MethodInfo info = null; boolean generic = false; if (signature != null) { try { info = parseMethodSignature(signature, exceptions); generic = true; } catch (ClsFormatException e) { if (LOG.isDebugEnabled()) LOG.debug("source=" + mySource + " signature=" + signature, e); } } if (info == null) { info = parseMethodDescription(desc, exceptions); } PsiMethodStubImpl stub = new PsiMethodStubImpl(myResult, canonicalMethodName, TypeInfo.fromString(info.returnType, false), flags, null); PsiModifierListStub modList = new PsiModifierListStubImpl(stub, packMethodFlags(access, myResult.isInterface())); PsiTypeParameterListStub list = new PsiTypeParameterListStubImpl(stub); for (Pair<String, String[]> parameter : info.typeParameters) { PsiTypeParameterStub parameterStub = new PsiTypeParameterStubImpl(list, StringRef.fromString(parameter.first)); newReferenceList(JavaStubElementTypes.EXTENDS_BOUND_LIST, parameterStub, parameter.second); } boolean isEnumConstructor = isEnum && isConstructor; boolean isInnerClassConstructor = isConstructor && !(myParent instanceof PsiFileStub) && !isSet(myModList.getModifiersMask(), Opcodes.ACC_STATIC); List<String> args = info.argTypes; if (!generic && isEnumConstructor && args.size() >= 2 && JAVA_LANG_STRING.equals(args.get(0)) && "int".equals(args.get(1))) { // omit synthetic enum constructor parameters args = args.subList(2, args.size()); } PsiParameterListStubImpl parameterList = new PsiParameterListStubImpl(stub); int paramCount = args.size(); PsiParameterStubImpl[] paramStubs = new PsiParameterStubImpl[paramCount]; for (int i = 0; i < paramCount; i++) { // omit synthetic inner class constructor parameter if (i == 0 && !generic && isInnerClassConstructor) continue; String arg = args.get(i); boolean isEllipsisParam = isVarargs && i == paramCount - 1; TypeInfo typeInfo = TypeInfo.fromString(arg, isEllipsisParam); String paramName = i < parameterNames.length ? parameterNames[i] : "p" + (i + 1); PsiParameterStubImpl parameterStub = new PsiParameterStubImpl(parameterList, paramName, typeInfo, isEllipsisParam, true); paramStubs[i] = parameterStub; new PsiModifierListStubImpl(parameterStub, 0); } newReferenceList(JavaStubElementTypes.THROWS_LIST, stub, ArrayUtil.toStringArray(info.throwTypes)); int localVarIgnoreCount = isStatic ? 0 : isEnumConstructor ? 3 : 1; int paramIgnoreCount = isEnumConstructor ? 2 : isInnerClassConstructor ? 1 : 0; return new MethodAnnotationCollectingVisitor(stub, modList, localVarIgnoreCount, paramIgnoreCount, paramCount, paramStubs, myMapping); } private MethodInfo parseMethodSignature(String signature, String[] exceptions) throws ClsFormatException { MethodInfo result = new MethodInfo(); CharacterIterator iterator = new StringCharacterIterator(signature); result.typeParameters = SignatureParsing.parseTypeParametersDeclaration(iterator, myMapping); if (iterator.current() != '(') throw new ClsFormatException(); iterator.next(); if (iterator.current() == ')') { result.argTypes = ContainerUtil.emptyList(); } else { result.argTypes = ContainerUtil.newSmartList(); while (iterator.current() != ')' && iterator.current() != CharacterIterator.DONE) { result.argTypes.add(SignatureParsing.parseTypeString(iterator, myMapping)); } if (iterator.current() != ')') throw new ClsFormatException(); } iterator.next(); result.returnType = SignatureParsing.parseTypeString(iterator, myMapping); result.throwTypes = null; while (iterator.current() == '^') { iterator.next(); if (result.throwTypes == null) result.throwTypes = ContainerUtil.newSmartList(); result.throwTypes.add(SignatureParsing.parseTypeString(iterator, myMapping)); } if (exceptions != null && (result.throwTypes == null || exceptions.length > result.throwTypes.size())) { // a signature may be inconsistent with exception list - in this case, the more complete list takes precedence result.throwTypes = ContainerUtil.map(exceptions, new Function<String, String>() { @Override public String fun(String name) { return myMapping.fun(name); } }); } return result; } private MethodInfo parseMethodDescription(String desc, String[] exceptions) { MethodInfo result = new MethodInfo(); result.typeParameters = ContainerUtil.emptyList(); result.returnType = toJavaType(Type.getReturnType(desc), myMapping); result.argTypes = ContainerUtil.map(Type.getArgumentTypes(desc), new Function<Type, String>() { @Override public String fun(Type type) { return toJavaType(type, myMapping); } }); result.throwTypes = exceptions == null ? null : ContainerUtil.map(exceptions, new Function<String, String>() { @Override public String fun(String name) { return myMapping.fun(name); } }); return result; } private static class ClassInfo { private List<Pair<String, String[]>> typeParameters; private String superName; private List<String> interfaceNames; } private static class MethodInfo { private List<Pair<String, String[]>> typeParameters; private String returnType; private List<String> argTypes; private List<String> throwTypes; } private static class AnnotationTextCollector extends AnnotationVisitor { private final StringBuilder myBuilder = new StringBuilder(); private final Function<String, String> myMapping; private final Consumer<String> myCallback; private boolean hasPrefix; private boolean hasParams; public AnnotationTextCollector(@Nullable String desc, Function<String, String> mapping, Consumer<String> callback) { super(ASM_API); myMapping = mapping; myCallback = callback; if (desc != null) { hasPrefix = true; myBuilder.append('@').append(toJavaType(Type.getType(desc), myMapping)); } } @Override public void visit(String name, Object value) { valuePairPrefix(name); myBuilder.append(constToString(value, null, true, myMapping)); } @Override public void visitEnum(String name, String desc, String value) { valuePairPrefix(name); myBuilder.append(toJavaType(Type.getType(desc), myMapping)).append('.').append(value); } private void valuePairPrefix(String name) { if (!hasParams) { hasParams = true; if (hasPrefix) { myBuilder.append('('); } } else { myBuilder.append(','); } if (name != null) { myBuilder.append(name).append('='); } } @Override public AnnotationVisitor visitAnnotation(String name, String desc) { valuePairPrefix(name); return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { myBuilder.append(text); } }); } @Override public AnnotationVisitor visitArray(String name) { valuePairPrefix(name); myBuilder.append('{'); return new AnnotationTextCollector(null, myMapping, new Consumer<String>() { @Override public void consume(String text) { myBuilder.append(text).append('}'); } }); } @Override public void visitEnd() { if (hasPrefix && hasParams) { myBuilder.append(')'); } myCallback.consume(myBuilder.toString()); } } private static class FieldAnnotationCollectingVisitor extends FieldVisitor { private final PsiModifierListStub myModList; private final Function<String, String> myMapping; private Set<String> myFilter; private FieldAnnotationCollectingVisitor(PsiModifierListStub modList, Function<String, String> mapping) { super(ASM_API); myModList = modList; myMapping = mapping; } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { if (myFilter == null) myFilter = ContainerUtil.newTroveSet(); myFilter.add(text); new PsiAnnotationStubImpl(myModList, text); } }); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, final TypePath typePath, String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { if (typePath == null && (myFilter == null || !myFilter.contains(text))) { new PsiAnnotationStubImpl(myModList, text); } } }); } } private static class MethodAnnotationCollectingVisitor extends MethodVisitor { private final PsiMethodStub myOwner; private final PsiModifierListStub myModList; private final int myIgnoreCount; private final int myParamIgnoreCount; private final int myParamCount; private final PsiParameterStubImpl[] myParamStubs; private final Function<String, String> myMapping; private int myUsedParamSize; private int myUsedParamCount; private List<Set<String>> myFilters; private MethodAnnotationCollectingVisitor(PsiMethodStub owner, PsiModifierListStub modList, int ignoreCount, int paramIgnoreCount, int paramCount, PsiParameterStubImpl[] paramStubs, Function<String, String> mapping) { super(ASM_API); myOwner = owner; myModList = modList; myIgnoreCount = ignoreCount; myParamIgnoreCount = paramIgnoreCount; myParamCount = paramCount; myParamStubs = paramStubs; myMapping = mapping; } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { filter(0, text); new PsiAnnotationStubImpl(myModList, text); } }); } @Override @Nullable public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc, boolean visible) { return parameter < myParamIgnoreCount ? null : new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { int idx = parameter - myParamIgnoreCount; filter(idx + 1, text); new PsiAnnotationStubImpl(myOwner.findParameter(idx).getModList(), text); } }); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, final TypePath typePath, String desc, boolean visible) { final TypeReference ref = new TypeReference(typeRef); return new AnnotationTextCollector(desc, myMapping, new Consumer<String>() { @Override public void consume(String text) { if (ref.getSort() == TypeReference.METHOD_RETURN && typePath == null && !filtered(0, text)) { new PsiAnnotationStubImpl(myModList, text); } else if (ref.getSort() == TypeReference.METHOD_FORMAL_PARAMETER && typePath == null) { int idx = ref.getFormalParameterIndex() - myParamIgnoreCount; if (!filtered(idx + 1, text)) { new PsiAnnotationStubImpl(myOwner.findParameter(idx).getModList(), text); } } } }); } @Override public AnnotationVisitor visitAnnotationDefault() { return new AnnotationTextCollector(null, myMapping, new Consumer<String>() { @Override public void consume(String text) { ((PsiMethodStubImpl)myOwner).setDefaultValueText(text); } }); } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { if (index >= myIgnoreCount) { // long and double variables increase the index by 2, not by 1 int paramIndex = (index - myIgnoreCount == myUsedParamSize) ? myUsedParamCount : index - myIgnoreCount; if (paramIndex >= myParamCount) return; if (ClsParsingUtil.isJavaIdentifier(name, LanguageLevel.HIGHEST)) { PsiParameterStubImpl parameterStub = myParamStubs[paramIndex]; if (parameterStub != null) { parameterStub.setName(name); } } myUsedParamCount = paramIndex + 1; myUsedParamSize += "D".equals(desc) || "J".equals(desc) ? 2 : 1; } } private void filter(int index, String text) { if (myFilters == null) { myFilters = ContainerUtil.newArrayListWithCapacity(myParamCount + 1); for (int i = 0; i < myParamCount + 1; i++) myFilters.add(null); } Set<String> filter = myFilters.get(index); if (filter == null) myFilters.set(index, (filter = ContainerUtil.newTroveSet())); filter.add(text); } private boolean filtered(int index, String text) { return myFilters != null && myFilters.get(index) != null && myFilters.get(index).contains(text); } } @Nullable private static String constToString(@Nullable Object value, @Nullable String type, boolean anno, Function<String, String> mapping) { if (value == null) return null; if (value instanceof String) { return "\"" + StringUtil.escapeStringCharacters((String)value) + "\""; } if (value instanceof Boolean || value instanceof Short || value instanceof Byte) { return value.toString(); } if (value instanceof Character) { return "'" + StringUtil.escapeCharCharacters(value.toString()) + "'"; } if (value instanceof Long) { return value.toString() + 'L'; } if (value instanceof Integer) { if ("boolean".equals(type)) { if (value.equals(0)) return "false"; if (value.equals(1)) return "true"; } if ("char".equals(type)) { char ch = (char)((Integer)value).intValue(); return "'" + StringUtil.escapeCharCharacters(String.valueOf(ch)) + "'"; } return value.toString(); } if (value instanceof Double) { double d = (Double)value; if (Double.isInfinite(d)) { return d > 0 ? DOUBLE_POSITIVE_INF : DOUBLE_NEGATIVE_INF; } else if (Double.isNaN(d)) { return DOUBLE_NAN; } return Double.toString(d); } if (value instanceof Float) { float v = (Float)value; if (Float.isInfinite(v)) { return v > 0 ? FLOAT_POSITIVE_INF : FLOAT_NEGATIVE_INF; } else if (Float.isNaN(v)) { return FLOAT_NAN; } else { return Float.toString(v) + 'f'; } } if (value.getClass().isArray()) { StringBuilder buffer = new StringBuilder(); buffer.append('{'); for (int i = 0, length = Array.getLength(value); i < length; i++) { if (i > 0) buffer.append(", "); buffer.append(constToString(Array.get(value, i), type, anno, mapping)); } buffer.append('}'); return buffer.toString(); } if (anno && value instanceof Type) { return toJavaType(((Type)value), mapping) + ".class"; } return null; } private static String toJavaType(Type type, Function<String, String> mapping) { int dimensions = 0; if (type.getSort() == Type.ARRAY) { dimensions = type.getDimensions(); type = type.getElementType(); } String text = type.getSort() == Type.OBJECT ? mapping.fun(type.getInternalName()) : type.getClassName(); if (dimensions > 0) text += StringUtil.repeat("[]", dimensions); return text; } private static Function<String, String> createMapping(Object classSource) { if (classSource instanceof VirtualFile) { final Map<String, Pair<String, String>> mapping = ContainerUtil.newHashMap(); try { byte[] bytes = ((VirtualFile)classSource).contentsToByteArray(false); new ClassReader(bytes).accept(new ClassVisitor(ASM_API) { @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { if (outerName != null && innerName != null) { mapping.put(name, pair(outerName, innerName)); } } }, EMPTY_ATTRIBUTES, ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES); } catch (Exception ignored) { } if (!mapping.isEmpty()) { return new Function<String, String>() { @Override public String fun(String internalName) { String className = internalName; if (className.indexOf('$') >= 0) { Pair<String, String> p = mapping.get(className); if (p == null) { return GUESSING_MAPPER.fun(className); } className = p.first; if (p.second != null) { className = fun(p.first) + '.' + p.second; mapping.put(className, pair(className, (String)null)); } } return className.replace('/', '.'); } }; } } return GUESSING_MAPPER; } public static final Function<String, String> GUESSING_MAPPER = new Function<String, String>() { @Override public String fun(String internalName) { String canonicalText = internalName; if (canonicalText.indexOf('$') >= 0) { StringBuilder sb = new StringBuilder(canonicalText); boolean updated = false; for (int p = 0; p < sb.length(); p++) { char c = sb.charAt(p); if (c == '$' && p > 0 && sb.charAt(p - 1) != '/' && p < sb.length() - 1 && sb.charAt(p + 1) != '$') { sb.setCharAt(p, '.'); updated = true; } } if (updated) { canonicalText = sb.toString(); } } return canonicalText.replace('/', '.'); } }; }
retomerz/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java
Java
apache-2.0
33,477
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with [email protected] * </p> */ package com.telefonica.euro_iaas.sdc.rest.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.telefonica.euro_iaas.sdc.model.Artifact; import com.telefonica.euro_iaas.sdc.model.InstallableInstance.Status; import com.telefonica.euro_iaas.sdc.model.Task; import com.telefonica.euro_iaas.sdc.model.dto.ArtifactDto; /** * Provides a rest api to works with ProductInstances * * @author Sergio Arroyo */ public interface ArtifactResource { /** * Install a product in a given host. * * @param product * the concrete release of a product to install. It also contains information about the VM where the * product is going to be installed * @param callback * if not empty, contains the url where the result of the async operation will be sent * @return the installed product. */ @POST @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) Task install(@PathParam("vdc") String vdc, @PathParam("productInstance") String productIntanceName, ArtifactDto artifact, @HeaderParam("callback") String callback); /** * Retrieve all ProductInstance created in the system. * * @param hostname * the host name where the product is installed (<i>nullable</i>) * @param domain * the domain where the machine is (<i>nullable</i>) * @param ip * the ip of the host (<i>nullable</i>) * @param page * for pagination is 0 based number(<i>nullable</i>) * @param pageSize * for pagination, the number of items retrieved in a query (<i>nullable</i>) * @param orderBy * the file to order the search (id by default <i>nullable</i>) * @param orderType * defines if the order is ascending or descending (asc by default <i>nullable</i>) * @param status * the status the product (<i>nullable</i>) * @return the product instances that match with the criteria. */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) List<ArtifactDto> findAll(@QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize, @QueryParam("orderBy") String orderBy, @QueryParam("orderType") String orderType, @QueryParam("status") List<Status> status, @PathParam("vdc") String vdc, @PathParam("productInstance") String productInstance); /** * Retrieve the selected product instance. * * @param name * the product name * @return the product instance * @throws EntityNotFoundException */ @GET @Path("/{name}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) Artifact load(@PathParam("vdc") String vdc, @PathParam("productInstance") String productInstance, @PathParam("name") String name); /** * Deploy an artefact in the product instance * * @param name * the installable instance name * @param artefact * the artefact to be deployed * @param callback * if not empty, contains the url where the result of the async operation will be sent * @return the task. */ @DELETE @Path("/{name}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) Task uninstall(@PathParam("vdc") String vdc, @PathParam("productInstance") String productInstance, @PathParam("name") String name, @HeaderParam("callback") String callback); }
Fiware/cloud.SDC
rest-api/src/main/java/com/telefonica/euro_iaas/sdc/rest/resources/ArtifactResource.java
Java
apache-2.0
4,870
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.excelwriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceDefinition; import org.pentaho.di.resource.ResourceNamingInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; 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; import org.w3c.dom.Node; public class ExcelWriterStepMeta extends BaseStepMeta implements StepMetaInterface { private static Class<?> PKG = ExcelWriterStepMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ public static final String IF_FILE_EXISTS_REUSE = "reuse"; public static final String IF_FILE_EXISTS_CREATE_NEW = "new"; public static final String IF_SHEET_EXISTS_REUSE = "reuse"; public static final String IF_SHEET_EXISTS_CREATE_NEW = "new"; public static final String ROW_WRITE_OVERWRITE = "overwrite"; public static final String ROW_WRITE_PUSH_DOWN = "push"; /** The base name of the output file */ private String fileName; /** what to do if file exists **/ private String ifFileExists; private String ifSheetExists; private boolean makeSheetActive; private boolean forceFormulaRecalculation = false; private boolean leaveExistingStylesUnchanged = false; /** advanced line append options **/ private int appendOffset = 0; private int appendEmpty = 0; private boolean appendOmitHeader = false; /** how to write rows **/ private String rowWritingMethod; /** where to start writing **/ private String startingCell; /** The file extension in case of a generated filename */ private String extension; /** The password to protect the sheet */ private String password; private String protectedBy; /** Add a header at the top of the file? */ private boolean headerEnabled; /** Add a footer at the bottom of the file? */ private boolean footerEnabled; /** if this value is larger then 0, the text file is split up into parts of this number of lines */ private int splitEvery; /** Flag: add the stepnr in the filename */ private boolean stepNrInFilename; /** Flag: add the date in the filename */ private boolean dateInFilename; /** Flag: add the filenames to result filenames */ private boolean addToResultFilenames; /** Flag: protect the sheet */ private boolean protectsheet; /** Flag: add the time in the filename */ private boolean timeInFilename; /** Flag: use a template */ private boolean templateEnabled; private boolean templateSheetEnabled; /** the excel template */ private String templateFileName; private String templateSheetName; /** the excel sheet name */ private String sheetname; /* THE FIELD SPECIFICATIONS ... */ /** The output fields */ private ExcelWriterStepField outputFields[]; /** Flag : appendLines lines? */ private boolean appendLines; /** Flag : Do not open new file when transformation start */ private boolean doNotOpenNewFileInit; private boolean SpecifyFormat; private String date_time_format; /** Flag : auto size columns? */ private boolean autosizecolums; public ExcelWriterStepMeta() { super(); } public int getAppendOffset() { return appendOffset; } public void setAppendOffset(int appendOffset) { this.appendOffset = appendOffset; } public int getAppendEmpty() { return appendEmpty; } public void setAppendEmpty(int appendEmpty) { this.appendEmpty = appendEmpty>=0?appendEmpty:0; } /** * @return Returns the dateInFilename. */ public boolean isDateInFilename() { return dateInFilename; } /** * @param dateInFilename * The dateInFilename to set. */ public void setDateInFilename(boolean dateInFilename) { this.dateInFilename = dateInFilename; } public boolean isAppendOmitHeader() { return appendOmitHeader; } public void setAppendOmitHeader(boolean appendOmitHeader) { this.appendOmitHeader = appendOmitHeader; } public String getStartingCell() { return startingCell; } public void setStartingCell(String startingCell) { this.startingCell = startingCell; } public String getRowWritingMethod() { return rowWritingMethod; } public void setRowWritingMethod(String rowWritingMethod) { this.rowWritingMethod = rowWritingMethod; } public String getIfFileExists() { return ifFileExists; } public void setIfFileExists(String ifFileExists) { this.ifFileExists = ifFileExists; } public String getIfSheetExists() { return ifSheetExists; } public void setIfSheetExists(String ifSheetExists) { this.ifSheetExists = ifSheetExists; } public String getProtectedBy() { return protectedBy; } public void setProtectedBy(String protectedBy) { this.protectedBy = protectedBy; } /** * @return Returns the extension. */ public String getExtension() { return extension; } /** * @param extension * The extension to set. */ public void setExtension(String extension) { this.extension = extension; } /** * @return Returns the fileName. */ public String getFileName() { return fileName; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @return Returns the sheet name. */ public String getSheetname() { return sheetname; } /** * @param sheetname * The sheet name. */ public void setSheetname(String sheetname) { this.sheetname = sheetname; } /** * @param fileName * The fileName to set. */ public void setFileName(String fileName) { this.fileName = fileName; } /** * @param password * teh passwoed to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the footer. */ public boolean isFooterEnabled() { return footerEnabled; } /** * @param footer * The footer to set. */ public void setFooterEnabled(boolean footer) { this.footerEnabled = footer; } /** * @return Returns the autosizecolums. */ public boolean isAutoSizeColums() { return autosizecolums; } /** * @param autosizecolums * The autosizecolums to set. */ public void setAutoSizeColums(boolean autosizecolums) { this.autosizecolums = autosizecolums; } /** * @return Returns the header. */ public boolean isHeaderEnabled() { return headerEnabled; } /** * @param header * The header to set. */ public void setHeaderEnabled(boolean header) { this.headerEnabled = header; } public boolean isSpecifyFormat() { return SpecifyFormat; } public void setSpecifyFormat(boolean SpecifyFormat) { this.SpecifyFormat = SpecifyFormat; } public String getDateTimeFormat() { return date_time_format; } public void setDateTimeFormat(String date_time_format) { this.date_time_format = date_time_format; } /** * @return Returns the splitEvery. */ public int getSplitEvery() { return splitEvery; } /** * @return Returns the add to result filesname. */ public boolean isAddToResultFiles() { return addToResultFilenames; } /** * @param addtoresultfilenamesin * The addtoresultfilenames to set. */ public void setAddToResultFiles(boolean addtoresultfilenamesin) { this.addToResultFilenames = addtoresultfilenamesin; } /** * @param splitEvery * The splitEvery to set. */ public void setSplitEvery(int splitEvery) { this.splitEvery = splitEvery>=0?splitEvery:0; } /** * @return Returns the stepNrInFilename. */ public boolean isStepNrInFilename() { return stepNrInFilename; } /** * @param stepNrInFilename * The stepNrInFilename to set. */ public void setStepNrInFilename(boolean stepNrInFilename) { this.stepNrInFilename = stepNrInFilename; } /** * @return Returns the timeInFilename. */ public boolean isTimeInFilename() { return timeInFilename; } /** * @return Returns the protectsheet. */ public boolean isSheetProtected() { return protectsheet; } /** * @param timeInFilename * The timeInFilename to set. */ public void setTimeInFilename(boolean timeInFilename) { this.timeInFilename = timeInFilename; } /** * @param protectsheet * the value to set. */ public void setProtectSheet(boolean protectsheet) { this.protectsheet = protectsheet; } /** * @return Returns the outputFields. */ public ExcelWriterStepField[] getOutputFields() { return outputFields; } /** * @param outputFields * The outputFields to set. */ public void setOutputFields(ExcelWriterStepField[] outputFields) { this.outputFields = outputFields; } /** * @return Returns the template. */ public boolean isTemplateEnabled() { return templateEnabled; } /** * @param template * The template to set. */ public void setTemplateEnabled(boolean template) { this.templateEnabled = template; } public boolean isTemplateSheetEnabled() { return templateSheetEnabled; } public void setTemplateSheetEnabled(boolean templateSheetEnabled) { this.templateSheetEnabled = templateSheetEnabled; } /** * @return Returns the templateFileName. */ public String getTemplateFileName() { return templateFileName; } /** * @param templateFileName * The templateFileName to set. */ public void setTemplateFileName(String templateFileName) { this.templateFileName = templateFileName; } public String getTemplateSheetName() { return templateSheetName; } public void setTemplateSheetName(String templateSheetName) { this.templateSheetName = templateSheetName; } /** * @return Returns the "do not open new file at init" flag. */ public boolean isDoNotOpenNewFileInit() { return doNotOpenNewFileInit; } /** * @param doNotOpenNewFileInit * The "do not open new file at init" flag to set. */ public void setDoNotOpenNewFileInit(boolean doNotOpenNewFileInit) { this.doNotOpenNewFileInit = doNotOpenNewFileInit; } /** * @return Returns the appendLines. */ public boolean isAppendLines() { return appendLines; } /** * @param appendLines * The appendLines to set. */ public void setAppendLines(boolean append) { this.appendLines = append; } public void setMakeSheetActive(boolean makeSheetActive) { this.makeSheetActive = makeSheetActive; } public boolean isMakeSheetActive() { return makeSheetActive; } public boolean isForceFormulaRecalculation() { return forceFormulaRecalculation; } public void setForceFormulaRecalculation(boolean forceFormulaRecalculation) { this.forceFormulaRecalculation = forceFormulaRecalculation; } public boolean isLeaveExistingStylesUnchanged() { return leaveExistingStylesUnchanged; } public void setLeaveExistingStylesUnchanged(boolean leaveExistingStylesUnchanged) { this.leaveExistingStylesUnchanged = leaveExistingStylesUnchanged; } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { readData(stepnode); } public void allocate(int nrfields) { outputFields = new ExcelWriterStepField[nrfields]; } public Object clone() { ExcelWriterStepMeta retval = (ExcelWriterStepMeta) super.clone(); int nrfields = outputFields.length; retval.allocate(nrfields); for (int i = 0; i < nrfields; i++) { retval.outputFields[i] = (ExcelWriterStepField) outputFields[i].clone(); } return retval; } private void readData(Node stepnode) throws KettleXMLException { try { headerEnabled = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "header")); footerEnabled = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "footer")); appendOmitHeader = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "appendOmitHeader")); appendLines = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "appendLines")); makeSheetActive = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "makeSheetActive")); appendOffset = Const.toInt(XMLHandler.getTagValue(stepnode, "appendOffset"), 0); appendEmpty = Const.toInt(XMLHandler.getTagValue(stepnode, "appendEmpty"), 0); startingCell = XMLHandler.getTagValue(stepnode, "startingCell"); rowWritingMethod = XMLHandler.getTagValue(stepnode, "rowWritingMethod"); forceFormulaRecalculation = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "forceFormulaRecalculation")); leaveExistingStylesUnchanged = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "leaveExistingStylesUnchanged")); String addToResult = XMLHandler.getTagValue(stepnode, "add_to_result_filenames"); if (Const.isEmpty(addToResult)) addToResultFilenames = true; else addToResultFilenames = "Y".equalsIgnoreCase(addToResult); fileName = XMLHandler.getTagValue(stepnode, "file", "name"); extension = XMLHandler.getTagValue(stepnode, "file", "extention"); doNotOpenNewFileInit = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "do_not_open_newfile_init")); stepNrInFilename = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "split")); dateInFilename = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "add_date")); timeInFilename = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "add_time")); SpecifyFormat = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "SpecifyFormat")); date_time_format = XMLHandler.getTagValue(stepnode, "file", "date_time_format"); autosizecolums = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "autosizecolums")); protectsheet = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "file", "protect_sheet")); password = Encr.decryptPasswordOptionallyEncrypted(XMLHandler.getTagValue(stepnode, "file", "password")); protectedBy = XMLHandler.getTagValue(stepnode, "file", "protected_by"); splitEvery = Const.toInt(XMLHandler.getTagValue(stepnode, "file", "splitevery"), 0); templateEnabled = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "template", "enabled")); templateSheetEnabled = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "template", "sheet_enabled")); templateFileName = XMLHandler.getTagValue(stepnode, "template", "filename"); templateSheetName = XMLHandler.getTagValue(stepnode, "template", "sheetname"); sheetname = XMLHandler.getTagValue(stepnode, "file", "sheetname"); ifFileExists = XMLHandler.getTagValue(stepnode, "file", "if_file_exists"); ifSheetExists = XMLHandler.getTagValue(stepnode, "file", "if_sheet_exists"); Node fields = XMLHandler.getSubNode(stepnode, "fields"); int nrfields = XMLHandler.countNodes(fields, "field"); allocate(nrfields); for (int i = 0; i < nrfields; i++) { Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i); outputFields[i] = new ExcelWriterStepField(); outputFields[i].setName(XMLHandler.getTagValue(fnode, "name")); outputFields[i].setType(XMLHandler.getTagValue(fnode, "type")); outputFields[i].setFormat(XMLHandler.getTagValue(fnode, "format")); outputFields[i].setTitle(XMLHandler.getTagValue(fnode, "title")); outputFields[i].setTitleStyleCell(XMLHandler.getTagValue(fnode, "titleStyleCell")); outputFields[i].setStyleCell(XMLHandler.getTagValue(fnode, "styleCell")); outputFields[i].setCommentField(XMLHandler.getTagValue(fnode, "commentField")); outputFields[i].setCommentAuthorField(XMLHandler.getTagValue(fnode, "commentAuthorField")); outputFields[i].setFormula(XMLHandler.getTagValue(fnode, "formula") != null && XMLHandler.getTagValue(fnode, "formula").equalsIgnoreCase("Y")); outputFields[i].setHyperlinkField(XMLHandler.getTagValue(fnode, "hyperlinkField")); } } catch (Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public String getNewLine(String fformat) { String nl = System.getProperty("line.separator"); if (fformat != null) { if (fformat.equalsIgnoreCase("DOS")) { nl = "\r\n"; } else if (fformat.equalsIgnoreCase("UNIX")) { nl = "\n"; } } return nl; } public void setDefault() { autosizecolums = false; headerEnabled = true; footerEnabled = false; fileName = "file"; extension = "xls"; doNotOpenNewFileInit = false; stepNrInFilename = false; dateInFilename = false; timeInFilename = false; date_time_format = null; SpecifyFormat = false; addToResultFilenames = true; protectsheet = false; splitEvery = 0; templateEnabled = false; templateFileName = "template.xls"; sheetname = "Sheet1"; appendLines = false; ifFileExists = IF_FILE_EXISTS_CREATE_NEW; ifSheetExists = IF_SHEET_EXISTS_CREATE_NEW; startingCell = "A1"; rowWritingMethod = ROW_WRITE_OVERWRITE; appendEmpty = 0; appendOffset = 0; appendOmitHeader = false; makeSheetActive = true; forceFormulaRecalculation = false; allocate(0); } public String[] getFiles(VariableSpace space) { int copies = 1; int splits = 1; if (stepNrInFilename) { copies = 3; } if (splitEvery != 0) { splits = 4; } int nr = copies * splits; if (nr > 1) nr++; String retval[] = new String[nr]; int i = 0; for (int copy = 0; copy < copies; copy++) { for (int split = 0; split < splits; split++) { retval[i] = buildFilename(space, copy, split); i++; } } if (i < nr) { retval[i] = "..."; } return retval; } public String buildFilename(VariableSpace space, int stepnr, int splitnr) { SimpleDateFormat daf = new SimpleDateFormat(); // Replace possible environment variables... String retval = space.environmentSubstitute(fileName); String realextension = space.environmentSubstitute(extension); Date now = new Date(); if (SpecifyFormat && !Const.isEmpty(date_time_format)) { daf.applyPattern(date_time_format); String dt = daf.format(now); retval += dt; } else { if (dateInFilename) { daf.applyPattern("yyyMMdd"); String d = daf.format(now); retval += "_" + d; } if (timeInFilename) { daf.applyPattern("HHmmss"); String t = daf.format(now); retval += "_" + t; } } if (stepNrInFilename) { retval += "_" + stepnr; } if (splitEvery > 0) { retval += "_" + splitnr; } if (realextension != null && realextension.length() != 0) { retval += "." + realextension; } return retval; } public void getFields(RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) { if (r == null) r = new RowMeta(); // give back values // No values are added to the row in this type of step } public String getXML() { StringBuffer retval = new StringBuffer(800); retval.append(" ").append(XMLHandler.addTagValue("header", headerEnabled)); retval.append(" ").append(XMLHandler.addTagValue("footer", footerEnabled)); retval.append(" ").append(XMLHandler.addTagValue("makeSheetActive", makeSheetActive)); retval.append(" ").append(XMLHandler.addTagValue("rowWritingMethod", rowWritingMethod)); retval.append(" ").append(XMLHandler.addTagValue("startingCell", startingCell)); retval.append(" ").append(XMLHandler.addTagValue("appendOmitHeader", appendOmitHeader)); retval.append(" ").append(XMLHandler.addTagValue("appendOffset", appendOffset)); retval.append(" ").append(XMLHandler.addTagValue("appendEmpty", appendEmpty)); retval.append(" ").append(XMLHandler.addTagValue("rowWritingMethod", rowWritingMethod)); retval.append(" ").append(XMLHandler.addTagValue("forceFormulaRecalculation", forceFormulaRecalculation)); retval.append(" ").append(XMLHandler.addTagValue("leaveExistingStylesUnchanged", leaveExistingStylesUnchanged)); retval.append(" " + XMLHandler.addTagValue("appendLines", appendLines)); retval.append(" " + XMLHandler.addTagValue("add_to_result_filenames", addToResultFilenames)); retval.append(" <file>").append(Const.CR); retval.append(" ").append(XMLHandler.addTagValue("name", fileName)); retval.append(" ").append(XMLHandler.addTagValue("extention", extension)); retval.append(" ").append(XMLHandler.addTagValue("do_not_open_newfile_init", doNotOpenNewFileInit)); retval.append(" ").append(XMLHandler.addTagValue("split", stepNrInFilename)); retval.append(" ").append(XMLHandler.addTagValue("add_date", dateInFilename)); retval.append(" ").append(XMLHandler.addTagValue("add_time", timeInFilename)); retval.append(" ").append(XMLHandler.addTagValue("SpecifyFormat", SpecifyFormat)); retval.append(" ").append(XMLHandler.addTagValue("date_time_format", date_time_format)); retval.append(" ").append(XMLHandler.addTagValue("sheetname", sheetname)); retval.append(" ").append(XMLHandler.addTagValue("autosizecolums", autosizecolums)); retval.append(" ").append(XMLHandler.addTagValue("protect_sheet", protectsheet)); retval.append(" ").append(XMLHandler.addTagValue("password", Encr.encryptPasswordIfNotUsingVariables(password))); retval.append(" ").append(XMLHandler.addTagValue("protected_by", protectedBy)); retval.append(" ").append(XMLHandler.addTagValue("splitevery", splitEvery)); retval.append(" ").append(XMLHandler.addTagValue("if_file_exists", ifFileExists)); retval.append(" ").append(XMLHandler.addTagValue("if_sheet_exists", ifSheetExists)); retval.append(" </file>").append(Const.CR); retval.append(" <template>").append(Const.CR); retval.append(" ").append(XMLHandler.addTagValue("enabled", templateEnabled)); retval.append(" ").append(XMLHandler.addTagValue("sheet_enabled", templateSheetEnabled)); retval.append(" ").append(XMLHandler.addTagValue("filename", templateFileName)); retval.append(" ").append(XMLHandler.addTagValue("sheetname", templateSheetName)); retval.append(" </template>").append(Const.CR); retval.append(" <fields>").append(Const.CR); for (int i = 0; i < outputFields.length; i++) { ExcelWriterStepField field = outputFields[i]; if (field.getName() != null && field.getName().length() != 0) { retval.append(" <field>").append(Const.CR); retval.append(" ").append(XMLHandler.addTagValue("name", field.getName())); retval.append(" ").append(XMLHandler.addTagValue("type", field.getTypeDesc())); retval.append(" ").append(XMLHandler.addTagValue("format", field.getFormat())); retval.append(" ").append(XMLHandler.addTagValue("title", field.getTitle())); retval.append(" ").append(XMLHandler.addTagValue("titleStyleCell", field.getTitleStyleCell())); retval.append(" ").append(XMLHandler.addTagValue("styleCell", field.getStyleCell())); retval.append(" ").append(XMLHandler.addTagValue("commentField", field.getCommentField())); retval.append(" ").append(XMLHandler.addTagValue("commentAuthorField", field.getCommentAuthorField())); retval.append(" ").append(XMLHandler.addTagValue("formula", field.isFormula())); retval.append(" ").append(XMLHandler.addTagValue("hyperlinkField", field.getHyperlinkField())); retval.append(" </field>").append(Const.CR); } } retval.append(" </fields>").append(Const.CR); return retval.toString(); } public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { headerEnabled = rep.getStepAttributeBoolean(id_step, "header"); footerEnabled = rep.getStepAttributeBoolean(id_step, "footer"); makeSheetActive = rep.getStepAttributeBoolean(id_step, "makeSheetActive"); appendOmitHeader = rep.getStepAttributeBoolean(id_step, "appendOmitHeader"); startingCell = rep.getStepAttributeString(id_step, "startingCell"); appendEmpty = (int)rep.getStepAttributeInteger(id_step, "appendEmpty"); appendOffset = (int)rep.getStepAttributeInteger(id_step, "appendOffset"); rowWritingMethod = rep.getStepAttributeString(id_step, "rowWritingMethod"); appendLines = rep.getStepAttributeBoolean(id_step, "appendLines"); forceFormulaRecalculation = rep.getStepAttributeBoolean(id_step, "forceFormulaRecalculation"); leaveExistingStylesUnchanged = rep.getStepAttributeBoolean(id_step, "leaveExistingStylesUnchanged"); String addToResult = rep.getStepAttributeString(id_step, "add_to_result_filenames"); if (Const.isEmpty(addToResult)) addToResultFilenames = true; else addToResultFilenames = rep.getStepAttributeBoolean(id_step, "add_to_result_filenames"); fileName = rep.getStepAttributeString(id_step, "file_name"); extension = rep.getStepAttributeString(id_step, "file_extention"); doNotOpenNewFileInit = rep.getStepAttributeBoolean(id_step, "do_not_open_newfile_init"); splitEvery = (int) rep.getStepAttributeInteger(id_step, "file_split"); stepNrInFilename = rep.getStepAttributeBoolean(id_step, "file_add_stepnr"); dateInFilename = rep.getStepAttributeBoolean(id_step, "file_add_date"); timeInFilename = rep.getStepAttributeBoolean(id_step, "file_add_time"); SpecifyFormat = rep.getStepAttributeBoolean(id_step, "SpecifyFormat"); date_time_format = rep.getStepAttributeString(id_step, "date_time_format"); autosizecolums = rep.getStepAttributeBoolean(id_step, "autosizecolums"); protectsheet = rep.getStepAttributeBoolean(id_step, "protect_sheet"); password = Encr.decryptPasswordOptionallyEncrypted(rep.getStepAttributeString(id_step, "password")); protectedBy = rep.getStepAttributeString(id_step, "protected_by"); templateEnabled = rep.getStepAttributeBoolean(id_step, "template_enabled"); templateFileName = rep.getStepAttributeString(id_step, "template_filename"); templateSheetEnabled = rep.getStepAttributeBoolean(id_step, "template_sheet_enabled"); templateSheetName = rep.getStepAttributeString(id_step, "template_sheetname"); sheetname = rep.getStepAttributeString(id_step, "sheetname"); ifFileExists = rep.getStepAttributeString(id_step, "if_file_exists"); ifSheetExists = rep.getStepAttributeString(id_step, "if_sheet_exists"); int nrfields = rep.countNrStepAttributes(id_step, "field_name"); allocate(nrfields); for (int i = 0; i < nrfields; i++) { outputFields[i] = new ExcelWriterStepField(); outputFields[i].setName(rep.getStepAttributeString(id_step, i, "field_name")); outputFields[i].setType(rep.getStepAttributeString(id_step, i, "field_type")); outputFields[i].setFormat(rep.getStepAttributeString(id_step, i, "field_format")); outputFields[i].setTitle(rep.getStepAttributeString(id_step, i, "field_title")); outputFields[i].setTitleStyleCell(rep.getStepAttributeString(id_step, i, "field_title_style_cell")); outputFields[i].setStyleCell(rep.getStepAttributeString(id_step, i, "field_style_cell")); outputFields[i].setCommentField(rep.getStepAttributeString(id_step, i, "field_comment_field")); outputFields[i].setCommentAuthorField(rep.getStepAttributeString(id_step, i, "field_comment_author_field")); outputFields[i].setFormula(rep.getStepAttributeBoolean(id_step, i, "field_formula")); outputFields[i].setHyperlinkField(rep.getStepAttributeString(id_step, i, "field_hyperlink_field")); } } catch (Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "header", headerEnabled); rep.saveStepAttribute(id_transformation, id_step, "footer", footerEnabled); rep.saveStepAttribute(id_transformation, id_step, "makeSheetActive", makeSheetActive); rep.saveStepAttribute(id_transformation, id_step, "startingCell", startingCell); rep.saveStepAttribute(id_transformation, id_step, "appendOmitHeader", appendOmitHeader); rep.saveStepAttribute(id_transformation, id_step, "appendEmpty", appendEmpty); rep.saveStepAttribute(id_transformation, id_step, "appendOffset", appendOffset); rep.saveStepAttribute(id_transformation, id_step, "rowWritingMethod", rowWritingMethod); rep.saveStepAttribute(id_transformation, id_step, "appendLines", appendLines); rep.saveStepAttribute(id_transformation, id_step, "add_to_result_filenames", addToResultFilenames); rep.saveStepAttribute(id_transformation, id_step, "file_name", fileName); rep.saveStepAttribute(id_transformation, id_step, "do_not_open_newfile_init", doNotOpenNewFileInit); rep.saveStepAttribute(id_transformation, id_step, "forceFormulaRecalculation", forceFormulaRecalculation); rep.saveStepAttribute(id_transformation, id_step, "leaveExistingStylesUnchanged", leaveExistingStylesUnchanged); rep.saveStepAttribute(id_transformation, id_step, "file_extention", extension); rep.saveStepAttribute(id_transformation, id_step, "file_split", splitEvery); rep.saveStepAttribute(id_transformation, id_step, "file_add_stepnr", stepNrInFilename); rep.saveStepAttribute(id_transformation, id_step, "file_add_date", dateInFilename); rep.saveStepAttribute(id_transformation, id_step, "file_add_time", timeInFilename); rep.saveStepAttribute(id_transformation, id_step, "SpecifyFormat", SpecifyFormat); rep.saveStepAttribute(id_transformation, id_step, "date_time_format", date_time_format); rep.saveStepAttribute(id_transformation, id_step, "autosizecolums", autosizecolums); rep.saveStepAttribute(id_transformation, id_step, "protect_sheet", protectsheet); rep.saveStepAttribute(id_transformation, id_step, "protected_by", protectedBy); rep.saveStepAttribute(id_transformation, id_step, "password", Encr.encryptPasswordIfNotUsingVariables(password)); rep.saveStepAttribute(id_transformation, id_step, "template_enabled", templateEnabled); rep.saveStepAttribute(id_transformation, id_step, "template_filename", templateFileName); rep.saveStepAttribute(id_transformation, id_step, "template_sheet_enabled", templateSheetEnabled); rep.saveStepAttribute(id_transformation, id_step, "template_sheetname", templateSheetName); rep.saveStepAttribute(id_transformation, id_step, "sheetname", sheetname); rep.saveStepAttribute(id_transformation, id_step, "if_file_exists", ifFileExists); rep.saveStepAttribute(id_transformation, id_step, "if_sheet_exists", ifSheetExists); for (int i = 0; i < outputFields.length; i++) { ExcelWriterStepField field = outputFields[i]; rep.saveStepAttribute(id_transformation, id_step, i, "field_name", field.getName()); rep.saveStepAttribute(id_transformation, id_step, i, "field_type", field.getTypeDesc()); rep.saveStepAttribute(id_transformation, id_step, i, "field_format", field.getFormat()); rep.saveStepAttribute(id_transformation, id_step, i, "field_title", field.getTitle()); rep.saveStepAttribute(id_transformation, id_step, i, "field_title_style_cell", field.getTitleStyleCell()); rep.saveStepAttribute(id_transformation, id_step, i, "field_style_cell", field.getStyleCell()); rep.saveStepAttribute(id_transformation, id_step, i, "field_comment_field", field.getCommentField()); rep.saveStepAttribute(id_transformation, id_step, i, "field_comment_author_field", field.getCommentAuthorField()); rep.saveStepAttribute(id_transformation, id_step, i, "field_formula", field.isFormula()); rep.saveStepAttribute(id_transformation, id_step, i, "field_hyperlink_field", field.getHyperlinkField()); } } catch (Exception e) { throw new KettleException("Unable to save step information to the repository for id_step=" + id_step, e); } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info) { CheckResult cr; // Check output fields if (prev != null && prev.size() > 0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.FieldsReceived", "" + prev.size()), stepMeta); remarks.add(cr); String error_message = ""; boolean error_found = false; // Starting from selected fields in ... for (int i = 0; i < outputFields.length; i++) { int idx = prev.indexOfValue(outputFields[i].getName()); if (idx < 0) { error_message += "\t\t" + outputFields[i].getName() + Const.CR; error_found = true; } } if (error_found) { error_message = BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.FieldsNotFound", error_message); cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, error_message, stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.AllFieldsFound"), stepMeta); remarks.add(cr); } } // See if we have input streams leading to this step! if (input.length > 0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.ExpectedInputOk"), stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.ExpectedInputError"), stepMeta); remarks.add(cr); } cr = new CheckResult(CheckResultInterface.TYPE_RESULT_COMMENT, BaseMessages.getString(PKG, "ExcelWriterStepMeta.CheckResult.FilesNotChecked"), stepMeta); remarks.add(cr); } /** * Since the exported transformation that runs this will reside in a ZIP file, we can't reference files relatively. So what this does is turn the name of the base path into an absolute path. */ public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface, Repository repository) throws KettleException { try { // The object that we're modifying here is a copy of the original! // So let's change the filename from relative to absolute by grabbing the file object... // if (!Const.isEmpty(fileName)) { FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(fileName), space); fileName = resourceNamingInterface.nameResource(fileObject, space, true); } if (!Const.isEmpty(templateFileName)) { FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(templateFileName), space); templateFileName = resourceNamingInterface.nameResource(fileObject, space, true); } return null; } catch (Exception e) { throw new KettleException(e); //$NON-NLS-1$ } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new ExcelWriterStep(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new ExcelWriterStepData(); } public String[] getUsedLibraries() { return new String[0]; } }
soluvas/pdi-ce
src/org/pentaho/di/trans/steps/excelwriter/ExcelWriterStepMeta.java
Java
apache-2.0
36,872
package dao; import java.util.Vector; import com.ibm.xsp.model.domino.DominoUtils; import lotus.domino.Database; import model.Person; /** * * @author weihang chen * */ public class PersonDaoImpl extends DaoBase implements PersonDao { private static final long serialVersionUID = -3180284664017555290L; @SuppressWarnings("unchecked") public Vector<Person> getPeople() throws Exception { // hard code the db Database personDb = DominoUtils.openDatabaseByName("names.nsf"); Vector<Person> people = (Vector<Person>) findAllByKey(null, personDb, "People", Person.class); return people; } }
OpenNTF/CustomPersistentLayers
JPADominoNew/Code/Java/dao/PersonDaoImpl.java
Java
apache-2.0
642
package com.mic.log.util.sms; import com.mic.log.util.PropertiesUtils; public class SmsManager { public static void main(String[] args) { String wsAddress=PropertiesUtils.getValue("smsUrl"); try { WebServiceClient wsc=new WebServiceClient(); wsc.init(wsAddress, PropertiesUtils.getValue("smsNamespaceURI")); Integer iRet=new Integer(0); String[] paraArray=new String[10]; paraArray[0]="mictest"; paraArray[1]="focustech1+11"; paraArray[2]="18913984951"; paraArray[3]="sms/mt"; paraArray[4]="ÏîÄ¿¾¯±¨"; paraArray[5]="ÏîÄ¿EN-·¢ÉúError"; paraArray[6]=null; paraArray[7]="414"; paraArray[8]=""; paraArray[9]=""; iRet=(Integer)wsc.invokeForObject("sendMessageX", paraArray, new Class[]{Integer.class}); System.out.println(getSmsStatusMsg(iRet)); } catch(Exception ex) { ex.printStackTrace(); } } public static String getSmsStatusMsg(int iRet) { if(iRet==-1) { return "Óû§Ãû»ò¿ÚÁî´íÎó"; } else if(iRet==-2) { return "IPÑéÖ¤´íÎó"; } else if(iRet==-3) { return "¶¨Ê±ÈÕÆÚ´íÎó"; } else if(iRet==-101) { return "²ÎÊý´íÎóuserIdΪ¿Õ"; } else if(iRet==-102) { return "²ÎÊý´íÎóÄ¿±êºÅÂëΪ¿Õ"; } else if(iRet==-103) { return "²ÎÊý´íÎóÄÚÈÝΪ¿Õ"; } else if(iRet==200) { return "Ä¿±êºÅÂë´íÎó"; } else if(iRet==201) { return "Ä¿±êºÅÂëÔÚºÚÃûµ¥ÖÐ"; } else if(iRet==202) { return "ÄÚÈݰüº¬Ãô¸Ð´Ê"; } else if(iRet==203) { return "ÌØ·þºÅÂëδ·ÖÅä"; } else if(iRet==204) { return "·ÖÅäͨµÀ´íÎó"; } else if(iRet==999) { return "·¢ËÍÈý´Î¶¼³¬Ê±"; } else if(iRet==-10) { return "Óà¶î²»×ã"; } else { return "δ֪´íÎó"; } } }
yifzhang/storm-miclog
src/jvm/com/mic/log/util/sms/SmsManager.java
Java
apache-2.0
1,804
/* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.mapstore; import com.hazelcast.config.Config; import com.hazelcast.config.MapStoreConfig; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.core.MapLoader; import com.hazelcast.core.MapLoaderLifecycleSupport; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.util.Properties; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.withSettings; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class MapLoaderLifecycleTest extends HazelcastTestSupport { private MapLoaderLifecycleSupport loader = mockMapLoaderWithLifecycle(); private Config config = new Config(); @Before public void configure() { config.getMapConfig("map").setMapStoreConfig(new MapStoreConfig().setImplementation(loader)); } @Test public void testInitCalled_whenMapCreated() throws Exception { HazelcastInstance hz = createHazelcastInstance(config); IMap<String, String> map = hz.getMap("map"); // MapStore creation is deferred, so trigger map store creation by putting some data in the map map.put("a", "b"); verify(loader).init(eq(hz), eq(new Properties()), eq("map")); } @Test public void testDestroyCalled_whenNodeShutdown() throws Exception { HazelcastInstance hz = createHazelcastInstance(config); IMap<String, String> map = hz.getMap("map"); // MapStore creation is deferred, so trigger map store creation by putting some data in the map map.put("a", "b"); hz.shutdown(); verify(loader).destroy(); } private static MapLoaderLifecycleSupport mockMapLoaderWithLifecycle() { return mock(MapLoaderLifecycleSupport.class, withSettings().extraInterfaces(MapLoader.class)); } }
tombujok/hazelcast
hazelcast/src/test/java/com/hazelcast/map/impl/mapstore/MapLoaderLifecycleTest.java
Java
apache-2.0
2,874
package com.tarena.crm.action; import java.util.List; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSONArray; import com.tarena.crm.dao.BaseDao; import com.tarena.crm.dao.impl.CustomTypeDaoImpl; import com.tarena.crm.entity.Customtype; import com.tarena.crm.service.impl.CustomTypeServiceImpl; import com.tarena.minispringmvc.servlet.Action; import com.tarena.minispringmvc.servlet.RequestPath; @Action public class CustomTypeAction { @RequestPath(path = "/customType/add.do") public void add(HttpServletRequest request, HttpServletResponse response) throws Exception{ String type = (String) request.getParameter("type"); PrintWriter out = response.getWriter(); try { Object flag = new CustomTypeServiceImpl().add(new Customtype(type)); if(flag == null){ out.print("fail"); return; } out.print("ok"); } catch (Exception e) { out.print("fail"); }finally{ out.close(); } } @RequestPath(path = "/customType/delete.do") public void delete(HttpServletRequest request, HttpServletResponse response)throws Exception{ String id = request.getParameter("id"); PrintWriter out = response.getWriter(); try{ new CustomTypeServiceImpl().delete(Long.parseLong(id)); out.print("ok"); }catch(Exception e){ out.println("fail"); }finally{ out.close(); } } @RequestPath(path = "/customType/findAll.do") public void findAll(HttpServletRequest request, HttpServletResponse response)throws Exception{ response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); try{ List all = new CustomTypeServiceImpl().findAll(); if(all == null){ out.println("fail"); return ; } Object json = JSONArray.toJSON(all); out.print(json); }catch(Exception e){ out.println("error"); }finally{ out.close(); } } }
ChunboLI/NETCTOSS
crm/src/com/tarena/crm/action/CustomTypeAction.java
Java
apache-2.0
1,934
package com.taobao.api.response; import com.taobao.api.internal.mapping.ApiField; import com.taobao.api.TaobaoObject; import com.taobao.api.TaobaoResponse; /** * TOP API: alibaba.aliqin.fc.flow.charge.province response. * * @author top auto create * @since 1.0, null */ public class AlibabaAliqinFcFlowChargeProvinceResponse extends TaobaoResponse { private static final long serialVersionUID = 4639282987239157872L; /** * 无 */ @ApiField("value") private Result value; public void setValue(Result value) { this.value = value; } public Result getValue( ) { return this.value; } /** * 无 * * @author top auto create * @since 1.0, null */ public static class Result extends TaobaoObject { private static final long serialVersionUID = 4321888368814244542L; /** * 错误码 */ @ApiField("code") private String code; /** * 无 */ @ApiField("model") private String model; /** * 原因 */ @ApiField("msg") private String msg; /** * 结果 */ @ApiField("success") private Boolean success; public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } } }
exercisecode/alidayu_demo
alidayu/src/main/java/com/taobao/api/response/AlibabaAliqinFcFlowChargeProvinceResponse.java
Java
apache-2.0
1,657
/** * Copyright 2013 Autentia Real Business Solution S.L. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.autentia.web.rest.wadl.builder.namespace; import com.autentia.xml.namespace.QNameBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.xml.namespace.QName; import java.util.Arrays; import java.util.Collection; import java.util.Date; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class QNameBuilderForBasicTypesTest { private static final QNameBuilder Q_NAME_BUILDER = new QNameBuilderFactory().getBuilder(); private final Class<?> basicType; private final String expectedLocalPart; @Parameters public static Collection<Object[]> parameters() { return Arrays.asList(new Object[][]{ {boolean.class, "boolean"}, {boolean.class, "boolean"}, {byte.class, "byte"}, {Byte.class, "byte"}, {short.class, "short"}, {Short.class, "short"}, {int.class, "integer"}, {Integer.class, "integer"}, {long.class, "long"}, {Long.class, "long"}, {float.class, "float"}, {Float.class, "float"}, {double.class, "double"}, {Double.class, "double"}, {String.class, "string"}, {Date.class, "date"} }); } public QNameBuilderForBasicTypesTest(Class<?> basicType, String expectedLocalPart) { this.basicType = basicType; this.expectedLocalPart = expectedLocalPart; } @Test public void givenBasicType_whenBuild_thenReturnStandardSchemaRepresentation() { final QName qName = Q_NAME_BUILDER.buildFor(basicType); assertThat(qName.getNamespaceURI(), is("http://www.w3.org/2001/XMLSchema")); assertThat(qName.getLocalPart(), is(expectedLocalPart)); assertThat(qName.getPrefix(), is("xs")); } }
autentia/wadl-tools
spring-wadl-generator/src/test/java/com/autentia/web/rest/wadl/builder/namespace/QNameBuilderForBasicTypesTest.java
Java
apache-2.0
2,691
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2014 Wisdom Framework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.wisdom.database.jdbc.it; import org.junit.Before; import org.junit.Test; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.wisdom.database.jdbc.Statements; import org.wisdom.database.jdbc.service.DataSources; import org.wisdom.test.parents.WisdomTest; import javax.inject.Inject; import javax.sql.DataSource; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; /** * Check the behavior of the data source manager inside Wisdom. */ public class DataSourcesIT extends WisdomTest { @Inject DataSources sources; @Before public void setup() { File db = new File("target/db"); db.mkdirs(); } @Test public void testDerby() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); assertThat(sources.getDataSources()).containsKeys("derby"); assertThat(sources.getDataSource("derby")).isNotNull(); sources.getConnection("derby").createStatement().execute(Statements.CREATE_TABLE); sources.getConnection("derby").createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection("derby").createStatement().execute(Statements.INSERT_DENVER); sources.getConnection("derby").createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection("derby").createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=derby)"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } @Test public void testH2Memory() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); assertThat(sources.getDataSources()).containsKeys("h2mem"); assertThat(sources.getDataSource("h2mem")).isNotNull(); sources.getConnection("h2mem").createStatement().execute(Statements.CREATE_TABLE); sources.getConnection("h2mem").createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection("h2mem").createStatement().execute(Statements.INSERT_DENVER); sources.getConnection("h2mem").createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection("h2mem").createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=h2mem)"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } @Test public void testH2File() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); assertThat(sources.getDataSources()).containsKeys("h2file"); assertThat(sources.getDataSource("h2file")).isNotNull(); sources.getConnection("h2file").createStatement().execute(Statements.CREATE_TABLE); sources.getConnection("h2file").createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection("h2file").createStatement().execute(Statements.INSERT_DENVER); sources.getConnection("h2file").createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection("h2file").createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=h2file)"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } @Test public void testHSQLMem() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); String database = "hsqlmem"; assertThat(sources.getDataSources()).containsKeys(database); assertThat(sources.getDataSource(database)).isNotNull(); sources.getConnection(database).createStatement().execute(Statements.CREATE_TABLE); sources.getConnection(database).createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection(database).createStatement().execute(Statements.INSERT_DENVER); sources.getConnection(database).createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection(database).createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=" + database + ")"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } @Test public void testHSQLFile() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); assertThat(sources.getDataSources()).containsKeys("hsqlfile"); assertThat(sources.getDataSource("hsqlfile")).isNotNull(); sources.getConnection("hsqlfile").createStatement().execute(Statements.CREATE_TABLE); sources.getConnection("hsqlfile").createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection("hsqlfile").createStatement().execute(Statements.INSERT_DENVER); sources.getConnection("hsqlfile").createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection("hsqlfile").createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=hsqlfile)"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } @Test public void testSQLite() throws SQLException, InvalidSyntaxException { assertThat(sources).isNotNull(); String database = "sqlite"; assertThat(sources.getDataSources()).containsKeys(database); assertThat(sources.getDataSource(database)).isNotNull(); sources.getConnection(database).createStatement().execute(Statements.CREATE_TABLE); sources.getConnection(database).createStatement().execute(Statements.INSERT_CARIBOU); sources.getConnection(database).createStatement().execute(Statements.INSERT_DENVER); sources.getConnection(database).createStatement().execute(Statements.INSERT_PHOENIX); ResultSet results = sources.getConnection(database).createStatement().executeQuery(Statements.SELECT_WITH_LAT); assertThat(results).isNotNull(); // We have only one result (CARIBOU) results.next(); assertThat(results.getString(2).trim()).isEqualTo("Caribou"); results.close(); // Check the Data Source service Collection<ServiceReference<DataSource>> refs = context.getServiceReferences(DataSource.class, "(datasource.name=" + database + ")"); assertThat(refs).isNotNull().isNotEmpty().hasSize(1); } }
hboumedane/wisdom-jdbc
wisdom-jdbc-datasources/src/test/java/org/wisdom/database/jdbc/it/DataSourcesIT.java
Java
apache-2.0
8,891
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ReadOnlyByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.base64.Base64Dialect; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.List; import java.util.Set; import javax.net.ssl.SSLHandshakeException; import static java.util.Arrays.asList; /** * Constants for SSL packets. */ final class SslUtils { // Protocols static final String PROTOCOL_SSL_V2_HELLO = "SSLv2Hello"; static final String PROTOCOL_SSL_V2 = "SSLv2"; static final String PROTOCOL_SSL_V3 = "SSLv3"; static final String PROTOCOL_TLS_V1 = "TLSv1"; static final String PROTOCOL_TLS_V1_1 = "TLSv1.1"; static final String PROTOCOL_TLS_V1_2 = "TLSv1.2"; /** * change cipher spec */ static final int SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC = 20; /** * alert */ static final int SSL_CONTENT_TYPE_ALERT = 21; /** * handshake */ static final int SSL_CONTENT_TYPE_HANDSHAKE = 22; /** * application data */ static final int SSL_CONTENT_TYPE_APPLICATION_DATA = 23; /** * HeartBeat Extension */ static final int SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT = 24; /** * the length of the ssl record header (in bytes) */ static final int SSL_RECORD_HEADER_LENGTH = 5; /** * Not enough data in buffer to parse the record length */ static final int NOT_ENOUGH_DATA = -1; /** * data is not encrypted */ static final int NOT_ENCRYPTED = -2; static final String[] DEFAULT_CIPHER_SUITES = { // GCM (Galois/Counter Mode) requires JDK 8. "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", // AES256 requires JCE unlimited strength jurisdiction policy files. "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", // GCM (Galois/Counter Mode) requires JDK 8. "TLS_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", // AES256 requires JCE unlimited strength jurisdiction policy files. "TLS_RSA_WITH_AES_256_CBC_SHA" }; /** * Add elements from {@code names} into {@code enabled} if they are in {@code supported}. */ static void addIfSupported(Set<String> supported, List<String> enabled, String... names) { for (String n: names) { if (supported.contains(n)) { enabled.add(n); } } } static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, Iterable<String> fallbackCiphers) { if (defaultCiphers.isEmpty()) { for (String cipher : fallbackCiphers) { if (cipher.startsWith("SSL_") || cipher.contains("_RC4_")) { continue; } defaultCiphers.add(cipher); } } } static void useFallbackCiphersIfDefaultIsEmpty(List<String> defaultCiphers, String... fallbackCiphers) { useFallbackCiphersIfDefaultIsEmpty(defaultCiphers, asList(fallbackCiphers)); } /** * Converts the given exception to a {@link SSLHandshakeException}, if it isn't already. */ static SSLHandshakeException toSSLHandshakeException(Throwable e) { if (e instanceof SSLHandshakeException) { return (SSLHandshakeException) e; } return (SSLHandshakeException) new SSLHandshakeException(e.getMessage()).initCause(e); } /** * Return how much bytes can be read out of the encrypted data. Be aware that this method will not increase * the readerIndex of the given {@link ByteBuf}. * * @param buffer * The {@link ByteBuf} to read from. Be aware that it must have at least * {@link #SSL_RECORD_HEADER_LENGTH} bytes to read, * otherwise it will throw an {@link IllegalArgumentException}. * @return length * The length of the encrypted packet that is included in the buffer or * {@link #SslUtils#NOT_ENOUGH_DATA} if not enough data is present in the * {@link ByteBuf}. This will return {@link SslUtils#NOT_ENCRYPTED} if * the given {@link ByteBuf} is not encrypted at all. * @throws IllegalArgumentException * Is thrown if the given {@link ByteBuf} has not at least {@link #SSL_RECORD_HEADER_LENGTH} * bytes to read. */ static int getEncryptedPacketLength(ByteBuf buffer, int offset) { int packetLength = 0; // SSLv3 or TLS - Check ContentType boolean tls; switch (buffer.getUnsignedByte(offset)) { case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC: case SSL_CONTENT_TYPE_ALERT: case SSL_CONTENT_TYPE_HANDSHAKE: case SSL_CONTENT_TYPE_APPLICATION_DATA: case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT: tls = true; break; default: // SSLv2 or bad data tls = false; } if (tls) { // SSLv3 or TLS - Check ProtocolVersion int majorVersion = buffer.getUnsignedByte(offset + 1); if (majorVersion == 3) { // SSLv3 or TLS packetLength = unsignedShortBE(buffer, offset + 3) + SSL_RECORD_HEADER_LENGTH; if (packetLength <= SSL_RECORD_HEADER_LENGTH) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } else { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } if (!tls) { // SSLv2 or bad data - Check the version int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3; int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 packetLength = headerLength == 2 ? (shortBE(buffer, offset) & 0x7FFF) + 2 : (shortBE(buffer, offset) & 0x3FFF) + 3; if (packetLength <= headerLength) { return NOT_ENOUGH_DATA; } } else { return NOT_ENCRYPTED; } } return packetLength; } // Reads a big-endian unsigned short integer from the buffer @SuppressWarnings("deprecation") private static int unsignedShortBE(ByteBuf buffer, int offset) { return buffer.order() == ByteOrder.BIG_ENDIAN ? buffer.getUnsignedShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset)) & 0xFFFF; } // Reads a big-endian short integer from the buffer @SuppressWarnings("deprecation") private static short shortBE(ByteBuf buffer, int offset) { return buffer.order() == ByteOrder.BIG_ENDIAN ? buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset)); } private static short unsignedByte(byte b) { return (short) (b & 0xFF); } // Reads a big-endian unsigned short integer from the buffer private static int unsignedShortBE(ByteBuffer buffer, int offset) { return shortBE(buffer, offset) & 0xFFFF; } // Reads a big-endian short integer from the buffer private static short shortBE(ByteBuffer buffer, int offset) { return buffer.order() == ByteOrder.BIG_ENDIAN ? buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset)); } static int getEncryptedPacketLength(ByteBuffer[] buffers, int offset) { ByteBuffer buffer = buffers[offset]; // Check if everything we need is in one ByteBuffer. If so we can make use of the fast-path. if (buffer.remaining() >= SSL_RECORD_HEADER_LENGTH) { return getEncryptedPacketLength(buffer); } // We need to copy 5 bytes into a temporary buffer so we can parse out the packet length easily. ByteBuffer tmp = ByteBuffer.allocate(5); do { buffer = buffers[offset++].duplicate(); if (buffer.remaining() > tmp.remaining()) { buffer.limit(buffer.position() + tmp.remaining()); } tmp.put(buffer); } while (tmp.hasRemaining()); // Done, flip the buffer so we can read from it. tmp.flip(); return getEncryptedPacketLength(tmp); } private static int getEncryptedPacketLength(ByteBuffer buffer) { int packetLength = 0; int pos = buffer.position(); // SSLv3 or TLS - Check ContentType boolean tls; switch (unsignedByte(buffer.get(pos))) { case SSL_CONTENT_TYPE_CHANGE_CIPHER_SPEC: case SSL_CONTENT_TYPE_ALERT: case SSL_CONTENT_TYPE_HANDSHAKE: case SSL_CONTENT_TYPE_APPLICATION_DATA: case SSL_CONTENT_TYPE_EXTENSION_HEARTBEAT: tls = true; break; default: // SSLv2 or bad data tls = false; } if (tls) { // SSLv3 or TLS - Check ProtocolVersion int majorVersion = unsignedByte(buffer.get(pos + 1)); if (majorVersion == 3) { // SSLv3 or TLS packetLength = unsignedShortBE(buffer, pos + 3) + SSL_RECORD_HEADER_LENGTH; if (packetLength <= SSL_RECORD_HEADER_LENGTH) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } else { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } if (!tls) { // SSLv2 or bad data - Check the version int headerLength = (unsignedByte(buffer.get(pos)) & 0x80) != 0 ? 2 : 3; int majorVersion = unsignedByte(buffer.get(pos + headerLength + 1)); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 packetLength = headerLength == 2 ? (shortBE(buffer, pos) & 0x7FFF) + 2 : (shortBE(buffer, pos) & 0x3FFF) + 3; if (packetLength <= headerLength) { return NOT_ENOUGH_DATA; } } else { return NOT_ENCRYPTED; } } return packetLength; } static void notifyHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) { // We have may haven written some parts of data before an exception was thrown so ensure we always flush. // See https://github.com/netty/netty/issues/3900#issuecomment-172481830 ctx.flush(); ctx.fireUserEventTriggered(new SslHandshakeCompletionEvent(cause)); ctx.close(); } /** * Fills the {@link ByteBuf} with zero bytes. */ static void zeroout(ByteBuf buffer) { if (!(buffer instanceof ReadOnlyByteBuf)) { buffer.setZero(0, buffer.capacity()); } } /** * Fills the {@link ByteBuf} with zero bytes and releases it. */ static void zerooutAndRelease(ByteBuf buffer) { zeroout(buffer); buffer.release(); } /** * Same as {@link Base64#encode(ByteBuf, boolean)} but allows the use of a custom {@link ByteBufAllocator}. * * @see Base64#encode(ByteBuf, boolean) */ static ByteBuf toBase64(ByteBufAllocator allocator, ByteBuf src) { ByteBuf dst = Base64.encode(src, src.readerIndex(), src.readableBytes(), true, Base64Dialect.STANDARD, allocator); src.readerIndex(src.writerIndex()); return dst; } private SslUtils() { } }
imangry/netty-zh
handler/src/main/java/io/netty/handler/ssl/SslUtils.java
Java
apache-2.0
12,781
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.extension.definition.extraction; import org.apache.maven.artifact.Artifact; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class ExtensionClassLoader extends URLClassLoader { private final URL[] urls; private final Artifact narArtifact; private final Collection<Artifact> allArtifacts; public ExtensionClassLoader(final URL[] urls, final ClassLoader parent, final Artifact narArtifact, final Collection<Artifact> otherArtifacts) { super(urls, parent); this.urls = urls; this.narArtifact = narArtifact; this.allArtifacts = new ArrayList<>(otherArtifacts); if (narArtifact != null) { allArtifacts.add(narArtifact); } } public ExtensionClassLoader(final URL[] urls, final Artifact narArtifact, final Collection<Artifact> otherArtifacts) { super(urls); this.urls = urls; this.narArtifact = narArtifact; this.allArtifacts = new ArrayList<>(otherArtifacts); if (narArtifact != null) { allArtifacts.add(narArtifact); } } public String getNiFiApiVersion() { final Collection<Artifact> artifacts = getAllArtifacts(); for (final Artifact artifact : artifacts) { if (artifact.getArtifactId().equals("nifi-api") && artifact.getGroupId().equals("org.apache.nifi")) { return artifact.getVersion(); } } final ClassLoader parent = getParent(); if (parent instanceof ExtensionClassLoader) { return ((ExtensionClassLoader) parent).getNiFiApiVersion(); } return null; } public Artifact getNarArtifact() { return narArtifact; } public Collection<Artifact> getAllArtifacts() { return allArtifacts; } @Override public String toString() { return "ExtensionClassLoader[" + narArtifact + ", Dependencies=" + Arrays.asList(urls) + "]"; } public String toTree() { final StringBuilder sb = new StringBuilder(); sb.append("ClassLoader for ").append(narArtifact).append(" with nifi-api version ").append(getNiFiApiVersion()).append(":\n"); for (final URL url : urls) { sb.append(url).append("\n"); } final ClassLoader parent = getParent(); if (parent instanceof ExtensionClassLoader) { sb.append("\n\n-------- Parent:\n"); sb.append(((ExtensionClassLoader) parent).toTree()); } else if (parent instanceof URLClassLoader) { sb.append(toTree((URLClassLoader) parent)); } return sb.toString(); } private String toTree(final URLClassLoader classLoader) { final StringBuilder sb = new StringBuilder(); sb.append("\n\n-------- Parent:\n"); final URL[] urls = classLoader.getURLs(); for (final URL url : urls) { sb.append(url).append("\n"); } final ClassLoader parent = classLoader.getParent(); if (parent instanceof URLClassLoader) { final URLClassLoader urlParent = (URLClassLoader) parent; sb.append(toTree(urlParent)); } return sb.toString(); } }
apache/nifi-maven
src/main/java/org/apache/nifi/extension/definition/extraction/ExtensionClassLoader.java
Java
apache-2.0
4,115
/** * Copyright 2009-2012 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Consumer Type</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getConsumerType() * @model * @generated */ public enum ConsumerType implements Enumerator { /** * The '<em><b>Highlevel</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #HIGHLEVEL_VALUE * @generated * @ordered */ HIGHLEVEL(0, "highlevel", "highlevel"), /** * The '<em><b>Simple</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SIMPLE_VALUE * @generated * @ordered */ SIMPLE(1, "simple", "simple"); /** * The '<em><b>Highlevel</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Highlevel</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #HIGHLEVEL * @model name="highlevel" * @generated * @ordered */ public static final int HIGHLEVEL_VALUE = 0; /** * The '<em><b>Simple</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Simple</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SIMPLE * @model name="simple" * @generated * @ordered */ public static final int SIMPLE_VALUE = 1; /** * An array of all the '<em><b>Consumer Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ConsumerType[] VALUES_ARRAY = new ConsumerType[] { HIGHLEVEL, SIMPLE, }; /** * A public read-only list of all the '<em><b>Consumer Type</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<ConsumerType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Consumer Type</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static ConsumerType get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ConsumerType result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Consumer Type</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static ConsumerType getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ConsumerType result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Consumer Type</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static ConsumerType get(int value) { switch (value) { case HIGHLEVEL_VALUE: return HIGHLEVEL; case SIMPLE_VALUE: return SIMPLE; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ConsumerType(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } // ConsumerType
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/ConsumerType.java
Java
apache-2.0
6,092
/** * **************************************************************************** * <p> * Copyright (c) 2015. Rick Hightower, Geoff Chandler * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ________ __________.______________ * \_____ \\______ \ \__ ___/ * / / \ \| | _/ | | | ______ * / \_/. \ | \ | | | /_____/ * \_____\ \_/______ /___| |____| * \__> \/ * ___________.__ ____. _____ .__ .__ * \__ ___/| |__ ____ | |____ ___ _______ / \ |__| ___________ ____ ______ ______________ _|__| ____ ____ * | | | | \_/ __ \ | \__ \\ \/ /\__ \ / \ / \| |/ ___\_ __ \/ _ \/ ___// __ \_ __ \ \/ / |/ ___\/ __ \ * | | | Y \ ___/ /\__| |/ __ \\ / / __ \_ / Y \ \ \___| | \( <_> )___ \\ ___/| | \/\ /| \ \__\ ___/ * |____| |___| /\___ > \________(____ /\_/ (____ / \____|__ /__|\___ >__| \____/____ >\___ >__| \_/ |__|\___ >___ > * \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ * .____ ._____. * | | |__\_ |__ * | | | || __ \ * | |___| || \_\ \ * |_______ \__||___ / * \/ \/ * ____. _________________ _______ __ __ ___. _________ __ __ _____________________ ____________________ * | |/ _____/\_____ \ \ \ / \ / \ ____\_ |__ / _____/ ____ ____ | | __ _____/ |_ \______ \_ _____// _____/\__ ___/ * | |\_____ \ / | \ / | \ \ \/\/ // __ \| __ \ \_____ \ / _ \_/ ___\| |/ // __ \ __\ | _/| __)_ \_____ \ | | * /\__| |/ \/ | \/ | \ \ /\ ___/| \_\ \/ ( <_> ) \___| <\ ___/| | | | \| \/ \ | | * \________/_______ /\_______ /\____|__ / /\ \__/\ / \___ >___ /_______ /\____/ \___ >__|_ \\___ >__| /\ |____|_ /_______ /_______ / |____| * \/ \/ \/ )/ \/ \/ \/ \/ \/ \/ \/ )/ \/ \/ \/ * __________ __ .__ __ __ ___. * \______ \ ____ _/ |_| |__ ____ / \ / \ ____\_ |__ * | | _// __ \ \ __\ | \_/ __ \ \ \/\/ // __ \| __ \ * | | \ ___/ | | | Y \ ___/ \ /\ ___/| \_\ \ * |______ /\___ > |__| |___| /\___ > \__/\ / \___ >___ / * \/ \/ \/ \/ \/ \/ \/ * <p> * QBit - The Microservice lib for Java : JSON, WebSocket, REST. Be The Web! * http://rick-hightower.blogspot.com/2014/12/rise-of-machines-writing-high-speed.html * http://rick-hightower.blogspot.com/2014/12/quick-guide-to-programming-services-in.html * http://rick-hightower.blogspot.com/2015/01/quick-startClient-qbit-programming.html * http://rick-hightower.blogspot.com/2015/01/high-speed-soa.html * http://rick-hightower.blogspot.com/2015/02/qbit-event-bus.html * <p> * **************************************************************************** */ package io.advantageous.qbit.service; /** * created by rhightower on 2/19/15. */ public interface Startable { default void start() { } default void startWithNotify(Runnable runnable) { throw new UnsupportedOperationException("start With Notice if not supported by " + this.getClass().getName()); } }
RichardHightower/qbit
qbit/core/src/main/java/io/advantageous/qbit/service/Startable.java
Java
apache-2.0
4,060
package edu.rit.csh; /** * Autogenerated by Avro * * DO NOT EDIT DIRECTLY */ @SuppressWarnings("all") /** The record data for an article's view for a given hour */ @org.apache.avro.specific.AvroGenerated public class LogRecord extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"LogRecord\",\"doc\":\"The record data for an article's view for a given hour\",\"fields\":[{\"name\":\"pageTitle\",\"type\":\"string\",\"doc\":\"The title of the article\"},{\"name\":\"timestamp\",\"type\":\"long\",\"doc\":\"The hour in which the log data occured\"},{\"name\":\"count\",\"type\":\"int\",\"doc\":\"the number of views the article got\"}]}"); public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } /** The title of the article */ @Deprecated public java.lang.CharSequence pageTitle; /** The hour in which the log data occured */ @Deprecated public long timestamp; /** the number of views the article got */ @Deprecated public int count; /** * Default constructor. Note that this does not initialize fields * to their default values from the schema. If that is desired then * one should use <code>newBuilder()</code>. */ public LogRecord() {} /** * All-args constructor. */ public LogRecord(java.lang.CharSequence pageTitle, java.lang.Long timestamp, java.lang.Integer count) { this.pageTitle = pageTitle; this.timestamp = timestamp; this.count = count; } public org.apache.avro.Schema getSchema() { return SCHEMA$; } // Used by DatumWriter. Applications should not call. public java.lang.Object get(int field$) { switch (field$) { case 0: return pageTitle; case 1: return timestamp; case 2: return count; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } // Used by DatumReader. Applications should not call. @SuppressWarnings(value="unchecked") public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: pageTitle = (java.lang.CharSequence)value$; break; case 1: timestamp = (java.lang.Long)value$; break; case 2: count = (java.lang.Integer)value$; break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } /** * Gets the value of the 'pageTitle' field. * The title of the article */ public java.lang.CharSequence getPageTitle() { return pageTitle; } /** * Sets the value of the 'pageTitle' field. * The title of the article * @param value the value to set. */ public void setPageTitle(java.lang.CharSequence value) { this.pageTitle = value; } /** * Gets the value of the 'timestamp' field. * The hour in which the log data occured */ public java.lang.Long getTimestamp() { return timestamp; } /** * Sets the value of the 'timestamp' field. * The hour in which the log data occured * @param value the value to set. */ public void setTimestamp(java.lang.Long value) { this.timestamp = value; } /** * Gets the value of the 'count' field. * the number of views the article got */ public java.lang.Integer getCount() { return count; } /** * Sets the value of the 'count' field. * the number of views the article got * @param value the value to set. */ public void setCount(java.lang.Integer value) { this.count = value; } /** Creates a new LogRecord RecordBuilder */ public static LogRecord.Builder newBuilder() { return new LogRecord.Builder(); } /** Creates a new LogRecord RecordBuilder by copying an existing Builder */ public static LogRecord.Builder newBuilder(LogRecord.Builder other) { return new LogRecord.Builder(other); } /** Creates a new LogRecord RecordBuilder by copying an existing LogRecord instance */ public static LogRecord.Builder newBuilder(LogRecord other) { return new LogRecord.Builder(other); } /** * RecordBuilder for LogRecord instances. */ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<LogRecord> implements org.apache.avro.data.RecordBuilder<LogRecord> { private java.lang.CharSequence pageTitle; private long timestamp; private int count; /** Creates a new Builder */ private Builder() { super(LogRecord.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(LogRecord.Builder other) { super(other); if (isValidValue(fields()[0], other.pageTitle)) { this.pageTitle = data().deepCopy(fields()[0].schema(), other.pageTitle); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.timestamp)) { this.timestamp = data().deepCopy(fields()[1].schema(), other.timestamp); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.count)) { this.count = data().deepCopy(fields()[2].schema(), other.count); fieldSetFlags()[2] = true; } } /** Creates a Builder by copying an existing LogRecord instance */ private Builder(LogRecord other) { super(LogRecord.SCHEMA$); if (isValidValue(fields()[0], other.pageTitle)) { this.pageTitle = data().deepCopy(fields()[0].schema(), other.pageTitle); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.timestamp)) { this.timestamp = data().deepCopy(fields()[1].schema(), other.timestamp); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.count)) { this.count = data().deepCopy(fields()[2].schema(), other.count); fieldSetFlags()[2] = true; } } /** Gets the value of the 'pageTitle' field */ public java.lang.CharSequence getPageTitle() { return pageTitle; } /** Sets the value of the 'pageTitle' field */ public LogRecord.Builder setPageTitle(java.lang.CharSequence value) { validate(fields()[0], value); this.pageTitle = value; fieldSetFlags()[0] = true; return this; } /** Checks whether the 'pageTitle' field has been set */ public boolean hasPageTitle() { return fieldSetFlags()[0]; } /** Clears the value of the 'pageTitle' field */ public LogRecord.Builder clearPageTitle() { pageTitle = null; fieldSetFlags()[0] = false; return this; } /** Gets the value of the 'timestamp' field */ public java.lang.Long getTimestamp() { return timestamp; } /** Sets the value of the 'timestamp' field */ public LogRecord.Builder setTimestamp(long value) { validate(fields()[1], value); this.timestamp = value; fieldSetFlags()[1] = true; return this; } /** Checks whether the 'timestamp' field has been set */ public boolean hasTimestamp() { return fieldSetFlags()[1]; } /** Clears the value of the 'timestamp' field */ public LogRecord.Builder clearTimestamp() { fieldSetFlags()[1] = false; return this; } /** Gets the value of the 'count' field */ public java.lang.Integer getCount() { return count; } /** Sets the value of the 'count' field */ public LogRecord.Builder setCount(int value) { validate(fields()[2], value); this.count = value; fieldSetFlags()[2] = true; return this; } /** Checks whether the 'count' field has been set */ public boolean hasCount() { return fieldSetFlags()[2]; } /** Clears the value of the 'count' field */ public LogRecord.Builder clearCount() { fieldSetFlags()[2] = false; return this; } @Override public LogRecord build() { try { LogRecord record = new LogRecord(); record.pageTitle = fieldSetFlags()[0] ? this.pageTitle : (java.lang.CharSequence) defaultValue(fields()[0]); record.timestamp = fieldSetFlags()[1] ? this.timestamp : (java.lang.Long) defaultValue(fields()[1]); record.count = fieldSetFlags()[2] ? this.count : (java.lang.Integer) defaultValue(fields()[2]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } }
JDrit/HBaseBulkImportWikiData
src/main/java/edu/rit/csh/LogRecord.java
Java
apache-2.0
8,426
package org.vaadin.viritin.fields; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.ui.Component; import com.vaadin.ui.CustomField; import com.vaadin.ui.ListSelect; import java.util.Collection; import java.util.HashSet; /** * TODO improve this, just copy pasted from archived SmartFields addon. * * @see MultiSelectTable A table based and more complete version of this. * * @author mstahv * @param <T> the type of the value for this select */ @Deprecated public class CollectionSelect<T> extends CustomField<Collection<T>> { private ListSelect select = new ListSelect() { @SuppressWarnings("unchecked") public String getItemCaption(Object option) { if (captionGenerator != null) { return captionGenerator.getCaption((T) option); } return super.getItemCaption(option); }; }; private CaptionGenerator<T> captionGenerator; @Override protected Component initContent() { return select; } public CollectionSelect() { select.setMultiSelect(true); select.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange( com.vaadin.data.Property.ValueChangeEvent event) { /* * Modify the original collection to make it possible for e.g. * ORM tools to optimize queries */ Collection<T> collection = getInternalValue(); HashSet<T> orphaned = new HashSet<T>(collection); @SuppressWarnings("unchecked") Collection<T> newValueSet = (Collection<T>) select.getValue(); for (T t : newValueSet) { orphaned.remove(t); if (!collection.contains(t)) { collection.add(t); } } collection.removeAll(orphaned); CollectionSelect.super.setInternalValue(collection); fireValueChange(true); } }); } public CollectionSelect(Collection<T> options) { this(); setOptions(options); } public CollectionSelect(String caption, Collection<T> options) { this(caption); setOptions(options); } public CollectionSelect(String caption) { this(); setCaption(caption); } @SuppressWarnings("deprecation") public void setOptions(Collection<T> options) { select.setContainerDataSource(new BeanItemContainer<T>(options)); } @SuppressWarnings("unchecked") @Override public Class<? extends Collection<T>> getType() { try { return getPropertyDataSource().getType(); } catch (Exception e) { return null; } } @Override protected void setInternalValue(Collection<T> newValue) { super.setInternalValue(newValue); select.setValue(newValue); } public CaptionGenerator<T> getCaptionGenerator() { return captionGenerator; } public void setCaptionGenerator(CaptionGenerator<T> captionGenerator) { this.captionGenerator = captionGenerator; } }
bpupadhyaya/dashboard-demo-1
src/main/java/org/vaadin/viritin/fields/CollectionSelect.java
Java
apache-2.0
2,724
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.assistants; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceFaultInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceInSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AddressingEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.AggregateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BAMMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BeanMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.BuilderMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CacheMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CallTemplateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CalloutMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ClassMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloneMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CloudConnectorOperationInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.CommandMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ConditionalRouterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBLookupMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DBReportMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DataMapperMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DefaultEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DefaultEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.DropMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EJBMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnqueueMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EnrichMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EntitlementMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EventMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FailoverEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FailoverEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FastXSLTMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FaultMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.FilterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ForEachMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HTTPEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HTTPEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.HeaderMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.InboundEndpointOnErrorSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.InboundEndpointSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.IterateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.JsonTransformMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoadBalanceEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoadBalanceEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LogMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.LoopBackMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MergeNodeFirstInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MergeNodeSecondInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.MessageInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.NamedEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.OAuthMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PayloadFactoryMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PropertyGroupMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PropertyMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyFaultInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyInSequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ProxyInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.PublishEventMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RMSequenceMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RecipientListEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RecipientListEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RespondMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RouterMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RouterMediatorOutputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.RuleMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ScriptMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SendMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequenceInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequencesInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SmooksMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SpringMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.StoreMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SwitchMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateEndpointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TemplateEndpointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ThrottleMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.TransactionMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.URLRewriteMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.ValidateMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.WSDLEndPointInputConnector2EditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.WSDLEndPointInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XQueryMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.XSLTMediatorInputConnectorEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbModelingAssistantProvider; /** * @generated */ public class EsbModelingAssistantProviderOfRouterMediatorOutputConnectorEditPart extends EsbModelingAssistantProvider { /** * @generated */ @Override public List<IElementType> getRelTypesOnSource(IAdaptable source) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSource((RouterMediatorOutputConnectorEditPart) sourceEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSource(RouterMediatorOutputConnectorEditPart source) { List<IElementType> types = new ArrayList<IElementType>(1); types.add(EsbElementTypes.EsbLink_4001); return types; } /** * @generated */ @Override public List<IElementType> getRelTypesOnSourceAndTarget(IAdaptable source, IAdaptable target) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); IGraphicalEditPart targetEditPart = (IGraphicalEditPart) target.getAdapter(IGraphicalEditPart.class); return doGetRelTypesOnSourceAndTarget((RouterMediatorOutputConnectorEditPart) sourceEditPart, targetEditPart); } /** * @generated */ public List<IElementType> doGetRelTypesOnSourceAndTarget(RouterMediatorOutputConnectorEditPart source, IGraphicalEditPart targetEditPart) { List<IElementType> types = new LinkedList<IElementType>(); if (targetEditPart instanceof ProxyInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ProxyFaultInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DropMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PropertyMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PropertyGroupMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ThrottleMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FilterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LogMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EnrichMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof XSLTMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SwitchMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EventMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EntitlementMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ClassMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SpringMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ScriptMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FaultMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof XQueryMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CommandMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DBLookupMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DBReportMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SmooksMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SendMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HeaderMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloneMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CacheMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof IterateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CalloutMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TransactionMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RMSequenceMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RuleMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof OAuthMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AggregateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof StoreMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BuilderMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CallTemplateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PayloadFactoryMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EnqueueMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof URLRewriteMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ValidateMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RouterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ConditionalRouterMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BAMMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof BeanMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof EJBMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DefaultEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FailoverEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RecipientListEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof WSDLEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof NamedEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoadBalanceEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressingEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HTTPEndPointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TemplateEndpointInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloudConnectorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CloudConnectorOperationInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoopBackMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RespondMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof CallMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DataMapperMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FastXSLTMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ForEachMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof PublishEventMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof JsonTransformMediatorInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof ProxyInSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MessageInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MergeNodeFirstInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof MergeNodeSecondInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof SequencesInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof DefaultEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof AddressEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof FailoverEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof RecipientListEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof WSDLEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof LoadBalanceEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof HTTPEndPointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof TemplateEndpointInputConnector2EditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceFaultInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof APIResourceInSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof InboundEndpointSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } if (targetEditPart instanceof InboundEndpointOnErrorSequenceInputConnectorEditPart) { types.add(EsbElementTypes.EsbLink_4001); } return types; } /** * @generated */ @Override public List<IElementType> getTypesForTarget(IAdaptable source, IElementType relationshipType) { IGraphicalEditPart sourceEditPart = (IGraphicalEditPart) source.getAdapter(IGraphicalEditPart.class); return doGetTypesForTarget((RouterMediatorOutputConnectorEditPart) sourceEditPart, relationshipType); } /** * @generated */ public List<IElementType> doGetTypesForTarget(RouterMediatorOutputConnectorEditPart source, IElementType relationshipType) { List<IElementType> types = new ArrayList<IElementType>(); if (relationshipType == EsbElementTypes.EsbLink_4001) { types.add(EsbElementTypes.ProxyInputConnector_3003); types.add(EsbElementTypes.ProxyFaultInputConnector_3489); types.add(EsbElementTypes.DropMediatorInputConnector_3008); types.add(EsbElementTypes.PropertyMediatorInputConnector_3033); types.add(EsbElementTypes.PropertyGroupMediatorInputConnector_3789); types.add(EsbElementTypes.ThrottleMediatorInputConnector_3121); types.add(EsbElementTypes.FilterMediatorInputConnector_3010); types.add(EsbElementTypes.LogMediatorInputConnector_3018); types.add(EsbElementTypes.EnrichMediatorInputConnector_3036); types.add(EsbElementTypes.XSLTMediatorInputConnector_3039); types.add(EsbElementTypes.SwitchMediatorInputConnector_3042); types.add(EsbElementTypes.SequenceInputConnector_3049); types.add(EsbElementTypes.EventMediatorInputConnector_3052); types.add(EsbElementTypes.EntitlementMediatorInputConnector_3055); types.add(EsbElementTypes.ClassMediatorInputConnector_3058); types.add(EsbElementTypes.SpringMediatorInputConnector_3061); types.add(EsbElementTypes.ScriptMediatorInputConnector_3064); types.add(EsbElementTypes.FaultMediatorInputConnector_3067); types.add(EsbElementTypes.XQueryMediatorInputConnector_3070); types.add(EsbElementTypes.CommandMediatorInputConnector_3073); types.add(EsbElementTypes.DBLookupMediatorInputConnector_3076); types.add(EsbElementTypes.DBReportMediatorInputConnector_3079); types.add(EsbElementTypes.SmooksMediatorInputConnector_3082); types.add(EsbElementTypes.SendMediatorInputConnector_3085); types.add(EsbElementTypes.HeaderMediatorInputConnector_3100); types.add(EsbElementTypes.CloneMediatorInputConnector_3103); types.add(EsbElementTypes.CacheMediatorInputConnector_3106); types.add(EsbElementTypes.IterateMediatorInputConnector_3109); types.add(EsbElementTypes.CalloutMediatorInputConnector_3115); types.add(EsbElementTypes.TransactionMediatorInputConnector_3118); types.add(EsbElementTypes.RMSequenceMediatorInputConnector_3124); types.add(EsbElementTypes.RuleMediatorInputConnector_3127); types.add(EsbElementTypes.OAuthMediatorInputConnector_3130); types.add(EsbElementTypes.AggregateMediatorInputConnector_3112); types.add(EsbElementTypes.StoreMediatorInputConnector_3589); types.add(EsbElementTypes.BuilderMediatorInputConnector_3592); types.add(EsbElementTypes.CallTemplateMediatorInputConnector_3595); types.add(EsbElementTypes.PayloadFactoryMediatorInputConnector_3598); types.add(EsbElementTypes.EnqueueMediatorInputConnector_3601); types.add(EsbElementTypes.URLRewriteMediatorInputConnector_3621); types.add(EsbElementTypes.ValidateMediatorInputConnector_3624); types.add(EsbElementTypes.RouterMediatorInputConnector_3629); types.add(EsbElementTypes.ConditionalRouterMediatorInputConnector_3636); types.add(EsbElementTypes.BAMMediatorInputConnector_3681); types.add(EsbElementTypes.BeanMediatorInputConnector_3684); types.add(EsbElementTypes.EJBMediatorInputConnector_3687); types.add(EsbElementTypes.DefaultEndPointInputConnector_3021); types.add(EsbElementTypes.AddressEndPointInputConnector_3030); types.add(EsbElementTypes.FailoverEndPointInputConnector_3088); types.add(EsbElementTypes.RecipientListEndPointInputConnector_3693); types.add(EsbElementTypes.WSDLEndPointInputConnector_3092); types.add(EsbElementTypes.NamedEndpointInputConnector_3661); types.add(EsbElementTypes.LoadBalanceEndPointInputConnector_3095); types.add(EsbElementTypes.APIResourceEndpointInputConnector_3675); types.add(EsbElementTypes.AddressingEndpointInputConnector_3690); types.add(EsbElementTypes.HTTPEndPointInputConnector_3710); types.add(EsbElementTypes.TemplateEndpointInputConnector_3717); types.add(EsbElementTypes.CloudConnectorInputConnector_3720); types.add(EsbElementTypes.CloudConnectorOperationInputConnector_3723); types.add(EsbElementTypes.LoopBackMediatorInputConnector_3737); types.add(EsbElementTypes.RespondMediatorInputConnector_3740); types.add(EsbElementTypes.CallMediatorInputConnector_3743); types.add(EsbElementTypes.DataMapperMediatorInputConnector_3762); types.add(EsbElementTypes.FastXSLTMediatorInputConnector_3765); types.add(EsbElementTypes.ForEachMediatorInputConnector_3781); types.add(EsbElementTypes.PublishEventMediatorInputConnector_3786); types.add(EsbElementTypes.JsonTransformMediatorInputConnector_3792); types.add(EsbElementTypes.ProxyInSequenceInputConnector_3731); types.add(EsbElementTypes.MessageInputConnector_3046); types.add(EsbElementTypes.MergeNodeFirstInputConnector_3014); types.add(EsbElementTypes.MergeNodeSecondInputConnector_3015); types.add(EsbElementTypes.SequencesInputConnector_3616); types.add(EsbElementTypes.DefaultEndPointInputConnector_3644); types.add(EsbElementTypes.AddressEndPointInputConnector_3647); types.add(EsbElementTypes.FailoverEndPointInputConnector_3650); types.add(EsbElementTypes.RecipientListEndPointInputConnector_3697); types.add(EsbElementTypes.WSDLEndPointInputConnector_3654); types.add(EsbElementTypes.LoadBalanceEndPointInputConnector_3657); types.add(EsbElementTypes.HTTPEndPointInputConnector_3713); types.add(EsbElementTypes.TemplateEndpointInputConnector_3726); types.add(EsbElementTypes.APIResourceInputConnector_3670); types.add(EsbElementTypes.APIResourceFaultInputConnector_3672); types.add(EsbElementTypes.APIResourceInSequenceInputConnector_3747); types.add(EsbElementTypes.InboundEndpointSequenceInputConnector_3768); types.add(EsbElementTypes.InboundEndpointOnErrorSequenceInputConnector_3770); } return types; } }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/providers/assistants/EsbModelingAssistantProviderOfRouterMediatorOutputConnectorEditPart.java
Java
apache-2.0
30,420
package macrobase.analysis.transform; import macrobase.analysis.transform.aggregate.AggregateConf; import macrobase.conf.MacroBaseConf; import macrobase.datamodel.Datum; import macrobase.util.TestUtils; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static junit.framework.TestCase.assertTrue; public class BatchSlidingWindowTransformTest { private static MacroBaseConf conf = new MacroBaseConf(); private static List<Datum> data = new ArrayList<>(); @BeforeClass public static void setUpBeforeClass() throws Exception { conf.set(MacroBaseConf.TIME_COLUMN, 0); conf.set(AggregateConf.AGGREGATE_TYPE, AggregateConf.AggregateType.MAX); for (int i = 0; i < 100; ++i) { Datum d = TestUtils.createTimeDatum(i, 100 - i); data.add(d); } } @Test public void testBasicMaxAggregate() throws Exception { conf.set(MacroBaseConf.TIME_WINDOW, 10); SlidingWindowTransform sw = new BatchSlidingWindowTransform(conf, 5); sw.initialize(); sw.consume(data.subList(0, 20)); sw.shutdown(); List<Datum> transformed = sw.getStream().drain(); assertTrue(transformed.size() == 3); for (int i = 0; i < 3; i ++) { Datum d = transformed.get(i); assertTrue(d.metrics().getEntry(0) == i * 5); assertTrue(d.metrics().getEntry(1) == 100 - 5 * i); } } private void testContinuousStreams(int stream1, int stream2) throws Exception { SlidingWindowTransform sw = new BatchSlidingWindowTransform(conf, 25); sw.initialize(); sw.consume(data.subList(0, stream1)); sw.consume(data.subList(stream1, stream2)); sw.consume(data.subList(stream2, 100)); sw.shutdown(); List<Datum> transformed = sw.getStream().drain(); assertTrue(transformed.size() == 4); for (int i = 0; i < 4; i++) { Datum d = transformed.get(i); assertTrue(d.metrics().getEntry(0) == i * 25); assertTrue(d.metrics().getEntry(1) == 100 - 25 * i); } } private void testDiscontinuousStreams() throws Exception { SlidingWindowTransform sw = new BatchSlidingWindowTransform(conf, 25); // Should produce empty window in between sw.consume(data.subList(0, 46)); sw.consume(data.subList(80, 100)); sw.shutdown(); List<Datum> transformed = sw.getStream().drain(); assertTrue(transformed.size() == 4); assertTrue(transformed.get(0).metrics().getEntry(0) == 0); assertTrue(transformed.get(0).metrics().getEntry(1) == 100); assertTrue(transformed.get(1).metrics().getEntry(0) == 25); assertTrue(transformed.get(1).metrics().getEntry(1) == 75); assertTrue(transformed.get(2).metrics().getEntry(0) == 50); assertTrue(transformed.get(2).metrics().getEntry(1) == 0); assertTrue(transformed.get(3).metrics().getEntry(0) == 75); assertTrue(transformed.get(3).metrics().getEntry(1) == 20); } @Test public void testStreaming() throws Exception { // window = 35, slide = 25, MAX conf.set(MacroBaseConf.TIME_WINDOW, 35); // Test two different breakdowns of streams should get the same result testContinuousStreams(40, 85); testContinuousStreams(13, 57); // Test data streams that have gaps in between conf.set(MacroBaseConf.TIME_WINDOW, 30); testDiscontinuousStreams(); } }
kexinrong/macrobase
contrib/src/test/java/macrobase/analysis/transform/BatchSlidingWindowTransformTest.java
Java
apache-2.0
3,576
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.operator.scalar; import io.airlift.jcodings.specific.NonStrictUTF8Encoding; import io.airlift.joni.Option; import io.airlift.joni.Regex; import io.airlift.joni.Syntax; import io.airlift.slice.Slice; import io.prestosql.spi.PrestoException; import io.prestosql.spi.function.LiteralParameter; import io.prestosql.spi.function.LiteralParameters; import io.prestosql.spi.function.OperatorType; import io.prestosql.spi.function.ScalarOperator; import io.prestosql.spi.function.SqlType; import io.prestosql.type.JoniRegexpType; import static io.prestosql.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static io.prestosql.spi.type.Chars.padSpaces; public final class JoniRegexpCasts { private JoniRegexpCasts() { } @LiteralParameters("x") @ScalarOperator(OperatorType.CAST) @SqlType(JoniRegexpType.NAME) public static Regex castVarcharToJoniRegexp(@SqlType("varchar(x)") Slice pattern) { return joniRegexp(pattern); } @ScalarOperator(OperatorType.CAST) @LiteralParameters("x") @SqlType(JoniRegexpType.NAME) public static Regex castCharToJoniRegexp(@LiteralParameter("x") Long charLength, @SqlType("char(x)") Slice pattern) { return joniRegexp(padSpaces(pattern, charLength.intValue())); } public static Regex joniRegexp(Slice pattern) { Regex regex; try { // When normal UTF8 encoding instead of non-strict UTF8) is used, joni can infinite loop when invalid UTF8 slice is supplied to it. regex = new Regex(pattern.getBytes(), 0, pattern.length(), Option.DEFAULT, NonStrictUTF8Encoding.INSTANCE, Syntax.Java); } catch (Exception e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } return regex; } }
youngwookim/presto
presto-main/src/main/java/io/prestosql/operator/scalar/JoniRegexpCasts.java
Java
apache-2.0
2,374
package com.ctrip.xpipe.tuple; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.ContextualDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import java.io.IOException; import java.util.List; /** * @author wenchao.meng * <p> * Jul 06, 2017 */ public class PairDeserial extends StdDeserializer<Pair> implements ContextualDeserializer { private JavaType javaType; private KeyDeserializer _keyDeserializer; private JsonDeserializer<Object> _valueDeserializer; private TypeDeserializer _valueTypeDeserializer; protected PairDeserial() { super((Class<?>) null); } public PairDeserial(JavaType type, KeyDeserializer keyDeser, JsonDeserializer<Object> valueDeser, TypeDeserializer valueTypeDeser) { super(type); this.javaType = type; this._keyDeserializer = keyDeser; this._valueDeserializer = valueDeser; this._valueTypeDeserializer = valueTypeDeser; } @Override public Pair<Object, Object> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonToken t = p.getCurrentToken(); if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME && t != JsonToken.END_OBJECT) { // String may be ok however: // slightly redundant (since String was passed above), but return _deserializeFromEmpty(p, ctxt); } if (t == JsonToken.START_OBJECT) { t = p.nextToken(); } if (t != JsonToken.FIELD_NAME) { if (t == JsonToken.END_OBJECT) { ctxt.reportMappingException("Can not deserialize a Map.Entry out of empty JSON Object"); return null; } return (Pair<Object, Object>) ctxt.handleUnexpectedToken(handledType(), p); } final KeyDeserializer keyDes = _keyDeserializer; final JsonDeserializer<Object> valueDes = _valueDeserializer; final TypeDeserializer typeDeser = _valueTypeDeserializer; final String keyStr = p.getCurrentName(); Object key = keyDes.deserializeKey(keyStr, ctxt); Object value = null; // And then the value... t = p.nextToken(); try { // Note: must handle null explicitly here; value deserializers won't if (t == JsonToken.VALUE_NULL) { value = valueDes.getNullValue(ctxt); } else if (typeDeser == null) { value = valueDes.deserialize(p, ctxt); } else { value = valueDes.deserializeWithType(p, ctxt, typeDeser); } } catch (Exception e) { throw new IllegalStateException("pair value deserialize error", e); } // Close, but also verify that we reached the END_OBJECT t = p.nextToken(); if (t != JsonToken.END_OBJECT) { if (t == JsonToken.FIELD_NAME) { // most likely ctxt.reportMappingException("Problem binding JSON into Map.Entry: more than one entry in JSON (second field: '"+p.getCurrentName()+"')"); } else { // how would this occur? ctxt.reportMappingException("Problem binding JSON into Map.Entry: unexpected content after JSON Object entry: "+t); } return null; } return new Pair<>(key, value); } @Override public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { JavaType contextualType = ctxt.getContextualType(); List<JavaType> typeParameters = contextualType.getBindings().getTypeParameters(); if (typeParameters.size() != 2) { throw new IllegalStateException("size should be 2"); } JavaType kt = typeParameters.get(0); JavaType vt = typeParameters.get(1); KeyDeserializer keyDeserializer = ctxt.findKeyDeserializer(kt, property); JsonDeserializer<Object> contextualValueDeserializer = ctxt.findContextualValueDeserializer(vt, property); return new PairDeserial(contextualType, keyDeserializer, contextualValueDeserializer, null); } }
Yiiinsh/x-pipe
core/src/main/java/com/ctrip/xpipe/tuple/PairDeserial.java
Java
apache-2.0
4,442
/* * Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Validator.java * * User: Greg Schueler <a href="mailto:[email protected]">[email protected]</a> * Created: 7/28/11 2:37 PM * */ package com.dtolabs.rundeck.core.plugins.configuration; import java.util.*; /** * Validator utility class can create a validation report for a set of input properties and a configuration * description. * * @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a> */ public class Validator { /** * A validation report */ public static class Report { private HashMap<String, String> errors = new HashMap<String, String>(); /** * @return a map of errors, keyed by property name. */ public HashMap<String, String> getErrors() { return errors; } /** * @return true if all property values were valid */ public boolean isValid() { return 0 == errors.size(); } @Override public String toString() { if(isValid()) { return "Property validation OK."; }else{ return "Property validation FAILED. " + "errors=" + errors ; } } } /** * Validate a set of properties for a description, and return a report. * * @param props the input properties * @param desc the configuration description * * @return the validation report */ public static Report validate(final Properties props, final Description desc) { final Report report = new Report(); final List<Property> properties = desc.getProperties(); validate(props, report, properties, null); return report; } /** * Validate, ignoring properties below a scope, if set * @param props input properties * @param report report * @param properties property definitions * @param ignoredScope ignore scope */ private static void validate(Properties props, Report report, List<Property> properties, PropertyScope ignoredScope) { if(null!=properties){ for (final Property property : properties) { if (null != ignoredScope && property.getScope() != null && property.getScope().compareTo(ignoredScope) <= 0) { continue; } final String key = property.getName(); final String value = props.getProperty(key); if (null == value || "".equals(value)) { if (property.isRequired()) { report.errors.put(key, "required"); continue; } } else { //try to validate final PropertyValidator validator = property.getValidator(); if (null != validator) { try { if (!validator.isValid(value)) { report.errors.put(key, "Invalid value"); } } catch (ValidationException e) { report.errors.put(key, "Invalid value: " + e.getMessage()); } } } } } } /** * Validate a set of properties for a description, and return a report. * * @param resolver property resolver * @param description description * @param defaultScope default scope for properties * * @return the validation report */ public static Report validate(final PropertyResolver resolver, final Description description, PropertyScope defaultScope) { return validate(resolver, description, defaultScope, null); } /** * Validate a set of properties for a description, and return a report. * * @param resolver property resolver * @param description description * @param defaultScope default scope for properties * @param ignoredScope ignore properties at or below this scope, or null to ignore none * @return the validation report */ public static Report validate(final PropertyResolver resolver, final Description description, PropertyScope defaultScope, PropertyScope ignoredScope) { final Report report = new Report(); final List<Property> properties = description.getProperties(); final Map<String, Object> inputConfig = PluginAdapterUtility.mapDescribedProperties(resolver, description, defaultScope); validate(asProperties(inputConfig), report, properties, ignoredScope); return report; } private static Properties asProperties(Map<String, Object> inputConfig) { Properties configuration = new Properties(); configuration.putAll(inputConfig); return configuration; } /** * Converts a set of input configuration keys using the description's configuration to property mapping, or the same * input if the description has no mapping * @param input input map * @param desc plugin description * @return mapped values */ public static Map<String, String> mapProperties(final Map<String, String> input, final Description desc) { final Map<String, String> mapping = desc.getPropertiesMapping(); if (null == mapping) { return input; } return performMapping(input, mapping, false); } /** * Convert input keys via the supplied mapping. * @param input data * @param mapping map to convert key names * @param skip if true, ignore input entries when the key is not present in the mapping */ private static Map<String, String> performMapping(final Map<String, String> input, final Map<String, String> mapping, final boolean skip) { final Map<String, String> props = new HashMap<String, String>(); for (final Map.Entry<String, String> entry : input.entrySet()) { if (null != mapping.get(entry.getKey())) { props.put(mapping.get(entry.getKey()), entry.getValue()); } else if(!skip) { props.put(entry.getKey(), entry.getValue()); } } return props; } /** * Reverses a set of properties mapped using the description's configuration to property mapping, or the same input * if the description has no mapping * @param input input map * @param desc plugin description * @return mapped values */ public static Map<String, String> demapProperties(final Map<String, String> input, final Description desc) { final Map<String, String> mapping = desc.getPropertiesMapping(); if (null == mapping) { return input; } final Map<String, String> rev = new HashMap<String, String>(); for (final Map.Entry<String, String> entry : mapping.entrySet()) { rev.put(entry.getValue(), entry.getKey()); } return performMapping(input, rev, true); } }
tjordanchat/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/configuration/Validator.java
Java
apache-2.0
7,855
package com.yeungeek.hencoder.draw5; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.StringRes; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager pager; List<PageModel> pageModels = new ArrayList<>(); { pageModels.add(new PageModel(R.layout.sample_after_on_draw, R.string.title_after_on_draw, R.layout.practice_after_on_draw)); pageModels.add(new PageModel(R.layout.sample_before_on_draw, R.string.title_before_on_draw, R.layout.practice_before_on_draw)); pageModels.add(new PageModel(R.layout.sample_on_draw_layout, R.string.title_on_draw_layout, R.layout.practice_on_draw_layout)); pageModels.add(new PageModel(R.layout.sample_dispatch_draw, R.string.title_dispatch_draw, R.layout.practice_dispatch_draw)); pageModels.add(new PageModel(R.layout.sample_after_on_draw_foreground, R.string.title_after_on_draw_foreground, R.layout.practice_after_on_draw_foreground)); pageModels.add(new PageModel(R.layout.sample_before_on_draw_foreground, R.string.title_before_on_draw_foreground, R.layout.practice_before_on_draw_foreground)); pageModels.add(new PageModel(R.layout.sample_after_draw, R.string.title_after_draw, R.layout.practice_after_draw)); pageModels.add(new PageModel(R.layout.sample_before_draw, R.string.title_before_draw, R.layout.practice_before_draw)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { PageModel pageModel = pageModels.get(position); return PageFragment.newInstance(pageModel.sampleLayoutRes, pageModel.practiceLayoutRes); } @Override public int getCount() { return pageModels.size(); } @Override public CharSequence getPageTitle(int position) { return getString(pageModels.get(position).titleRes); } }); tabLayout = (TabLayout) findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(pager); } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private class PageModel { @LayoutRes int sampleLayoutRes; @StringRes int titleRes; @LayoutRes int practiceLayoutRes; PageModel(@LayoutRes int sampleLayoutRes, @StringRes int titleRes, @LayoutRes int practiceLayoutRes) { this.sampleLayoutRes = sampleLayoutRes; this.titleRes = titleRes; this.practiceLayoutRes = practiceLayoutRes; } } }
yeungeek/AndroidRoad
HenCoderPractice/draw5/src/main/java/com/yeungeek/hencoder/draw5/MainActivity.java
Java
apache-2.0
3,262
package com.qubling.sidekick.model; import java.util.Collection; import java.util.Collections; import com.qubling.sidekick.fetch.Fetcher; import com.qubling.sidekick.fetch.SubqueryFetcher; import com.qubling.sidekick.fetch.UpdateFetcher; import com.qubling.sidekick.fetch.cpan.CPANQueryFetcher; import com.qubling.sidekick.fetch.cpan.ModuleDetailsFetcher; import com.qubling.sidekick.fetch.cpan.ModuleForReleaseFetcher; import com.qubling.sidekick.fetch.cpan.ModuleKeywordSearch; import com.qubling.sidekick.fetch.cpan.ModulePodFetcher; import com.qubling.sidekick.instance.Author; import com.qubling.sidekick.instance.Module; import com.qubling.sidekick.instance.Release; import com.qubling.sidekick.search.ResultSet; import com.qubling.sidekick.search.Schema; public class ModuleModel extends Model<Module> { public ModuleModel(Schema schema) { super(schema); } protected Module constructInstance(String name) { return new Module(this, name); } public Fetcher<Module> searchByKeyword(String keywords) { return new ModuleKeywordSearch(this, keywords); } public Fetcher<Module> searchByKeyword(String keywords, int size) { ModuleKeywordSearch keywordSearch = new ModuleKeywordSearch(this, keywords); keywordSearch.setSize(size); return keywordSearch; } public Fetcher<Module> fetchModulesForRelease(Release release) { CPANQueryFetcher<Module> fetcher = new ModuleForReleaseFetcher(this, release); fetcher.setSize(999); return fetcher; } public UpdateFetcher<Module> fetchPod() { return new ModulePodFetcher(this); } public UpdateFetcher<Module> fetch() { return new ModuleDetailsFetcher(this); } public UpdateFetcher<Module> fetchReleaseFavorites(String myPrivateToken) { ResultSet.Remap<Module, Release> remapper = new ResultSet.Remap<Module, Release>() { @Override public Collection<Release> map(Module module) { Release release = module.getRelease(); if (release == null) { return Collections.emptyList(); } else { return Collections.singleton(release); } } }; UpdateFetcher<Release> fetcher = getSchema().getReleaseModel().fetchFavorites(myPrivateToken); return new SubqueryFetcher<Module, Release>(this, fetcher, remapper); } public UpdateFetcher<Module> fetchReleaseRatings() { ResultSet.Remap<Module, Release> remapper = new ResultSet.Remap<Module, Release>() { @Override public Collection<Release> map(Module module) { Release release = module.getRelease(); if (release == null) { return Collections.emptyList(); } else { return Collections.singleton(release); } } }; UpdateFetcher<Release> fetcher = getSchema().getReleaseModel().fetchRatings(); return new SubqueryFetcher<Module, Release>(this, fetcher, remapper); } public UpdateFetcher<Module> fetchAuthors() { ResultSet.Remap<Module, Author> remapper = new ResultSet.Remap<Module, Author>() { @Override public Collection<Author> map(Module module) { Author author = module.getAuthor(); if (author == null) { return Collections.emptyList(); } else { return Collections.singleton(author); } } }; UpdateFetcher<Author> fetcher = getSchema().getAuthorModel().fetchDetails(); return new SubqueryFetcher<Module, Author>(this, fetcher, remapper); } public UpdateFetcher<Module> fetchGravatars(float gravatarDpSize) { ResultSet.Remap<Module, Author> remapper = new ResultSet.Remap<Module, Author>() { @Override public Collection<Author> map(Module module) { Author author = module.getAuthor(); if (author == null) { return Collections.emptyList(); } else { return Collections.singleton(author); } } }; UpdateFetcher<Author> fetcher = getSchema().getAuthorModel().fetchGravatars(gravatarDpSize); return new SubqueryFetcher<Module, Author>(this, fetcher, remapper); } @Override public String toString() { return getSchema() + ":ModuleModel"; } }
1nv4d3r5/CPAN-Sidekick
src/com/qubling/sidekick/model/ModuleModel.java
Java
artistic-2.0
4,009
package org.cellocad.adaptors.ucfwriters.ucf_writers_EcoJS4ibb; import org.cellocad.MIT.dnacompiler.Args; import org.cellocad.MIT.dnacompiler.Util; import org.cellocad.MIT.tandem_promoter.InterpolateTandemPromoter; import org.json.simple.JSONObject; import java.util.ArrayList; import java.util.Map; public class collection_writer_tandem_promoters extends collection_writer { @Override public ArrayList<Map> getObjects() { ArrayList<Map> objects = new ArrayList<>(); Args options = new Args(); String path = options.get_home() + "/resources/data/tandem_promoters/"; String in_csv = path + "tandem_promoter_params_110215.csv"; ArrayList<ArrayList<String>> in_tokens = Util.fileTokenizer(in_csv); /** * 4-input tandem promoter data trumps 2-input tandem promoter data. */ JSONObject tandem_promoter_objects = new JSONObject(); tokens2json(in_tokens, "in_110215", tandem_promoter_objects); //will overwrite ArrayList<String> tp_names = new ArrayList<String>( tandem_promoter_objects.keySet() ); for(String tp_name: tp_names) { JSONObject tp = (JSONObject) tandem_promoter_objects.get(tp_name); InterpolateTandemPromoter itp = new InterpolateTandemPromoter(); double[][] grid = itp.interpolateTandemPromoter(tp, tp_name); tp.put("grid", grid); objects.add(tp); } return objects; } public static void tokens2json(ArrayList<ArrayList<String>> tokens_list, String source, JSONObject tandem_promoter_objects) { String hill_activation = "ymin+(ymax-ymin)/(1.0+(K/x)^n)"; String hill_repression = "ymin+(ymax-ymin)/(1.0+(x/K)^n)"; for(ArrayList<String> tokens: tokens_list) { if(tokens.size() <= 3) { continue; } String gateA = tokens.get(0); String gateB = tokens.get(1); String state = tokens.get(2); Double ymax = Double.valueOf(tokens.get(3)); Double ymin = Double.valueOf(tokens.get(4)); Double K = Double.valueOf(tokens.get(5)); Double n = Double.valueOf(tokens.get(6)); String tandem_promoter_name = gateA + "_" + gateB; String equation_name = state + "_equation"; String params_name = state + "_params"; if(! tandem_promoter_objects.containsKey(tandem_promoter_name)) { tandem_promoter_objects.put(tandem_promoter_name, new JSONObject()); } JSONObject tp_obj = (JSONObject) tandem_promoter_objects.get(tandem_promoter_name); tp_obj.put("collection", "tandem_promoter"); tp_obj.put("name", gateA + "_" + gateB); tp_obj.put("gateA", gateA); tp_obj.put("gateB", gateB); tp_obj.put("source", source); JSONObject params = new JSONObject(); String gate_name = ""; if(equation_name.startsWith("0x") || equation_name.startsWith("1x")) { gate_name = gateB; } else { gate_name = gateA; } String type = ""; if(gate_name.contains("pTac") || gate_name.contains("pTet") || gate_name.contains("pBAD") || gate_name.contains("pLuxStar")) { type = "INPUT"; } else { type = "NOT"; } String regulation = ""; if(type.equals("INPUT")) { regulation = "activation"; } else if(type.equals("NOT")){ regulation = "repression"; } params.put("ymax", ymax); params.put("ymin", ymin); params.put("K", K); params.put("n", n); tp_obj.put(params_name, params); if(regulation.equals("activation")) { tp_obj.put(equation_name, hill_activation); } else if(regulation.equals("repression")) { tp_obj.put(equation_name, hill_repression); } } } }
CIDARLAB/cello
src/main/java/org/cellocad/adaptors/ucfwriters/ucf_writers_EcoJS4ibb/collection_writer_tandem_promoters.java
Java
bsd-2-clause
4,189
package org.glob3.mobile.specific; import org.glob3.mobile.generated.IByteBuffer; import org.glob3.mobile.generated.ICanvas; import org.glob3.mobile.generated.IDeviceInfo; import org.glob3.mobile.generated.IFactory; import org.glob3.mobile.generated.IFloatBuffer; import org.glob3.mobile.generated.IIntBuffer; import org.glob3.mobile.generated.IShortBuffer; import org.glob3.mobile.generated.ITimer; import org.glob3.mobile.generated.IWebSocket; import org.glob3.mobile.generated.IWebSocketListener; import org.glob3.mobile.generated.URL; public class Factory_JavaDesktop extends IFactory { @Override public ITimer createTimer() { throw new RuntimeException("Not yet implemented"); } @Override public IFloatBuffer createFloatBuffer(final int size) { return new FloatBuffer_JavaDesktop(size); } @Override public IFloatBuffer createFloatBuffer(final float pF0, final float pF1, final float pF2, final float pF3, final float pF4, final float pF5, final float pF6, final float pF7, final float pF8, final float pF9, final float pF10, final float pF11, final float pF12, final float pF13, final float pF14, final float pF15) { throw new RuntimeException("Not yet implemented"); } @Override public IIntBuffer createIntBuffer(final int pSize) { throw new RuntimeException("Not yet implemented"); } @Override public IShortBuffer createShortBuffer(final int size) { throw new RuntimeException("Not yet implemented"); } @Override public IByteBuffer createByteBuffer(final int length) { return new ByteBuffer_JavaDesktop(length); } @Override public IByteBuffer createByteBuffer(final byte[] data, final int length) { return new ByteBuffer_JavaDesktop(data); } @Override public ICanvas createCanvas() { throw new RuntimeException("Not yet implemented"); } @Override public IWebSocket createWebSocket(final URL url, final IWebSocketListener listener, final boolean autodeleteListener, final boolean autodeleteWebSocket) { throw new RuntimeException("Not yet implemented"); } // @Override // public IShortBuffer createShortBuffer(final short[] array) { // throw new RuntimeException("Not yet implemented"); // } // @Override // public IFloatBuffer createFloatBuffer(final float[] array) { // return new FloatBuffer_JavaDesktop(array); // } @Override public IShortBuffer createShortBuffer(final short[] array, final int length) { throw new RuntimeException("Not yet implemented"); } @Override public IFloatBuffer createFloatBuffer(final float[] array, final int length) { return new FloatBuffer_JavaDesktop(array, length); } @Override protected IDeviceInfo createDeviceInfo() { throw new RuntimeException("Not yet implemented"); } }
octavianiLocator/g3m
JavaDesktop/G3MJavaDesktopSDK/src/org/glob3/mobile/specific/Factory_JavaDesktop.java
Java
bsd-2-clause
3,745
package com.jamerlan.utils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Encoder { public byte[] encode(String text) throws UnsupportedEncodingException { byte[] bytesOfMessage = text.getBytes("UTF-8"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return md.digest(bytesOfMessage); } }
jamerlan/jSpringLobbyLib
src/main/java/com/jamerlan/utils/MD5Encoder.java
Java
bsd-2-clause
565
package org.jcodec.codecs.aac.blocks; import org.jcodec.common.io.BitReader; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * Channel pair element; reference: table 4.4. * * @author The JCodec project * */ public class BlockCPE extends BlockICS { private int[] ms_mask; public void parse(BitReader _in) { // int i, ret, common_window, ms_present = 0; // int common_window = _in.read1Bit(); if (common_window != 0) { parseICSInfo(_in); // i = cpe->ch[1].ics.use_kb_window[0]; // cpe->ch[1].ics = cpe->ch[0].ics; // cpe->ch[1].ics.use_kb_window[1] = i; // if (cpe->ch[1].ics.predictor_present && (ac->m4ac.object_type != // AOT_AAC_MAIN)) // if ((cpe->ch[1].ics.ltp.present = get_bits(gb, 1))) // decode_ltp(ac, &cpe->ch[1].ics.ltp, gb, cpe->ch[1].ics.max_sfb); int ms_present = _in.readNBit(2); if (ms_present == 3) { throw new RuntimeException("ms_present = 3 is reserved."); } else if (ms_present != 0) decodeMidSideStereo(_in, ms_present, 0, 0); } BlockICS ics1 = new BlockICS(); ics1.parse(_in); BlockICS ics2 = new BlockICS(); ics2.parse(_in); } private void decodeMidSideStereo(BitReader _in, int ms_present, int numWindowGroups, int maxSfb) { if (ms_present == 1) { for (int idx = 0; idx < numWindowGroups * maxSfb; idx++) ms_mask[idx] = _in.read1Bit(); } } }
jcodec/jcodec
src/main/java/org/jcodec/codecs/aac/blocks/BlockCPE.java
Java
bsd-2-clause
1,645
/* * Copyright (C) 2011, 2012 University of Szeged * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.arm.nevada.client.shared.events; import com.google.gwt.event.shared.EventHandler; public interface InstructionUpdatedInViewEventHandler extends EventHandler { void onInstructionUpdatedInView(InstructionUpdatedInViewEvent event); }
ossy-szeged/nevada
src/com/arm/nevada/client/shared/events/InstructionUpdatedInViewEventHandler.java
Java
bsd-2-clause
1,629
package com.atlassian.jira.plugins.dvcs.github.impl; import com.atlassian.jira.plugins.dvcs.github.api.GitHubRESTClient; import com.atlassian.jira.plugins.dvcs.github.api.model.GitHubRepositoryHook; import com.atlassian.jira.plugins.dvcs.model.Repository; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.springframework.stereotype.Component; import java.util.List; import javax.annotation.ParametersAreNonnullByDefault; import javax.ws.rs.core.MediaType; /** * An implementation of {@link GitHubRESTClient}. * * @author Stanislav Dvorscak */ @Component public class GitHubRESTClientImpl extends AbstractGitHubRESTClientImpl implements GitHubRESTClient { /** * {@inheritDoc} */ @Override public GitHubRepositoryHook addHook(Repository repository, GitHubRepositoryHook hook) { WebResource webResource = resource(repository, "/hooks"); return webResource.type(MediaType.APPLICATION_JSON_TYPE).post(GitHubRepositoryHook.class, hook); } /** * {@inheritDoc} */ @Override public void deleteHook(Repository repository, GitHubRepositoryHook hook) { WebResource webResource = resource(repository, "/hooks/" + hook.getId()); webResource.delete(); } /** * {@inheritDoc} */ @Override public List<GitHubRepositoryHook> getHooks(Repository repository) { WebResource hooksWebResource = resource(repository, "/hooks"); return getAll(hooksWebResource, GitHubRepositoryHook[].class); } @ParametersAreNonnullByDefault public List<GitHubRepositoryHook> getHooks(Repository repository, String username, String password) { WebResource hooksWebResource = resource(repository, "/hooks"); final HTTPBasicAuthFilter httpBasicFilter = new HTTPBasicAuthFilter(username, password); return getAll(hooksWebResource, GitHubRepositoryHook[].class, httpBasicFilter); } }
markphip/testing
jira-dvcs-connector-github/src/main/java/com/atlassian/jira/plugins/dvcs/github/impl/GitHubRESTClientImpl.java
Java
bsd-2-clause
1,996
/* Copyright (c) 2014, scenarioo.org Development Team * All rights reserved. * * See https://github.com/scenarioo?tab=members * for a complete list of contributors to this project. * * Redistribution and use of the Scenarioo Examples in source and binary forms, * with or without modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.scenarioo.example.e4.orders.createorder; import org.eclipse.jface.dialogs.IPageChangedListener; import org.eclipse.jface.dialogs.PageChangedEvent; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardDialog; import org.scenarioo.example.e4.dto.CreateOrderDTO; import org.scenarioo.example.e4.dto.OrderPositionsTableviewDTO; import org.scenarioo.example.e4.services.ArticleService; import org.scenarioo.example.e4.services.OrderService; public class NewOrderWizard extends Wizard implements IPageChangedListener { private final ArticleService articleService; private final OrderService orderService; protected OrderPage one; protected PositionsPage two; public NewOrderWizard(final OrderService orderService, final ArticleService articleService) { super(); this.orderService = orderService; this.articleService = articleService; setNeedsProgressMonitor(true); } @Override public String getWindowTitle() { return "Create New Order"; } @Override public void addPages() { OrderPositionsTableviewDTO orderPositionsForViewDTO = new OrderPositionsTableviewDTO(); one = new OrderPage(orderPositionsForViewDTO.getOrder()); two = new PositionsPage(articleService, orderPositionsForViewDTO); addPage(one); addPage(two); WizardDialog dialog = (WizardDialog) getContainer(); dialog.addPageChangedListener(this); } @Override public boolean performFinish() { CreateOrderDTO orderWithPos = new CreateOrderDTO(one.getOrderForUpdate(), two.getOrderPositionsForUpdate()); orderService.createOrder(orderWithPos); return true; } /** * @see org.eclipse.jface.dialogs.IPageChangedListener#pageChanged(org.eclipse.jface.dialogs.PageChangedEvent) */ @Override public void pageChanged(final PageChangedEvent event) { if (two.equals(event.getSelectedPage())) { two.updateOrderInfo(one.getOrderForUpdate()); } } }
scenarioo/scenarioo-example-swtbot-e4
plugins/org.scenarioo.example.e4.orders/src/org/scenarioo/example/e4/orders/createorder/NewOrderWizard.java
Java
bsd-2-clause
3,416
/* * Copyright (c) 2016, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.ac.man.cs.llvm.ir.model; import uk.ac.man.cs.llvm.ir.types.Type; public final class FunctionParameter implements ValueSymbol { private final Type type; private final int index; private String name = ValueSymbol.UNKNOWN; public FunctionParameter(Type type, int index) { this.type = type; this.index = index; } public int index() { return index; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = "%" + name; } @Override public Type getType() { return type; } }
crbb/sulong
projects/uk.ac.man.cs.llvm/src/uk/ac/man/cs/llvm/ir/model/FunctionParameter.java
Java
bsd-3-clause
2,235
package com.psddev.dari.db; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.Settings; /** * Caches the results of read operations. * * <p>For example, given:</p> * * <blockquote><pre>{@literal CachingDatabase caching = new CachingDatabase(); caching.setDelegate(Database.Static.getDefault()); PaginatedResult<Article> result = Query.from(Article.class).using(caching).select(0, 5); * }</pre></blockquote> * * <p>These are some of the queries that won't trigger additional * reads in the delegate database:</p> * * <ul> * <li>{@code Query.from(Article.class).using(caching).count()}</li> * <li>{@code Query.from(Article.class).using(caching).where("_id = ?", result.getItems().get(0));}</li> * </ul> * * <p>All methods are thread-safe.</p> */ public class CachingDatabase extends ForwardingDatabase { private static final String CACHE_SIZE_SETTING = "dari/cachingDatabaseMaximumSize"; private static final long DEFAULT_CACHE_SIZE = 1000L; private static final Object MISSING = new Object(); private final Cache<UUID, Object> objectCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private final Cache<UUID, Object> referenceCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private final Cache<Query<?>, List<?>> readAllCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private final Cache<Query<?>, Long> readCountCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private final Cache<Query<?>, Object> readFirstCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private final LoadingCache<Query<?>, Map<Range, PaginatedResult<?>>> readPartialCache = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build( new CacheLoader<Query<?>, Map<Range, PaginatedResult<?>>>() { @Override public Map<Range, PaginatedResult<?>> load(Query<?> key) throws Exception { return new ConcurrentHashMap<>(); } }); private final Cache<UUID, Boolean> idOnlyQueryIds = CacheBuilder.newBuilder().maximumSize(getCacheSize()).build(); private static class Range { public final long offset; public final int limit; public Range(long offset, int limit) { this.offset = offset; this.limit = limit; } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Range) { Range otherRange = (Range) other; return offset == otherRange.offset && limit == otherRange.limit; } else { return false; } } @Override public int hashCode() { return ObjectUtils.hashCode(offset, limit); } } /** * Returns the set of all IDs which were results of ID-only queries. * * @return Never {@code null}. Mutable. Thread-safe. */ public Set<UUID> getIdOnlyQueryIds() { return idOnlyQueryIds.asMap().keySet(); } /** * Returns the map of all objects cached so far. * * @return Never {@code null}. Mutable. Thread-safe. */ public Map<UUID, Object> getObjectCache() { return objectCache.asMap(); } /** * Returns the map of all object references cached so far. * * @return Never {@code null}. Mutable. Thread-safe. */ public Map<UUID, Object> getReferenceCache() { return referenceCache.asMap(); } // --- ForwardingDatabase support --- private long getCacheSize() { return Settings.getOrDefault(long.class, CACHE_SIZE_SETTING, DEFAULT_CACHE_SIZE); } private boolean isCacheDisabled(Query<?> query) { if (query.isCache()) { return query.as(QueryOptions.class).isDisabled(); } else { return true; } } private Object findCachedObject(UUID id, Query<?> query) { Object object = objectCache.getIfPresent(id); if (object == null && query.isReferenceOnly()) { object = referenceCache != null ? referenceCache.getIfPresent(id) : null; } if (object != null) { Class<?> objectClass = query.getObjectClass(); if (objectClass != null && !objectClass.isInstance(object)) { object = null; } } return object; } private void cacheObject(Object object) { State state = ((Recordable) object).getState(); UUID id = state.getId(); if (state.isReferenceOnly()) { referenceCache.put(id, object); } else if (!state.isResolveToReferenceOnly()) { objectCache.put(id, object); } } @Override @SuppressWarnings("unchecked") public <T> List<T> readAll(Query<T> query) { if (isCacheDisabled(query)) { return super.readAll(query); } List<Object> all = new ArrayList<Object>(); List<Object> values = query.findIdOnlyQueryValues(); if (values != null) { List<Object> newValues = null; for (Object value : values) { UUID valueId = ObjectUtils.to(UUID.class, value); if (valueId != null) { idOnlyQueryIds.put(valueId, true); Object object = findCachedObject(valueId, query); if (object != null) { all.add(object); continue; } } if (newValues == null) { newValues = new ArrayList<Object>(); } newValues.add(value); } if (newValues == null) { return (List<T>) all; } else { query = query.clone(); query.setPredicate(PredicateParser.Static.parse("_id = ?", newValues)); } } List<?> list = readAllCache.getIfPresent(query); if (list == null) { list = super.readAll(query); readAllCache.put(query, list); for (Object item : list) { cacheObject(item); } } all.addAll(list); return (List<T>) all; } @Override public long readCount(Query<?> query) { if (isCacheDisabled(query)) { return super.readCount(query); } Long count = readCountCache.getIfPresent(query); if (count == null) { COUNT: { if (readAllCache != null) { List<?> list = readAllCache.getIfPresent(query); if (list != null) { count = (long) list.size(); break COUNT; } } if (readPartialCache != null) { Map<Range, PaginatedResult<?>> subCache = readPartialCache.getIfPresent(query); if (subCache != null && !subCache.isEmpty()) { count = subCache.values().iterator().next().getCount(); break COUNT; } } count = super.readCount(query); } readCountCache.put(query, count); } return count; } @Override @SuppressWarnings("unchecked") public <T> T readFirst(Query<T> query) { if (isCacheDisabled(query)) { return super.readFirst(query); } List<Object> values = query.findIdOnlyQueryValues(); if (values != null) { for (Object value : values) { UUID valueId = ObjectUtils.to(UUID.class, value); if (valueId != null) { idOnlyQueryIds.put(valueId, true); Object object = findCachedObject(valueId, query); if (object != null) { return (T) object; } } } } Object first = readFirstCache.getIfPresent(query); if (first == null) { first = super.readFirst(query); if (first == null) { first = MISSING; } else { cacheObject(first); } readFirstCache.put(query, first); } return first != MISSING ? (T) first : null; } @Override @SuppressWarnings("unchecked") public <T> PaginatedResult<T> readPartial(Query<T> query, long offset, int limit) { if (isCacheDisabled(query)) { return super.readPartial(query, offset, limit); } Map<Range, PaginatedResult<?>> subCache = readPartialCache.getUnchecked(query); Range range = new Range(offset, limit); PaginatedResult<?> result = subCache.get(range); if (result == null) { result = super.readPartial(query, offset, limit); subCache.put(range, result); for (Object item : result.getItems()) { cacheObject(item); } } return (PaginatedResult<T>) result; } @Override public void save(State state) { super.save(state); flush(); } /** * Flush the entire cache. This is executed after every .save() to avoid inconsistent results. */ protected void flush() { objectCache.invalidateAll(); referenceCache.invalidateAll(); readAllCache.invalidateAll(); readCountCache.invalidateAll(); readFirstCache.invalidateAll(); readPartialCache.invalidateAll(); } /** * {@link Query} options for {@link CachingDatabase}. * * @deprecated Use {@link Query#isCache}, {@link Query#noCache}, or * {@link Query#setCache} instead. */ @Deprecated @Modification.FieldInternalNamePrefix("caching.") public static class QueryOptions extends Modification<Query<?>> { private boolean disabled; /** * Returns {@code true} if the caching should be disabled when * running the query. * * @deprecated Use {@link Query#isCache} instead. */ @Deprecated public boolean isDisabled() { Boolean old = ObjectUtils.to(Boolean.class, getOriginalObject().getOptions().get(IS_DISABLED_QUERY_OPTION)); return old != null ? old : disabled; } /** * Sets whether the caching should be disabled when running * the query. * * @deprecated Use {@link Query#noCache} or {@link Query#setCache} * instead. */ @Deprecated public void setDisabled(boolean disabled) { this.disabled = disabled; } } // --- Deprecated --- /** @deprecated Use {@link QueryOptions} instead. */ @Deprecated public static final String IS_DISABLED_QUERY_OPTION = "caching.isDisabled"; }
iamedu/dari
db/src/main/java/com/psddev/dari/db/CachingDatabase.java
Java
bsd-3-clause
11,552
package mltk.core; import java.util.Arrays; /** * Class for sparse vectors. * * @author Yin Lou * */ public class SparseVector implements Vector { protected int[] indices; protected double[] values; /** * Constructs a sparse vector from sparse-format arrays. * * @param indices the indices array. * @param values the values array. */ public SparseVector(int[] indices, double[] values) { this.indices = indices; this.values = values; } @Override public SparseVector copy() { int[] copyIndices = Arrays.copyOf(indices, indices.length); double[] copyValues = Arrays.copyOf(values, values.length); return new SparseVector(copyIndices, copyValues); } @Override public double getValue(int index) { int idx = Arrays.binarySearch(indices, index); if (idx >= 0) { return values[idx]; } else { return 0; } } @Override public double[] getValues() { return values; } /** * Returns the internal representation of indices. * * @return the internal representation of indices. */ public int[] getIndices() { return indices; } @Override public double[] getValues(int... indices) { double[] values = new double[indices.length]; for (int i = 0; i < values.length; i++) { values[i] = getValue(indices[i]); } return values; } @Override public void setValue(int index, double value) { int idx = Arrays.binarySearch(indices, index); if (idx >= 0) { values[idx] = value; } else { throw new UnsupportedOperationException(); } } @Override public void setValue(int[] indices, double[] v) { for (int i = 0; i < indices.length; i++) { setValue(indices[i], v[i]); } } @Override public boolean isSparse() { return true; } }
ardydedase/mltk
src/mltk/core/SparseVector.java
Java
bsd-3-clause
1,814
package com.oracle.pts.opp.wsclient.generated; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for RevenueLineSet complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RevenueLineSet"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="RevnId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="RevnLineTypeCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RevnSequenceNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="OptyId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="BUOrgId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="CustomerPartyId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="CustomerAccountId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="OwnerResourceId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="OwnerResourceOrgId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="OwnerOrgTreeStructCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="OwnerOrgTreeCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EffectiveDate" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/> * &lt;element name="ProdGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="RevnAmountCurcyCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RevnAmount" type="{http://xmlns.oracle.com/adf/svc/types/}AmountType" minOccurs="0"/> * &lt;element name="StatusCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CreatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CreationDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="ConflictId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="LastUpdatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="LastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="LastUpdateLogin" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="UserLastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/> * &lt;element name="ProdGroupName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="SalesAccountId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="Revenue" type="{http://xmlns.oracle.com/apps/sales/opptyMgmt/revenues/revenueService/}Revenue" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RevenueLineSet", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", propOrder = { "revnId", "revnLineTypeCode", "revnSequenceNumber", "optyId", "buOrgId", "customerPartyId", "customerAccountId", "ownerResourceId", "ownerResourceOrgId", "ownerOrgTreeStructCode", "ownerOrgTreeCode", "effectiveDate", "prodGroupId", "revnAmountCurcyCode", "revnAmount", "statusCode", "createdBy", "creationDate", "conflictId", "lastUpdatedBy", "lastUpdateDate", "lastUpdateLogin", "objectVersionNumber", "userLastUpdateDate", "prodGroupName", "salesAccountId", "revenue" }) public class RevenueLineSet { @XmlElement(name = "RevnId") protected Long revnId; @XmlElementRef(name = "RevnLineTypeCode", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> revnLineTypeCode; @XmlElementRef(name = "RevnSequenceNumber", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Integer> revnSequenceNumber; @XmlElementRef(name = "OptyId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> optyId; @XmlElementRef(name = "BUOrgId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> buOrgId; @XmlElementRef(name = "CustomerPartyId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> customerPartyId; @XmlElementRef(name = "CustomerAccountId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> customerAccountId; @XmlElementRef(name = "OwnerResourceId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> ownerResourceId; @XmlElementRef(name = "OwnerResourceOrgId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> ownerResourceOrgId; @XmlElementRef(name = "OwnerOrgTreeStructCode", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> ownerOrgTreeStructCode; @XmlElementRef(name = "OwnerOrgTreeCode", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> ownerOrgTreeCode; @XmlElementRef(name = "EffectiveDate", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> effectiveDate; @XmlElementRef(name = "ProdGroupId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> prodGroupId; @XmlElementRef(name = "RevnAmountCurcyCode", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> revnAmountCurcyCode; @XmlElementRef(name = "RevnAmount", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<AmountType> revnAmount; @XmlElementRef(name = "StatusCode", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> statusCode; @XmlElement(name = "CreatedBy") protected String createdBy; @XmlElement(name = "CreationDate") protected XMLGregorianCalendar creationDate; @XmlElement(name = "ConflictId") protected Long conflictId; @XmlElement(name = "LastUpdatedBy") protected String lastUpdatedBy; @XmlElement(name = "LastUpdateDate") protected XMLGregorianCalendar lastUpdateDate; @XmlElementRef(name = "LastUpdateLogin", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<String> lastUpdateLogin; @XmlElement(name = "ObjectVersionNumber") protected Integer objectVersionNumber; @XmlElementRef(name = "UserLastUpdateDate", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<XMLGregorianCalendar> userLastUpdateDate; @XmlElement(name = "ProdGroupName") protected String prodGroupName; @XmlElementRef(name = "SalesAccountId", namespace = "http://xmlns.oracle.com/oracle/apps/sales/opptyMgmt/revenues/revenueService/", type = JAXBElement.class) protected JAXBElement<Long> salesAccountId; @XmlElement(name = "Revenue") protected List<Revenue> revenue; /** * Gets the value of the revnId property. * * @return * possible object is * {@link Long } * */ public Long getRevnId() { return revnId; } /** * Sets the value of the revnId property. * * @param value * allowed object is * {@link Long } * */ public void setRevnId(Long value) { this.revnId = value; } /** * Gets the value of the revnLineTypeCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getRevnLineTypeCode() { return revnLineTypeCode; } /** * Sets the value of the revnLineTypeCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setRevnLineTypeCode(JAXBElement<String> value) { this.revnLineTypeCode = ((JAXBElement<String> ) value); } /** * Gets the value of the revnSequenceNumber property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Integer }{@code >} * */ public JAXBElement<Integer> getRevnSequenceNumber() { return revnSequenceNumber; } /** * Sets the value of the revnSequenceNumber property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Integer }{@code >} * */ public void setRevnSequenceNumber(JAXBElement<Integer> value) { this.revnSequenceNumber = ((JAXBElement<Integer> ) value); } /** * Gets the value of the optyId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getOptyId() { return optyId; } /** * Sets the value of the optyId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setOptyId(JAXBElement<Long> value) { this.optyId = ((JAXBElement<Long> ) value); } /** * Gets the value of the buOrgId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getBUOrgId() { return buOrgId; } /** * Sets the value of the buOrgId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setBUOrgId(JAXBElement<Long> value) { this.buOrgId = ((JAXBElement<Long> ) value); } /** * Gets the value of the customerPartyId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getCustomerPartyId() { return customerPartyId; } /** * Sets the value of the customerPartyId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setCustomerPartyId(JAXBElement<Long> value) { this.customerPartyId = ((JAXBElement<Long> ) value); } /** * Gets the value of the customerAccountId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getCustomerAccountId() { return customerAccountId; } /** * Sets the value of the customerAccountId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setCustomerAccountId(JAXBElement<Long> value) { this.customerAccountId = ((JAXBElement<Long> ) value); } /** * Gets the value of the ownerResourceId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getOwnerResourceId() { return ownerResourceId; } /** * Sets the value of the ownerResourceId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setOwnerResourceId(JAXBElement<Long> value) { this.ownerResourceId = ((JAXBElement<Long> ) value); } /** * Gets the value of the ownerResourceOrgId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getOwnerResourceOrgId() { return ownerResourceOrgId; } /** * Sets the value of the ownerResourceOrgId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setOwnerResourceOrgId(JAXBElement<Long> value) { this.ownerResourceOrgId = ((JAXBElement<Long> ) value); } /** * Gets the value of the ownerOrgTreeStructCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getOwnerOrgTreeStructCode() { return ownerOrgTreeStructCode; } /** * Sets the value of the ownerOrgTreeStructCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setOwnerOrgTreeStructCode(JAXBElement<String> value) { this.ownerOrgTreeStructCode = ((JAXBElement<String> ) value); } /** * Gets the value of the ownerOrgTreeCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getOwnerOrgTreeCode() { return ownerOrgTreeCode; } /** * Sets the value of the ownerOrgTreeCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setOwnerOrgTreeCode(JAXBElement<String> value) { this.ownerOrgTreeCode = ((JAXBElement<String> ) value); } /** * Gets the value of the effectiveDate property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getEffectiveDate() { return effectiveDate; } /** * Sets the value of the effectiveDate property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setEffectiveDate(JAXBElement<XMLGregorianCalendar> value) { this.effectiveDate = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the prodGroupId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getProdGroupId() { return prodGroupId; } /** * Sets the value of the prodGroupId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setProdGroupId(JAXBElement<Long> value) { this.prodGroupId = ((JAXBElement<Long> ) value); } /** * Gets the value of the revnAmountCurcyCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getRevnAmountCurcyCode() { return revnAmountCurcyCode; } /** * Sets the value of the revnAmountCurcyCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setRevnAmountCurcyCode(JAXBElement<String> value) { this.revnAmountCurcyCode = ((JAXBElement<String> ) value); } /** * Gets the value of the revnAmount property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link AmountType }{@code >} * */ public JAXBElement<AmountType> getRevnAmount() { return revnAmount; } /** * Sets the value of the revnAmount property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link AmountType }{@code >} * */ public void setRevnAmount(JAXBElement<AmountType> value) { this.revnAmount = ((JAXBElement<AmountType> ) value); } /** * Gets the value of the statusCode property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getStatusCode() { return statusCode; } /** * Sets the value of the statusCode property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setStatusCode(JAXBElement<String> value) { this.statusCode = ((JAXBElement<String> ) value); } /** * Gets the value of the createdBy property. * * @return * possible object is * {@link String } * */ public String getCreatedBy() { return createdBy; } /** * Sets the value of the createdBy property. * * @param value * allowed object is * {@link String } * */ public void setCreatedBy(String value) { this.createdBy = value; } /** * Gets the value of the creationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreationDate() { return creationDate; } /** * Sets the value of the creationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreationDate(XMLGregorianCalendar value) { this.creationDate = value; } /** * Gets the value of the conflictId property. * * @return * possible object is * {@link Long } * */ public Long getConflictId() { return conflictId; } /** * Sets the value of the conflictId property. * * @param value * allowed object is * {@link Long } * */ public void setConflictId(Long value) { this.conflictId = value; } /** * Gets the value of the lastUpdatedBy property. * * @return * possible object is * {@link String } * */ public String getLastUpdatedBy() { return lastUpdatedBy; } /** * Sets the value of the lastUpdatedBy property. * * @param value * allowed object is * {@link String } * */ public void setLastUpdatedBy(String value) { this.lastUpdatedBy = value; } /** * Gets the value of the lastUpdateDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getLastUpdateDate() { return lastUpdateDate; } /** * Sets the value of the lastUpdateDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setLastUpdateDate(XMLGregorianCalendar value) { this.lastUpdateDate = value; } /** * Gets the value of the lastUpdateLogin property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getLastUpdateLogin() { return lastUpdateLogin; } /** * Sets the value of the lastUpdateLogin property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setLastUpdateLogin(JAXBElement<String> value) { this.lastUpdateLogin = ((JAXBElement<String> ) value); } /** * Gets the value of the objectVersionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getObjectVersionNumber() { return objectVersionNumber; } /** * Sets the value of the objectVersionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setObjectVersionNumber(Integer value) { this.objectVersionNumber = value; } /** * Gets the value of the userLastUpdateDate property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public JAXBElement<XMLGregorianCalendar> getUserLastUpdateDate() { return userLastUpdateDate; } /** * Sets the value of the userLastUpdateDate property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >} * */ public void setUserLastUpdateDate(JAXBElement<XMLGregorianCalendar> value) { this.userLastUpdateDate = ((JAXBElement<XMLGregorianCalendar> ) value); } /** * Gets the value of the prodGroupName property. * * @return * possible object is * {@link String } * */ public String getProdGroupName() { return prodGroupName; } /** * Sets the value of the prodGroupName property. * * @param value * allowed object is * {@link String } * */ public void setProdGroupName(String value) { this.prodGroupName = value; } /** * Gets the value of the salesAccountId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public JAXBElement<Long> getSalesAccountId() { return salesAccountId; } /** * Sets the value of the salesAccountId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link Long }{@code >} * */ public void setSalesAccountId(JAXBElement<Long> value) { this.salesAccountId = ((JAXBElement<Long> ) value); } /** * Gets the value of the revenue property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the revenue property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRevenue().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Revenue } * * */ public List<Revenue> getRevenue() { if (revenue == null) { revenue = new ArrayList<Revenue>(); } return this.revenue; } }
delkyd/Oracle-Cloud
PaaS-SaaS_DynamicWS/CFHandler/JAX_WS_handlers_Accelerator/JAX_WS_handlers_Accelerator/src/com/oracle/pts/opp/wsclient/generated/RevenueLineSet.java
Java
bsd-3-clause
26,246
/* * Copyright (C) 2004-2019, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.sdk.model.notification; import static com.gooddata.sdk.common.util.ResourceUtils.readObjectFromResource; import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; import static net.javacrumbs.jsonunit.core.util.ResourceUtils.resource; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import org.testng.annotations.Test; public class ConditionTest { @Test public void testDeserialization() throws Exception { final TriggerCondition condition = readObjectFromResource("/notification/condition.json", TriggerCondition.class); assertThat(condition.getExpression(), is("true")); } @Test public void testSerialization() throws Exception { final TriggerCondition condition = new TriggerCondition("true"); assertThat(condition, jsonEquals(resource("notification/condition.json"))); } }
martiner/gooddata-java
gooddata-java-model/src/test/java/com/gooddata/sdk/model/notification/ConditionTest.java
Java
bsd-3-clause
1,132
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.renderers; import net.sourceforge.pmd.IRuleViolation; import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.Report; import java.io.IOException; import java.io.Writer; import java.util.Iterator; public class TextRenderer extends OnTheFlyRenderer { private boolean empty; public void start() throws IOException { empty = true; } public void renderFileViolations(Iterator<IRuleViolation> violations) throws IOException { Writer writer = getWriter(); StringBuffer buf = new StringBuffer(); empty = !violations.hasNext(); while (violations.hasNext()) { buf.setLength(0); IRuleViolation rv = violations.next(); buf.append(PMD.EOL).append(rv.getFilename()); buf.append(':').append(Integer.toString(rv.getBeginLine())); buf.append('\t').append(rv.getDescription()); writer.write(buf.toString()); } } public void end() throws IOException { Writer writer = getWriter(); StringBuffer buf = new StringBuffer(); if (!errors.isEmpty()) { empty = false; for(Report.ProcessingError error: errors) { buf.setLength(0); buf.append(PMD.EOL).append(error.getFile()); buf.append("\t-\t").append(error.getMsg()); writer.write(buf.toString()); } } for(Report.SuppressedViolation excluded: suppressed) { buf.setLength(0); buf.append(PMD.EOL); buf.append(excluded.getRuleViolation().getRule().getName()); buf.append(" rule violation suppressed by "); buf.append(excluded.suppressedByNOPMD() ? "//NOPMD" : "Annotation"); buf.append(" in ").append(excluded.getRuleViolation().getFilename()); writer.write(buf.toString()); } if (empty) { getWriter().write("No problems found!"); } } }
bolav/pmd-src-4.2.6-perl
src/net/sourceforge/pmd/renderers/TextRenderer.java
Java
bsd-3-clause
2,097
// ---------------------------------------------------------------------------- // Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // To contact the authors: // http://www.inf.ufrgs.br/~bordini // http://www.das.ufsc.br/~jomi // //---------------------------------------------------------------------------- package jason.asSyntax; import jason.NoValueException; import jason.asSemantics.Agent; import jason.asSemantics.Unifier; import jason.asSyntax.parser.as2j; import java.io.StringReader; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Represents a variable Term: like X (starts with upper case). It may have a * value, after {@link VarTerm}.apply. * * An object of this class can be used in place of a * Literal, Number, List, String, .... It behaves like a * Literal, Number, .... just in case its value is a Literal, * Number, ... * * @author jomi */ public class VarTerm extends LiteralImpl implements NumberTerm, ListTerm { //, StringTerm, ObjectTerm, PlanBody { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(VarTerm.class.getName()); //private Term value = null; public VarTerm(String s) { super(s); if (s != null && Character.isLowerCase(s.charAt(0))) { logger.warning("Are you sure you want to create a VarTerm that begins with lowercase (" + s + ")? Should it be a Term instead?"); Exception e = new Exception("stack"); e.printStackTrace(); } } public VarTerm(boolean negated, String s) { super(negated, s); } /** @deprecated prefer ASSyntax.parseVar(...) */ public static VarTerm parseVar(String sVar) { as2j parser = new as2j(new StringReader(sVar)); try { return parser.var(); } catch (Exception e) { logger.log(Level.SEVERE, "Error parsing var " + sVar, e); return null; } } @Override public Term capply(Unifier u) { if (u != null) { Term vl = u.get(this); if (vl != null) { if (!vl.isCyclicTerm() && vl.hasVar(this, u)) { //logger.warning("The value of a variable contains itself, variable "+super.getFunctor()+" "+super.getSrcInfo()+", value="+vl+", unifier="+u); u.remove(this); // remove this var to avoid loops in the apply below Term tempVl = vl.capply(u); u.bind(this, vl); CyclicTerm ct = new CyclicTerm((Literal)tempVl, this); Unifier renamedVars = new Unifier(); // remove "this" from the value to avoid loops in apply ct.makeVarsAnnon(renamedVars); renamedVars.remove(this); u.compose(renamedVars); vl = ct; } vl = vl.capply(u); // should clone here, since there is no cloning in unify // decide whether to use var annots in apply // X = p[a] // !X[b] // what's the event: // +!p[a] // or // +!p[a,b] // Answer: use annots of var, useful for meta-programming like // P[step(N)] if (vl.isLiteral() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental) vl = ((Literal)vl).forceFullLiteralImpl().addAnnots((ListTerm)this.getAnnots().capply(u)); } return vl; } } return clone(); } public Term clone() { // do not call constructor with term parameter! VarTerm t = new VarTerm(super.getFunctor()); t.setNegated(!negated()); t.srcInfo = this.srcInfo; if (hasAnnot()) t.setAnnots(getAnnots().cloneLT()); return t; } /* public PlanBody clonePB() { return (PlanBody)clone(); } */ public ListTerm cloneLT() { return (ListTerm)clone(); } @Override public boolean isVar() { return true; } public boolean isUnnamedVar() { return false; } @Override public boolean isGround() { return false; } /** * grounds a variable, set a value for this var * (e.g. X = 10; Y = a(b,c); ...) */ /*public boolean setValue(Term vl) { if (vl.isVar()) { logger.log(Level.WARNING, "Attempted set a variable as a value for a variable, in " + this.getFunctor(), new Exception()); return false; } vl = vl.clone(); // should clone here, since there is no cloning in unify // decide whether to use var annots in apply // X = p[a] // !X[b] // what's the event: // +!p[a] // or // +!p[a,b] // Answer: use annots of var, useful for meta-programming like // P[step(N)] if (vl.isLiteral() && this.hasAnnot()) { // if this var has annots, add them in the value's annots (Experimental) vl = ((Literal)vl).forceFullLiteralImpl().addAnnots(this.getAnnots()); } value = vl; resetHashCodeCache(); return true; }*/ /** returns true if this var has a value */ /* public boolean hasValue() { return value != null; } */ /* public boolean apply(Unifier u) { if (value == null) { Term vl = u.get(this); if (vl != null) { if (!vl.isCyclicTerm() && vl.hasVar(this, u)) { //logger.warning("The value of a variable contains itself, variable "+super.getFunctor()+" "+super.getSrcInfo()+", value="+vl+", unifier="+u); u.remove(this); // remove this var to avoid loops in the apply below //Term tempVl = vl.clone(); //tempVl.apply(u); Term tempVl = vl.capply(u); u.bind(this, vl); CyclicTerm ct = new CyclicTerm((Literal)tempVl, this); Unifier renamedVars = new Unifier(); // remove "this" from the value to avoid loops in apply ct.makeVarsAnnon(renamedVars); renamedVars.remove(this); u.compose(renamedVars); vl = ct; } vl = setValue(vl); value.apply(u); // in case t has var args return true; } } else { return getValue().apply(u); } return false; } */ /** * returns the value of this var. */ /* public Term getValue() { return value; }*/ @Override public boolean equals(Object t) { if (t == null) return false; if (t == this) return true; /*if (t instanceof Term) { Term vl = getValue(); // System.out.println("checking equals form "+tAsTerm.getFunctor()+" // and this "+this.getFunctor()+" my value "+vl); if (vl != null) { // compare the values return vl.equals(t); } */ // is t also a var? (its value must also be null) if (t instanceof VarTerm) { //final VarTerm tAsVT = (VarTerm) t; //if (tAsVT.getValue() == null) { return negated() == ((VarTerm)t).negated() && getFunctor().equals(((VarTerm)t).getFunctor()); //} } //} return false; } public int compareTo(Term t) { /*if (value != null) return value.compareTo(t); else*/ if (t == null || t.isUnnamedVar()) return -1; else if (t.isVar()) { if (!negated() && ((VarTerm)t).negated()) return -1; else return getFunctor().compareTo(((VarTerm)t).getFunctor()); } else { return 1; } } @Override public boolean subsumes(Term t) { /*if (value != null) return value.subsumes(t); else */ return true; } // ---------- // Term methods overridden // // in case this VarTerm has a value, use value's methods // ---------- /* @Override public String getFunctor() { if (value == null) { return super.getFunctor(); } else if (value instanceof Atom) { return ((Atom)getValue()).getFunctor(); } else { return null; } } @Override public PredicateIndicator getPredicateIndicator() { if (value != null && value.isLiteral()) { return ((Literal)value).getPredicateIndicator(); } else if (predicateIndicatorCache == null) { predicateIndicatorCache = new PredicateIndicator(getFunctor(), 0); } return predicateIndicatorCache; } @Override public int hashCode() { if (value != null) return value.hashCode(); else return getFunctor().hashCode(); } */ @Override public Iterator<Unifier> logicalConsequence(Agent ag, Unifier un) { /*if (value != null && value instanceof LogicalFormula) return ((LogicalFormula)value).logicalConsequence(ag, un); else {*/ // try to apply Term t = this.capply(un); if ( t.equals(this) ) { // the variable is still a Var, find all bels that unify. return super.logicalConsequence(ag, un); } else { // the clone is still a var return ((LogicalFormula)t).logicalConsequence(ag, un); } //} } @Override public Term getTerm(int i) { /*if (value != null && value.isStructure()) { return ((Structure)getValue()).getTerm(i); } else {*/ return null; //} } @Override public void addTerm(Term t) { /*if (value != null) if (value.isStructure()) ((Structure)getValue()).addTerm(t); else*/ logger.log(Level.WARNING, "The addTerm '"+t+"' in "+this+" was lost, since I am a var.", new Exception()); } @Override public int getArity() { /*if (value != null && value.isStructure()) { return ((Structure)getValue()).getArity(); } else {*/ return 0; //} } @Override public List<Term> getTerms() { /*if (value != null && value.isStructure()) { return ((Structure)getValue()).getTerms(); } else {*/ return null; //} } @Override public Literal setTerms(List<Term> l) { /*if (value != null) { if (value.isStructure()) { return ((Structure)getValue()).setTerms(l); } else { logger.log(Level.WARNING, "The setTerms '"+l+"' in "+this+" was lost, since this var value is not a Structure. The value's class is "+getValue().getClass().getName(), new Exception()); return null; } } else {*/ return this; //} } @Override public void setTerm(int i, Term t) { /*if (value != null) if (value.isStructure()) ((Structure)getValue()).setTerm(i,t); else logger.log(Level.WARNING, "The setTerm '"+t+"' in "+this+" was lost, since this var value is not a Structure. The value's class is "+getValue().getClass().getName(), new Exception()); */ } @Override public Literal addTerms(List<Term> l) { /*if (value != null) if (value.isStructure()) return ((Structure)getValue()).addTerms(l); else logger.log(Level.WARNING, "The addTerms '"+l+"' in "+this+" was lost, since this var value is not a Structure. The value's class is "+getValue().getClass().getName(), new Exception()); */ return this; } /* @Override public Term[] getTermsArray() { if (value != null && value.isStructure()) { return ((Structure)getValue()).getTermsArray(); } else { return null; } } */ @Override public boolean isInternalAction() { return false; } @Override public boolean isList() { return false; } @Override public boolean isString() { return false; } @Override public boolean isPlanBody() { return false; } @Override public boolean isNumeric() { return false; } @Override public boolean isPred() { return false; } @Override public boolean isLiteral() { return false; } @Override public boolean isStructure() { return false; } @Override public boolean isAtom() { return false; } @Override public boolean isRule() { return false; } @Override public boolean isArithExpr() { return false; } @Override public boolean isCyclicTerm() { return false; } /* @Override public VarTerm getCyclicVar() { if (value != null) return value.getCyclicVar(); else return super.getCyclicVar(); } */ @Override public boolean hasVar(VarTerm t, Unifier u) { /*if (value != null) return value.hasVar(t, u);*/ if (equals(t)) return true; if (u != null) { // if the var has a value in the unifier, search in that value Term vl = u.get(this); if (vl != null) { try { u.remove(this); // remove this var from the unifier to avoid going to search inside it again return vl.hasVar(t, u); } finally { u.bind(this, vl); } } } return false; } @Override public void countVars(Map<VarTerm, Integer> c) { //if (value == null) { int n = c.containsKey(this) ? c.get(this) : 0; c.put(this, n+1); super.countVars(c); /*} else { value.countVars(c); }*/ } /* @Override public Literal makeVarsAnnon(Unifier un) { if (value == null) return super.makeVarsAnnon(un); else if (getValue() instanceof Literal) return ((Literal)getValue()).makeVarsAnnon(un); else return null; } */ @Override public String toString() { //if (value == null) { String s = getFunctor(); if (hasAnnot()) s += getAnnots(); if (negated()) s = "~" + s; return s; //} else { // return value.toString(); //} } // ---------- // Pred methods overridden // // in case this VarTerm has a value, use value's methods // ---------- /* @Override public Literal setAnnots(ListTerm l) { if (value != null) if (getValue().isPred()) return ((Pred) getValue()).setAnnots(l); else logger.log(Level.WARNING, "The setAnnots '"+l+"' in "+this+" was lost, since this var value is not a Pred. The value's class is "+getValue().getClass().getName(), new Exception()); else return super.setAnnots(l); return this; } @Override public boolean importAnnots(Literal p) { if (value != null) if (getValue().isPred()) { return ((Pred) getValue()).importAnnots(p); } else { logger.log(Level.WARNING, "The importAnnots '"+p+"' in "+this+" was lost, since this var value is not a Pred. The value's class is "+getValue().getClass().getName(), new Exception()); return false; } else return super.importAnnots(p); } @Override public boolean addAnnot(Term t) { if (value != null) if (getValue().isPred()) { return ((Pred) getValue()).addAnnot(t); } else { logger.log(Level.WARNING, "The add of annotation '"+t+"' in "+this+" was lost, since this var value is not a Pred. The value's class is "+getValue().getClass().getName(), new Exception()); return false; } else return super.addAnnot(t); } @Override public Literal addAnnots(List<Term> l) { if (value != null) if (getValue().isPred()) { return ((Pred) getValue()).addAnnots(l); } else { logger.log(Level.WARNING, "The addAnnots '"+l+"' in "+this+" was lost, since this var value is not a Pred. The value's class is "+getValue().getClass().getName(), new Exception()); return null; } else return super.addAnnots(l); } @Override public void clearAnnots() { if (value != null && getValue().isPred()) ((Pred) getValue()).clearAnnots(); else super.clearAnnots(); } @Override public boolean delAnnots(List<Term> l) { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).delAnnots(l); else return super.delAnnots(l); } @Override public boolean delAnnot(Term t) { if (value != null && getValue().isPred()) return ((Pred) getValue()).delAnnot(t); else return super.delAnnot(t); } @Override public boolean hasAnnot(Term t) { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).hasAnnot(t); else return super.hasAnnot(t); } @Override public boolean hasAnnot() { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).hasAnnot(); else return super.hasAnnot(); } @Override public boolean hasSubsetAnnot(Literal p) { if (value != null && value.isLiteral()) { return ((Literal)value).hasSubsetAnnot(p); } else { return super.hasSubsetAnnot(p); } } @Override public boolean hasSubsetAnnot(Literal p, Unifier u) { if (value != null && value.isLiteral()) { return ((Literal)value).hasSubsetAnnot(p, u); } else { return super.hasSubsetAnnot(p, u); } } @Override public ListTerm getAnnots() { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).getAnnots(); else return super.getAnnots(); } @Override public void addSource(Term t) { if (value != null) if (getValue().isPred()) ((Pred) getValue()).addSource(t); else logger.log(Level.WARNING, "The addSource '"+t+"' in "+this+" was lost, since this var value is not a Pred. The value's class is "+getValue().getClass().getName(), new Exception()); else super.addSource(t); } @Override public boolean delSource(Term s) { if (value != null && getValue().isPred()) return ((Pred) getValue()).delSource(s); else return super.delSource(s); } @Override public void delSources() { if (value != null && getValue().isPred()) ((Pred) getValue()).delSources(); else super.delSources(); } @Override public ListTerm getSources() { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).getSources(); else return super.getSources(); } @Override public boolean hasSource() { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).hasSource(); else return super.hasSource(); } @Override public boolean hasSource(Term s) { if (value != null && getValue().isLiteral()) return ((Literal) getValue()).hasSource(s); else return super.hasSource(s); } // ---------- // Literal methods overridden // // in case this VarTerm has a value, use value's methods // ---------- @Override public boolean negated() { if (value == null) return super.negated(); else return getValue().isLiteral() && ((Literal) getValue()).negated(); } */ @Override public boolean canBeAddedInBB() { //if (value != null && getValue().isLiteral()) // return ((Literal) getValue()).canBeAddedInBB(); //else return false; } /* @Override public Literal forceFullLiteralImpl() { if (hasValue() && getValue().isLiteral()) return ((Literal)getValue()).forceFullLiteralImpl(); else return super.forceFullLiteralImpl(); } */ // ---------- // ArithmeticExpression methods overridden // Interface NumberTerm // ---------- public double solve() throws NoValueException { throw new NoValueException(); /* if (value != null && value.isNumeric()) return ((NumberTerm) value).solve(); else if (hasValue()) logger.log(Level.SEVERE, getErrorMsg()+" Error getting numerical value of VarTerm " + super.getFunctor() + ", the variable value ("+value+") is not a number.", new Exception()); else logger.log(Level.SEVERE, getErrorMsg()+" Error getting numerical value of VarTerm " + super.getFunctor() + ", the variable hasn't a value.", new Exception()); return 0; */ } // ---------- // // ListTerm methods overridden // // ---------- public void add(int index, Term o) { //if (value != null && getValue().isList()) // ((ListTerm) getValue()).add(index, o); } public boolean add(Term o) { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).add(o); } public boolean addAll(@SuppressWarnings("rawtypes") Collection c) { return false; // value != null && getValue().isList() && ((ListTerm) getValue()).addAll(c); } public boolean addAll(int index, @SuppressWarnings("rawtypes") Collection c) { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).addAll(index, c); } public void clear() { //if (value != null && getValue().isList()) // ((ListTerm) getValue()).clear(); } public boolean contains(Object o) { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).contains(o); } public boolean containsAll(@SuppressWarnings("rawtypes") Collection c) { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).containsAll(c); } public Term get(int index) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).get(index); else*/ return null; } public int indexOf(Object o) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).indexOf(o); else*/ return -1; } public int lastIndexOf(Object o) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).lastIndexOf(o); else*/ return -1; } public Iterator<Term> iterator() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).iterator(); else*/ return null; } public ListIterator<Term> listIterator() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).listIterator(); else*/ return null; } public ListIterator<Term> listIterator(int index) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).listIterator(index); else*/ return null; } public Term remove(int index) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).remove(index); else*/ return null; } public boolean remove(Object o) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).remove(o); else*/ return false; } public boolean removeAll(@SuppressWarnings("rawtypes") Collection c) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).removeAll(c); else*/ return false; } public boolean retainAll(@SuppressWarnings("rawtypes") Collection c) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).retainAll(c); else*/ return false; } public Term set(int index, Term o) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).set(index, o); else*/ return null; } public List<Term> subList(int arg0, int arg1) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).subList(arg0, arg1); else*/ return null; } public Iterator<List<Term>> subSets(int k) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).subSets(k); else*/ return null; } public Object[] toArray() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).toArray(); else*/ return null; } @SuppressWarnings("unchecked") public Object[] toArray(Object[] arg0) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).toArray(arg0); else*/ return null; } // from ListTerm public void setTerm(Term t) { //if (value != null && getValue().isList()) // ((ListTerm) getValue()).setTerm(t); } public void setNext(Term t) { //if (value != null && getValue().isList()) // ((ListTerm) getValue()).setNext(t); } public ListTerm append(Term t) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).append(t); else*/ return null; } public ListTerm insert(Term t) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).insert(t); else*/ return null; } public ListTerm concat(ListTerm lt) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).concat(lt); else*/ return null; } public ListTerm reverse() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).reverse(); else*/ return null; } public ListTerm union(ListTerm lt) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).union(lt); else*/ return null; } public ListTerm intersection(ListTerm lt) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).intersection(lt); else*/ return null; } public ListTerm difference(ListTerm lt) { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).difference(lt); else*/ return null; } public List<Term> getAsList() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getAsList(); else*/ return null; } public ListTerm getLast() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getLast(); else*/ return null; } public ListTerm getPenultimate() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getPenultimate(); else*/ return null; } public Term removeLast() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).removeLast(); else*/ return null; } public ListTerm getNext() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getNext(); else*/ return null; } public Term getTerm() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getTerm(); else*/ return null; } public boolean isEmpty() { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).isEmpty(); } public boolean isEnd() { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).isEnd(); } public boolean isTail() { return false; //value != null && getValue().isList() && ((ListTerm) getValue()).isTail(); } public void setTail(VarTerm v) { //if (value != null && getValue().isList()) // ((ListTerm) getValue()).setTail(v); } public VarTerm getTail() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).getTail(); else*/ return null; } public Iterator<ListTerm> listTermIterator() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).listTermIterator(); else*/ return null; } public int size() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).size(); else*/ return -1; } public ListTerm cloneLTShallow() { /*if (value != null && getValue().isList()) return ((ListTerm) getValue()).cloneLTShallow(); else*/ return null; } // ----------------------- // StringTerm interface implementation // ----------------------- /* public String getString() { if (value != null && getValue().isString()) return ((StringTerm) getValue()).getString(); else return null; } public int length() { if (value != null && getValue().isString()) return ((StringTerm) getValue()).length(); else return -1; } */ // ----------------------- // ObjectTerm interface implementation // ----------------------- /* public Object getObject() { if (value != null && getValue() instanceof ObjectTerm) return ((ObjectTerm) getValue()).getObject(); else return null; } */ // ----------------------- // PlanBody interface implementation // ----------------------- /* public BodyType getBodyType() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).getBodyType(); else return BodyType.none; } public Term getBodyTerm() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).getBodyTerm(); else return null; } public PlanBody getBodyNext() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).getBodyNext(); else return null; } public PlanBody getLastBody() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).getLastBody(); else return null; } public boolean isEmptyBody() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).isEmptyBody(); else return true; } public int getPlanSize() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).getPlanSize(); else return 0; } public void setBodyType(BodyType bt) { if (value != null && getValue() instanceof PlanBody) ((PlanBody) getValue()).setBodyType(bt); } public void setBodyTerm(Term t) { if (value != null && getValue() instanceof PlanBody) ((PlanBody) getValue()).setBodyTerm(t); } public void setBodyNext(PlanBody bl) { if (value != null && getValue() instanceof PlanBody) ((PlanBody) getValue()).setBodyNext(bl); } public boolean isBodyTerm() { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).isBodyTerm(); else return false; } public void setAsBodyTerm(boolean b) { if (value != null && getValue() instanceof PlanBody) ((PlanBody) getValue()).setAsBodyTerm(b); } public boolean add(PlanBody bl) { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).add(bl); else return false; } public boolean add(int index, PlanBody bl) { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).add(index, bl); else return false; } public Term removeBody(int index) { if (value != null && getValue() instanceof PlanBody) return ((PlanBody) getValue()).removeBody(index); else return null; } */ /** get as XML */ public Element getAsDOM(Document document) { /*if (hasValue()) { return value.getAsDOM(document); } else {*/ Element u = (Element) document.createElement("var-term"); u.setAttribute("functor", getFunctor()); if (hasAnnot()) { Element ea = document.createElement("annotations"); ea.appendChild(getAnnots().getAsDOM(document)); u.appendChild(ea); } return u; //} } }
lsa-pucrs/jason-ros-releases
Jason-1.4.0a/src/jason/asSyntax/VarTerm.java
Java
bsd-3-clause
36,028
package org.twig4j.core.syntax.parser.node.type.expression; import org.junit.Assert; import org.junit.Test; import org.twig4j.core.Environment; import org.twig4j.core.compiler.ClassCompiler; import org.twig4j.core.exception.LoaderException; import org.twig4j.core.exception.Twig4jRuntimeException; import org.twig4j.core.syntax.parser.node.Node; public class BinaryEndsWithTests { @Test public void testCompile() throws LoaderException, Twig4jRuntimeException { ClassCompiler compiler = new ClassCompiler(new Environment()); Node left = new StringConstant("foobar", 1); Node right = new StringConstant("bar", 1); BinaryEndsWith endsWithNode = new BinaryEndsWith(left, right, 1); endsWithNode.compile(compiler); Assert.assertEquals( "Compiled source should check if string ends with", "(String.valueOf(\"foobar\").endsWith(String.valueOf(\"bar\")))", compiler.getSourceCode() ); } }
palmfjord/twig4j-core
src/test/java/org/twig4j/core/syntax/parser/node/type/expression/BinaryEndsWithTests.java
Java
bsd-3-clause
1,002
package com.oracle.ptsdemo.healthcare.business.datasync.schedule; import java.util.Date; /** */ public class Job { private String name; private Date startTime; private Date endTime; private String status; private short interval; private String intervalUnit; /** */ public static final String Pharmacy = "Pharmacy"; /** */ public static final String BIReport = "BIReport"; /** */ public Job() { super(); } /** * @param status */ public void setStatus(String status) { this.status = status; } /** * @return */ public String getStatus() { return status; } /** * @param name */ public void setName(String name) { this.name = name; } /** * @return */ public String getName() { return name; } /** * @param startTime */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * @return */ public Date getStartTime() { return startTime; } /** * @param endTime */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * @return */ public Date getEndTime() { return endTime; } /** * @param interval */ public void setInterval(short interval) { this.interval = interval; } /** * @return */ public short getInterval() { return interval; } /** * @param intervalUnit */ public void setIntervalUnit(String intervalUnit) { this.intervalUnit = intervalUnit; } /** * @return */ public String getIntervalUnit() { return intervalUnit; } }
dushmis/Oracle-Cloud
PaaS-SaaS_HealthCareApp/DoctorPatientCRMExtension/HealthCare/HealthCare/src/com/oracle/ptsdemo/healthcare/business/datasync/schedule/Job.java
Java
bsd-3-clause
1,810
package org.hisp.dhis.webapi.controller; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpStatus; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.translation.Translation; import org.hisp.dhis.translation.TranslationProperty; import org.hisp.dhis.webapi.DhisWebSpringTest; import org.hisp.dhis.webapi.documentation.common.TestUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpSession; import org.springframework.test.web.servlet.MvcResult; import java.util.Locale; import static junit.framework.TestCase.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * @author Viet Nguyen <[email protected]> */ public class TranslationWebApiTest extends DhisWebSpringTest { @Autowired private IdentifiableObjectManager identifiableObjectManager; @Test public void testOK() throws Exception { Locale locale = Locale.FRENCH; MockHttpSession session = getSession( "ALL" ); DataElement dataElementA = createDataElement( 'A' ); identifiableObjectManager.save( dataElementA ); String valueToCheck = "frenchTranslated"; dataElementA.getTranslations().add( new Translation( locale.getLanguage(), TranslationProperty.NAME, valueToCheck ) ); mvc.perform( put( "/dataElements/" + dataElementA.getUid() + "/translations" ) .session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) .content( TestUtils.convertObjectToJsonBytes( dataElementA ) ) ) .andExpect( status().is( HttpStatus.SC_NO_CONTENT ) ); MvcResult result = mvc.perform( get( "/dataElements/" + dataElementA.getUid() + "?locale=" + locale.getLanguage() ).session( session ) .contentType( TestUtils.APPLICATION_JSON_UTF8 ) ).andReturn(); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree( result.getResponse().getContentAsString() ); assertEquals( valueToCheck, node.get( "displayName" ).asText() ); } }
vietnguyen/dhis2-core
dhis-2/dhis-web/dhis-web-api-test/src/test/java/org/hisp/dhis/webapi/controller/TranslationWebApiTest.java
Java
bsd-3-clause
3,897
/** * Copyright 2015 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.partition; import java.lang.reflect.Field; import java.util.Arrays; import java.util.NavigableMap; import java.util.Scanner; import java.util.concurrent.Callable; import javax.annotation.CheckForNull; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.primitives.UnsignedBytes; import com.palantir.atlasdb.keyvalue.api.KeyValueService; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.partition.api.DynamicPartitionMap; import com.palantir.atlasdb.keyvalue.partition.endpoint.KeyValueEndpoint; import com.palantir.atlasdb.keyvalue.partition.endpoint.SimpleKeyValueEndpoint; import com.palantir.atlasdb.keyvalue.partition.exception.EndpointVersionTooOldException; import com.palantir.atlasdb.keyvalue.partition.map.DynamicPartitionMapImpl; import com.palantir.atlasdb.keyvalue.partition.map.PartitionMapService; import com.palantir.atlasdb.keyvalue.partition.quorum.QuorumParameters; import com.palantir.atlasdb.keyvalue.partition.status.EndpointWithStatus; import com.palantir.atlasdb.keyvalue.partition.util.CycleMap; import com.palantir.atlasdb.keyvalue.remoting.RemotingPartitionMapService; import com.palantir.common.base.Throwables; import com.palantir.common.concurrent.PTExecutors; public class DynamicPartitionMapManager { private DynamicPartitionMap partitionMap; public DynamicPartitionMapManager(String masterUri) { PartitionMapService masterPms = RemotingPartitionMapService.createClientSide(masterUri); partitionMap = masterPms.getMap(); } public DynamicPartitionMapManager(DynamicPartitionMap dpm) { partitionMap = dpm; } @CheckForNull private <T> T runRetryableTask(Callable<T> task, Scanner scanner) { while (true) { try { return task.call(); } catch (Exception e) { e.printStackTrace(System.out); if (e instanceof EndpointVersionTooOldException) { System.out.println("Pushing new map to endpoint..."); ((EndpointVersionTooOldException) e).pushNewMap(partitionMap); System.out.println("Pushed."); } System.out.print("Retry? (y/n) "); if (!scanner.nextLine().equals("y")) { System.out.println("Fatal? (y/n)"); if (!scanner.nextLine().equals("n")) { throw Throwables.throwUncheckedException(e); } break; } } } return null; } public void addEndpoint(String kvsUri, String pmsUri, final byte[] key, String rack, Scanner scanner) { final SimpleKeyValueEndpoint skve = SimpleKeyValueEndpoint.create(kvsUri, pmsUri, rack); runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Adding..."); boolean added = partitionMap.addEndpoint(key, skve); Preconditions.checkState(added); return null; } }, scanner); pushMapToEndpointsNonCritical(); runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Backfilling..."); partitionMap.backfillAddedEndpoint(key); return null; } }, scanner); pushMapToEndpointsNonCritical(); runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Promoting..."); partitionMap.promoteAddedEndpoint(key); return null; } }, scanner); pushMapToEndpointsNonCritical(); } public void removeEndpoint(final byte[] key, Scanner scanner) { runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Removing..."); boolean removed = partitionMap.removeEndpoint(key); Preconditions.checkState(removed); return null; } }, scanner); pushMapToEndpointsNonCritical(); runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Backfilling..."); partitionMap.backfillRemovedEndpoint(key); return null; } }, scanner); pushMapToEndpointsNonCritical(); runRetryableTask(new Callable<Void>() { @Override public Void call() throws Exception { System.out.println("Promoting..."); partitionMap.promoteRemovedEndpoint(key); return null; } }, scanner); pushMapToEndpointsNonCritical(); } private void pushMapToEndpointsNonCritical() { try { partitionMap.pushMapToEndpoints(); } catch (RuntimeException e) { System.out.println("Non-critical error encountered while pushing map to endpoints:"); e.printStackTrace(System.out); } } public void updateLocalMap(String pmsUri) { partitionMap = RemotingPartitionMapService.createClientSide(pmsUri).getMap(); } public void addEndpointInteractive(Scanner scanner) { System.out.println("Adding endpoint"); byte[] key = readKey(scanner); System.out.print("Enter key value service URI: "); String kvsUri = scanner.nextLine(); System.out.print("Enter partition map service URI: "); String pmsUri = scanner.nextLine(); System.out.print("Enter rack name: "); String rack = scanner.nextLine(); System.out.println("Adding " + SimpleKeyValueEndpoint.create(kvsUri, pmsUri, rack) + " at key " + Arrays.toString(key)); System.out.print("y/n? "); if (!scanner.nextLine().equals("y")) { System.out.println("Aborting."); return; } addEndpoint(kvsUri, pmsUri, key, rack, scanner); } public void removeEndpointInteractive(Scanner scanner) { System.out.println("Removing endpoint"); byte[] key = readKey(scanner); System.out.println("Removing endpoint at " + Arrays.toString(key)); System.out.println("y/n?"); if (!scanner.nextLine().equals("y")) { System.out.println("Aborting."); return; } removeEndpoint(key, scanner); } private static byte[] readKey(Scanner scanner) { System.out.print("Key length: "); int keyLen = Integer.parseInt(scanner.nextLine()); byte[] key = new byte[keyLen]; for (int i=0; i<keyLen; ++i) { System.out.println("Enter unsigned byte no. " + i); int intByte = Integer.parseInt(scanner.nextLine()); if (intByte < 0 || intByte > 255) { throw new NumberFormatException("Invalid range for unsigned byte!"); } key[i] = (byte) intByte; } return key; } public void updateLocalMapInteractive(Scanner scanner) { System.out.println("Updating local map"); System.out.println("Enter PMS Uri to download new map: "); String pmsUri = scanner.nextLine(); updateLocalMap(pmsUri); } public void setVersionInteractive(Scanner scanner) { Preconditions.checkState(partitionMap instanceof DynamicPartitionMapImpl); System.out.println("Setting partition map version"); System.out.println("Current version: " + partitionMap.getVersion()); System.out.print("New version: "); long newVersion = Long.parseLong(scanner.nextLine()); ((DynamicPartitionMapImpl) partitionMap).setVersion(newVersion); pushMapToEndpointsNonCritical(); } public void pushToUriInteractive(Scanner scanner) { System.out.println("Pushing local map to URI"); System.out.print("Enter PMS URI: "); String pmsUri = scanner.nextLine(); pushMapToUri(pmsUri); } public void pushMapToUri(String pmsUri) { RemotingPartitionMapService.createClientSide(pmsUri).updateMap(partitionMap); } public static void main(String[] args) { System.out.println("AtlasDb Dynamic Partition Map Manager"); System.out.print("Enter PMS Uri to download initial map (empty for empty map): "); final DynamicPartitionMapManager instance; try (Scanner scanner = new Scanner(System.in)) { String initialPmsUri = scanner.nextLine(); if (!initialPmsUri.equals("")) { instance = new DynamicPartitionMapManager(initialPmsUri); } else { System.out.println("This is new partition map wizard"); System.out.print("replication factor: "); int repf = Integer.parseInt(scanner.nextLine()); System.out.print("read factor: "); int readf = Integer.parseInt(scanner.nextLine()); System.out.print("write factor: "); int writef = Integer.parseInt(scanner.nextLine()); QuorumParameters parameters = new QuorumParameters(repf, readf, writef); NavigableMap<byte[], KeyValueEndpoint> initialRing = Maps.newTreeMap(UnsignedBytes.lexicographicalComparator()); while (initialRing.size() < repf) { System.out.print("kvs URI: "); String kvsUri = scanner.nextLine(); System.out.print("pms URI: "); String pmsUri = scanner.nextLine(); System.out.print("rack: "); String rack = scanner.nextLine(); byte[] key = readKey(scanner); SimpleKeyValueEndpoint kve = SimpleKeyValueEndpoint.create(kvsUri, pmsUri, rack); initialRing.put(key, kve); } DynamicPartitionMapImpl dpmi = DynamicPartitionMapImpl.create(parameters, initialRing, PTExecutors.newCachedThreadPool()); instance = new DynamicPartitionMapManager(dpmi); } boolean exit = false; while (!exit) { System.out.println("Local partition map:"); System.out.println(instance.partitionMap); System.out.println("MAIN MENU"); System.out.println("1. Add endpoint"); System.out.println("2. Remove endpoint"); System.out.println("3. Update local map"); System.out.println("4. Set version (deprecated, test only)"); System.out.println("5. Push local map to Uri"); System.out.println("6. Clear all endpoint kvss"); System.out.println("0. Exit"); System.out.print("Choice: "); try { switch (Integer.parseInt(scanner.nextLine())) { case 1: instance.addEndpointInteractive(scanner); continue; case 2: instance.removeEndpointInteractive(scanner); continue; case 3: instance.updateLocalMapInteractive(scanner); continue; case 4: instance.setVersionInteractive(scanner); continue; case 5: instance.pushToUriInteractive(scanner); continue; case 6: instance.clearAllEndpointKvssInteractive(scanner); continue; case 0: exit = true; continue; } } catch (NumberFormatException e) { e.printStackTrace(System.out); continue; } catch (RuntimeException e) { System.out.println("ERROR DURING OPERATION"); e.printStackTrace(System.out); System.out.println("\n\nReturning to main menu\n\n"); continue; } System.out.println("Unrecognized command."); } } } private void clearAllEndpointKvssInteractive(Scanner scanner) { try { Field f = partitionMap.getClass().getDeclaredField("ring"); f.setAccessible(true); @SuppressWarnings("unchecked") CycleMap<?, EndpointWithStatus> ring = (CycleMap<?, EndpointWithStatus>) f.get(partitionMap); f.setAccessible(false); System.err.println("Ring=" + ring); for (EndpointWithStatus ews : ring.values()) { KeyValueService kvs = ews.get().keyValueService(); for (TableReference tableRef : kvs.getAllTableNames()) { System.err.println("Dropping table " + tableRef.getQualifiedName() + " from " + kvs); kvs.dropTable(tableRef); } } } catch (Exception e) { throw Throwables.throwUncheckedException(e); } } }
sh4nth/atlasdb-1
atlasdb-partition-manager/src/main/java/com/palantir/atlasdb/keyvalue/partition/DynamicPartitionMapManager.java
Java
bsd-3-clause
14,191
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.flump; import java.util.Collections; import java.util.List; public class LayerData { /** The authored name of this layer. */ public final String name; /** The keyframes in this layer. */ public final List<KeyframeData> keyframes; public LayerData (String name, List<KeyframeData> keyframes) { this.name = name; this.keyframes = Collections.unmodifiableList(keyframes); } /** The number of frames in this layer. */ public int frames () { KeyframeData lastKf = keyframes.get(keyframes.size() - 1); return lastKf.index + lastKf.duration; } // these are filled in by Library after the library is loaded protected boolean _multipleSymbols; protected Symbol _lastSymbol; }
joansmith/tripleplay
core/src/main/java/tripleplay/flump/LayerData.java
Java
bsd-3-clause
971
package com.tinkerpop.pipes.util.structures; import junit.framework.TestCase; import java.util.Arrays; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class TreeTest extends TestCase { public void testBasicTree() { Tree<String> tree = new Tree<String>(); tree.put("marko", new Tree<String>(Tree.createTree("a", new Tree<String>("a1", "a2")), Tree.createTree("b", new Tree<String>("b1", "b2", "b3")))); tree.put("josh", new Tree<String>("1", "2")); assertEquals(tree.getObjectsAtDepth(0).size(), 0); assertEquals(tree.getObjectsAtDepth(1).size(), 2); assertEquals(tree.getObjectsAtDepth(2).size(), 4); assertEquals(tree.getObjectsAtDepth(3).size(), 5); assertEquals(tree.getObjectsAtDepth(4).size(), 0); assertEquals(tree.getObjectsAtDepth(5).size(), 0); assertEquals(tree.get("josh").size(), 2); assertEquals(tree.get("marko").get("b").get("b1").size(), 0); assertEquals(tree.get("marko").get("b").size(), 3); assertNull(tree.get("marko").get("c")); } public void testTreeLeaves() { Tree<String> tree = new Tree<String>(); tree.put("marko", new Tree<String>(Tree.createTree("a", new Tree<String>("a1", "a2")), Tree.createTree("b", new Tree<String>("b1", "b2", "b3")))); tree.put("josh", new Tree<String>("1", "2")); assertEquals(tree.getLeafTrees().size(), 7); for (Tree<String> t : tree.getLeafTrees()) { assertEquals(t.keySet().size(), 1); final String key = t.keySet().iterator().next(); assertTrue(Arrays.asList("a1", "a2", "b1", "b2", "b3", "1", "2").contains(key)); } //System.out.println(tree.getLeafObjects()); assertEquals(tree.getLeafObjects().size(), 7); for (String s : tree.getLeafObjects()) { assertTrue(Arrays.asList("a1", "a2", "b1", "b2", "b3", "1", "2").contains(s)); } } }
whshev/pipes
src/test/java/com/tinkerpop/pipes/util/structures/TreeTest.java
Java
bsd-3-clause
1,974
/** * Copyright (c) 2012, The National Archives <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the The National Archives nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.droid.gui.filter; import java.awt.Component; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowEvent; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.xml.bind.JAXBException; import uk.gov.nationalarchives.droid.core.interfaces.filter.CriterionFieldEnum; import uk.gov.nationalarchives.droid.core.interfaces.filter.CriterionOperator; import uk.gov.nationalarchives.droid.gui.DroidUIContext; import uk.gov.nationalarchives.droid.gui.ProfileForm; import uk.gov.nationalarchives.droid.gui.action.ApplyFilterToTreeTableAction; import uk.gov.nationalarchives.droid.gui.filter.action.InitialiseFilterAction; import uk.gov.nationalarchives.droid.gui.filter.action.LoadFilterAction; import uk.gov.nationalarchives.droid.gui.filter.domain.DummyMetadata; import uk.gov.nationalarchives.droid.gui.filter.domain.FilterDomain; import uk.gov.nationalarchives.droid.gui.filter.domain.FilterValidationException; import uk.gov.nationalarchives.droid.gui.filter.domain.GenericMetadata; import uk.gov.nationalarchives.droid.gui.filter.domain.LastModifiedDateMetadata; import uk.gov.nationalarchives.droid.gui.filter.domain.ExtensionMismatchMetadata; import uk.gov.nationalarchives.droid.profile.FilterCriterionImpl; import uk.gov.nationalarchives.droid.profile.FilterImpl; import uk.gov.nationalarchives.droid.profile.FilterSpecDao; import uk.gov.nationalarchives.droid.profile.JaxbFilterSpecDao; import uk.gov.nationalarchives.droid.profile.ProfileManager; /** * @author Alok Kumar Dash. */ public class FilterDialog extends JDialog { /** */ private static final int ROW_HEIGHT = 23; /** */ private static final String REMOVE = "Remove"; private static final int COL_0_WIDTH = 150; private static final int COL_1_WIDTH = 150; private static final int COL_3_WIDTH = 90; private static final int COL_2_WIDTH = 375; private static final int COL_0 = 0; private static final int COL_1 = 1; private static final int COL_2 = 2; private static final int COL_3 = 3; private static final long serialVersionUID = 5181319919824269596L; private DefaultTableModel tableModel = new DefaultTableModel(); // FilterDomain is used to load Filter condition in filter dialog and // associated logic behind it. private FilterDomain filterDomain = new FilterDomain(); // Filter Context is used to store user selected values in filter and later // used to persist in an xml in local disk. // FilterContext filterContext = new FilterContext(); private FilterImpl filterContext; // temporary filter context is used to store previous state of FIlter // conditions before user stared to amend. // and it is used to assign to changed filterContext if user decide not to // apply changes. private FilterImpl tempFilterContext; private DroidUIContext droidContext; private ProfileManager profileManager; private JComboBox metaDataCombobox; private JComboBox operationCombobox; private DefaultComboBoxModel operationComboboxModel; private boolean filterPredicatesLoading; private JFileChooser filterFileChooser; /** * Creates new form FilterDialog. CLones Filter context. * * @param parent * Parent dialog. * @param modal * If we want filter dialog to be not modal. * @param filterContext * Filter Context * @param droidContext * Droid Context. * @param profileManager * Profile Manager. * @param filterFileChooser - the file chooser to load or save filters. */ public FilterDialog(Frame parent, boolean modal, FilterImpl filterContext, DroidUIContext droidContext, ProfileManager profileManager, JFileChooser filterFileChooser) { super(parent, modal); this.filterContext = filterContext; this.droidContext = droidContext; this.profileManager = profileManager; this.filterFileChooser = filterFileChooser; intialiseFilter(); initComponents(); myInitComponents(); tempFilterContext = (FilterImpl) filterContext.clone(); loadFilter(); setLocationRelativeTo(parent); } /** * * @return the filter */ public FilterDomain getFilter() { return filterDomain; } /** * * @param filter * the filter to set */ public void setFilter(FilterDomain filter) { this.filterDomain = filter; } /** * * @return the filter context */ public FilterImpl getFilterContext() { return filterContext; } private void loadFilter() { if (isFilterPrevioudlyLoaded()) { filterPredicatesLoading = true; filterEnabledCheckbox.setSelected(filterContext.isEnabled()); setFilterMode(); LoadFilterAction loadFilterAction = new LoadFilterAction(); loadFilterAction.loadFilter(this); filterPredicatesLoading = false; } } /** * */ private void setFilterMode() { if (filterContext.isNarrowed()) { narrowResultRadioButton.setSelected(true); } else { widenResultsRadioButton.setSelected(true); } } private boolean isFilterPrevioudlyLoaded() { return filterContext.hasCriteria(); } private void intialiseFilter() { String profileId = droidContext.getSelectedProfile().getProfile().getUuid(); InitialiseFilterAction initialiseFilterAction = new InitialiseFilterAction(); initialiseFilterAction.initialiseFilter(profileId, profileManager, filterDomain); } /** * @return Object[] Object Array for the entire row in the filter table. */ public Object[] getRowForTable() { Component component = new TextBoxAndButton(this); component.hide(); // get all the meta data and load the combo metaDataCombobox = new JComboBox(filterDomain.getMetaDataNames()); metaDataCombobox.setRenderer(new BasicComboBoxRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final String displayText = value == null ? "<Please select...>" : value.toString(); return super.getListCellRendererComponent(list, displayText, index, isSelected, cellHasFocus); } }); operationCombobox = new JComboBox(); operationComboboxModel = new DefaultComboBoxModel(); operationCombobox.setModel(operationComboboxModel); metaDataCombobox.addItemListener(new MetaDataComboItemListner()); operationCombobox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED && !filterPredicatesLoading) { // set the corresponding value at filter context. FilterCriterionImpl filterCriterion = filterContext.getFilterCriterion(filterTable.getSelectedRow()); JComboBox sourceCombo = (JComboBox) e.getSource(); filterCriterion.setOperator((CriterionOperator) sourceCombo.getSelectedItem()); } } }); // Remove button and its listner. JButton jButton2 = new JButton(REMOVE); // CHECKSTYLE:OFF FIXME - inner class is too long jButton2.addActionListener(new ActionListener() { // CHECKSTYLE:ON @Override public void actionPerformed(ActionEvent e) { if (tableModel.getRowCount() > 1 && (filterTable.getSelectedRow() + 1) != tableModel.getRowCount()) { int size = filterContext.getNumberOfFilterCriterion(); filterContext.removeFilterCriterion(filterTable.getSelectedRow()); // fill the empty criteria which is been removed. for (int k = filterTable.getSelectedRow() + 1; k < size; k++) { filterContext.getFilterCriteriaMap().put(k - 1, filterContext.getFilterCriteriaMap().get(k)); } // remove the last one filterContext.removeFilterCriterion(size - 1); tableModel.removeRow(filterTable.getSelectedRow()); tableModel.fireTableRowsDeleted(filterTable.getSelectedRow(), filterTable.getSelectedRow()); filterTable.revalidate(); initColumnSizes(filterTable); } } }); Object[] data = {metaDataCombobox, operationCombobox, component, jButton2 }; metaDataCombobox.setMaximumRowCount(filterDomain.getMetaDataNames().length); return data; } // CHECKSTYLE:OFF FIXME - anonymous class is way too long private class MetaDataComboItemListner implements ItemListener { @SuppressWarnings("deprecation") @Override // CHECKSTYLE:ON public void itemStateChanged(ItemEvent e) { if (!filterPredicatesLoading) { CriterionFieldEnum deSelectedItem = null; if (e.getStateChange() == e.DESELECTED) { deSelectedItem = (CriterionFieldEnum) e.getItem(); } Component comp = null; int selectedRow = filterTable.getSelectedRow(); // Get the source combo, and corresponding option combo and // textbox and button references. JComboBox sourceCombo = (JComboBox) e.getSource(); // find what is selected. CriterionFieldEnum selectedItem = (CriterionFieldEnum) sourceCombo.getSelectedItem(); if (selectedItem != null) { // get Metadata Object from the selected string. GenericMetadata metadata = filterDomain.getMetaDataFromFieldType(selectedItem); if (metadata instanceof LastModifiedDateMetadata) { comp = new DatePicker(); } else if (metadata instanceof ExtensionMismatchMetadata) { comp = new JComboBox(); } else { comp = new TextBoxAndButton(FilterDialog.this); } tableModel.setValueAt(comp, filterTable.getSelectedRow(), 2); if (e.getStateChange() == ItemEvent.SELECTED) { // Add a new row if metadata is selected at last // row. if (tableModel.getRowCount() == selectedRow + 1) { tableModel.addRow(getRowForTable()); filterTable.revalidate(); } JComboBox comboBox = (JComboBox) tableModel.getValueAt(selectedRow, 1); operationComboboxModel = (DefaultComboBoxModel) comboBox.getModel(); // If filter criteria is not there that means fresh // criteria for selected row and create one FilterCriterionImpl newCriteria = new FilterCriterionImpl(); newCriteria.setRowNumber(filterTable.getSelectedRow()); newCriteria.setField(metadata.getField()); filterContext.addFilterCiterion(newCriteria, filterTable.getSelectedRow()); // Apply metadaUi logic. applyMetadaUILogic(comp, metadata); //Add the possible criteria e.g. all, any equal to... operationComboboxModel.removeAllElements(); for (CriterionOperator metaDataOp : metadata.getOperationList()) { operationComboboxModel.addElement(metaDataOp); } if (comp instanceof TextBoxAndButton) { ((TextBoxAndButton) comp).setType(metadata, filterContext.getFilterCriterion(filterTable .getSelectedRow())); } //BNO: For extension_mismatch if (comp instanceof JComboBox) { JComboBox combo = (JComboBox) comp; combo.addItem("true"); combo.addItem("false"); } filterTable.repaint(); } } else { GenericMetadata metadata = getFilterDomain().getMetaDataFromFieldType(deSelectedItem); sourceCombo.getModel().setSelectedItem(metadata.getField()); } } } /** * @param comp * @param metadata */ @SuppressWarnings("deprecation") private void applyMetadaUILogic(Component comp, GenericMetadata metadata) { if (metadata.isFreeText()) { if (comp instanceof TextBoxAndButton) { ((TextBoxAndButton) comp).getButton().hide(); ((TextBoxAndButton) comp).getTextField().show(); } } else { //BNO need to check as we have a combo box for Extension Mismatch so can't assume // comp will always be TextAndButton if (comp instanceof TextBoxAndButton) { ((TextBoxAndButton) comp).getTextField().disable(); } comp.show(); } if (metadata instanceof DummyMetadata) { comp.hide(); } } } private void myInitComponents() { filterTable = new FilterTable(); filterTable.setRowHeight(ROW_HEIGHT); filterTable.setDefaultRenderer(JComponent.class, new JComponentCellRenderer()); filterTable.setDefaultEditor(JComponent.class, new JComponentCellEditor()); filterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tableModel.addColumn("Field"); tableModel.addColumn("Operation"); tableModel.addColumn("Values"); tableModel.addColumn(REMOVE); tableModel.insertRow(0, getRowForTable()); filterTable.setModel(tableModel); initColumnSizes(filterTable); jScrollPane1.setViewportView(filterTable); buttonGroup1.add(widenResultsRadioButton); buttonGroup1.add(narrowResultRadioButton); narrowResultRadioButton.setSelected(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" // <editor-fold defaultstate="collapsed" // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); widenResultsRadioButton = new javax.swing.JRadioButton(); narrowResultRadioButton = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); filterEnabledCheckbox = new javax.swing.JCheckBox(); jPanel1 = new javax.swing.JPanel(); jButtonCancle = new javax.swing.JButton(); jButtonApply = new javax.swing.JButton(); LoadFilterButton = new javax.swing.JButton(); SaveFilterButton = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); filterTable = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.title")); // NOI18N widenResultsRadioButton.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.widenResultsRadioButton.text")); // NOI18N narrowResultRadioButton.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.narrowResultRadioButton.text")); // NOI18N javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(narrowResultRadioButton) .addGap(18, 18, 18) .addComponent(widenResultsRadioButton) .addContainerGap(77, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(narrowResultRadioButton) .addComponent(widenResultsRadioButton))) ); filterEnabledCheckbox.setSelected(true); filterEnabledCheckbox.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.filterEnabledCheckbox.text")); // NOI18N filterEnabledCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { filterEnabledCheckboxActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(filterEnabledCheckbox) .addContainerGap(266, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(filterEnabledCheckbox)) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(108, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jButtonCancle.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jButtonCancle.text")); // NOI18N jButtonCancle.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancleActionPerformed(evt); } }); jButtonApply.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jButtonApply.text")); // NOI18N jButtonApply.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonApplyActionPerformed(evt); } }); LoadFilterButton.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.LoadFilterButton.text")); // NOI18N LoadFilterButton.setToolTipText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.LoadFilterButton.toolTipText")); // NOI18N LoadFilterButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadFilterButtonActionPerformed(evt); } }); SaveFilterButton.setText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.SaveFilterButton.text")); // NOI18N SaveFilterButton.setToolTipText(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.SaveFilterButton.toolTipText")); // NOI18N SaveFilterButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveFilterButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(LoadFilterButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(SaveFilterButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 228, Short.MAX_VALUE) .addComponent(jButtonApply, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonCancle, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButtonApply, jButtonCancle}); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(LoadFilterButton) .addComponent(SaveFilterButton) .addComponent(jButtonCancle) .addComponent(jButtonApply)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButtonApply, jButtonCancle}); filterTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(filterTable); filterTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jTable1.columnModel.title0")); // NOI18N filterTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jTable1.columnModel.title1")); // NOI18N filterTable.getColumnModel().getColumn(2).setHeaderValue(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jTable1.columnModel.title2")); // NOI18N filterTable.getColumnModel().getColumn(3).setHeaderValue(org.openide.util.NbBundle.getMessage(FilterDialog.class, "FilterDialog.jTable1.columnModel.title3")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 656, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void LoadFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadFilterButtonActionPerformed int result = filterFileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { //FIXME: should wire this up using spring, rather than hard coding references to // particular objects here. try { FilterSpecDao reader = new JaxbFilterSpecDao(); FileInputStream in = new FileInputStream(filterFileChooser.getSelectedFile()); filterContext = reader.loadFilter(in); in.close(); loadFilter(); } catch (JAXBException e) { JOptionPane.showMessageDialog(this, "There was a problem loading the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "There was a problem loading the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(this, "There was a problem loading the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_LoadFilterButtonActionPerformed private void SaveFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveFilterButtonActionPerformed if (applyValuesToContext()) { int result = filterFileChooser.showSaveDialog(this); if (result == JFileChooser.APPROVE_OPTION) { FileOutputStream out; try { out = new FileOutputStream(filterFileChooser.getSelectedFile()); FilterSpecDao writer = new JaxbFilterSpecDao(); writer.saveFilter(filterContext, out); out.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(this, "There was a problem saving the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } catch (JAXBException e) { JOptionPane.showMessageDialog(this, "There was a problem saving the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(this, "There was a problem saving the filter.", "Filter warning", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_SaveFilterButtonActionPerformed private void filterEnabledCheckboxActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_filterEnabledCheckboxActionPerformed // TODO add your handling code here: }// GEN-LAST:event_filterEnabledCheckboxActionPerformed private void jButtonCancleActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonCancleActionPerformed // filterContext = tempFilterContext ; droidContext.getSelectedProfile().getProfile().setFilter(tempFilterContext); this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }// GEN-LAST:event_jButtonCancleActionPerformed private void jButtonApplyActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonApplyActionPerformed filterContext.setEnabled(filterEnabledCheckbox.isSelected()); filterContext.setNarrowed(narrowResultRadioButton.isSelected()); //FilterImpl filter = droidContext.getSelectedProfile().getProfile().getFilter(); droidContext.getSelectedProfile().getProfile().setFilter(filterContext); if (applyValuesToContext()) { getDroidContext().getSelectedProfile().getProfile().setDirty(true); ProfileForm profileToFilter = getDroidContext().getSelectedProfile(); ApplyFilterToTreeTableAction applyFilterToTreeAction = new ApplyFilterToTreeTableAction(profileToFilter, getProfileManager()); applyFilterToTreeAction.applyFilter(); dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } //ApplyFilterAction applyFilterAction = new ApplyFilterAction(); //applyFilterAction.applyFilter(this); }// GEN-LAST:event_jButtonApplyActionPerformed /** * Attempts to apply the values in the dialog to the filter. * @return Whether the attempt was successful or not. */ private boolean applyValuesToContext() { DefaultTableModel tModel = (DefaultTableModel) getFilterTable().getModel(); List<String> errorStrings = new ArrayList<String>(); // Iterate through the table and set all the free text. // do not anything for the last row. for (int i = 0; i < tModel.getRowCount() - 1; i++) { // get the first combobox selected item. final JComboBox comboBox1 = (JComboBox) tModel.getValueAt(i, 0); CriterionFieldEnum firstComboBoxSelectedItem = (CriterionFieldEnum) comboBox1.getSelectedItem(); // get the Component . Component componentAtThirdRow = (Component) tModel.getValueAt( i, 2); String freeTextAtRow = null; try { if (componentAtThirdRow instanceof TextBoxAndButton) { freeTextAtRow = ((TextBoxAndButton) componentAtThirdRow) .getTextField().getText(); } else if (componentAtThirdRow instanceof DatePicker) { freeTextAtRow = ((DatePicker) componentAtThirdRow) .getDateString(); } else if (componentAtThirdRow instanceof JComboBox) { freeTextAtRow = ((JComboBox) componentAtThirdRow).getSelectedItem().toString(); } else { throw new RuntimeException("Fatal error"); } // get meta data object from the selected string. GenericMetadata metadata = getFilterDomain() .getMetaDataFromFieldType(firstComboBoxSelectedItem); // Validate the values. metadata.validate(freeTextAtRow); } catch (FilterValidationException filterValidationException) { errorStrings.add(filterValidationException.getMessage()); } FilterCriterionImpl filterCriteria = getFilterContext().getFilterCriterion(i); filterCriteria.setValueFreeText(freeTextAtRow); } if (errorStrings.size() > 0) { JOptionPane.showMessageDialog(this, errorStrings.toArray()); return false; } return true; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton LoadFilterButton; private javax.swing.JButton SaveFilterButton; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JCheckBox filterEnabledCheckbox; private javax.swing.JTable filterTable; private javax.swing.JButton jButtonApply; private javax.swing.JButton jButtonCancle; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JRadioButton narrowResultRadioButton; private javax.swing.JRadioButton widenResultsRadioButton; // End of variables declaration//GEN-END:variables private void initColumnSizes(JTable table) { // Disable auto resizing // table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Set the first visible column to 100 pixels wide TableColumn col = table.getColumnModel().getColumn(COL_0); col.setPreferredWidth(COL_0_WIDTH); col = table.getColumnModel().getColumn(COL_1); col.setPreferredWidth(COL_1_WIDTH); col = table.getColumnModel().getColumn(COL_2); col.setPreferredWidth(COL_2_WIDTH); col = table.getColumnModel().getColumn(COL_3); col.setPreferredWidth(COL_3_WIDTH); } /** * @return the filterDomain */ public FilterDomain getFilterDomain() { return filterDomain; } /** * @return the droidContext */ public DroidUIContext getDroidContext() { return droidContext; } /** * @return the jTable1 */ public javax.swing.JTable getFilterTable() { return filterTable; } /** * @return the profileManager */ public ProfileManager getProfileManager() { return profileManager; } }
seamang/droid
droid-swing-ui/src/main/java/uk/gov/nationalarchives/droid/gui/filter/FilterDialog.java
Java
bsd-3-clause
38,789
/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.keyframes.model.keyframedmodels; import java.util.List; import com.facebook.keyframes.model.KFAnimation; import com.facebook.keyframes.model.KFAnimation.PropertyType; import com.facebook.keyframes.model.KFAnimationFrame; /** * This is a special cased KFAnimation, since it is the only animation which is not applied * via a matrix. The information for this Modifiable is packed into a single length array. * A {@link KeyFramedObject} which houses information about a stroke width animation. This includes * float values for stroke width at any given key frame. This is a post-process object used for * KFAnimation. */ public class KeyFramedOpacity extends KeyFramedObject<KFAnimationFrame, KeyFramedOpacity.Opacity> { /** * A container object so that this class can set values on an object which on a common reference. */ public static class Opacity { private float mOpacity = 100; public float getOpacity() { return mOpacity; } public void setOpacity(float opacity) { mOpacity = opacity; } } /** * Constructs a KeyFramedOpacity from a {@link KFAnimation}. */ public static KeyFramedOpacity fromAnimation(KFAnimation animation) { if (animation.getPropertyType() != KFAnimation.PropertyType.OPACITY) { throw new IllegalArgumentException( "Cannot create a KeyFramedOpacity object from a non OPACITY animation."); } return new KeyFramedOpacity(animation.getAnimationFrames(), animation.getTimingCurves()); } public KeyFramedOpacity( List<KFAnimationFrame> objects, float[][][] timingCurves) { super(objects, timingCurves); } private KeyFramedOpacity() { super(); } /** * Applies the current state, given by interpolationValue, to the Opacity object. * @param stateA Initial state * @param stateB End state * @param interpolationValue Progress [0..1] between stateA and stateB * @param modifiable The Opacity to apply the values to */ @Override protected void applyImpl( KFAnimationFrame stateA, KFAnimationFrame stateB, float interpolationValue, Opacity modifiable) { if (stateB == null) { modifiable.setOpacity(stateA.getData()[0]); return; } modifiable.setOpacity( interpolateValue(stateA.getData()[0], stateB.getData()[0], interpolationValue)); } }
marmelroy/Keyframes
android/keyframes/src/main/java/com/facebook/keyframes/model/keyframedmodels/KeyFramedOpacity.java
Java
bsd-3-clause
2,697
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde licenses this file to you under the Modified BSD License // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/BSD-3-Clause */ package sqlline; import java.sql.ResultSet; import java.sql.SQLException; import java.util.NoSuchElementException; /** * Rows implementation which returns rows incrementally from result set * without any buffering. */ class IncrementalRows extends Rows { private final ResultSet rs; private final Row labelRow; private final Row maxRow; private Row nextRow; private boolean endOfResult; private boolean normalizingWidths; private DispatchCallback dispatchCallback; IncrementalRows(SqlLine sqlLine, ResultSet rs, DispatchCallback dispatchCallback) throws SQLException { super(sqlLine, rs); this.rs = rs; this.dispatchCallback = dispatchCallback; labelRow = new Row(rsMeta.getColumnCount()); maxRow = new Row(rsMeta.getColumnCount()); // pre-compute normalization so we don't have to deal // with SQLExceptions later for (int i = 0; i < maxRow.sizes.length; ++i) { // normalized display width is based on maximum of display size // and label size maxRow.sizes[i] = Math.max( maxRow.sizes[i], rsMeta.getColumnDisplaySize(i + 1)); } nextRow = labelRow; endOfResult = false; } public boolean hasNext() { if (endOfResult || dispatchCallback.isCanceled()) { return false; } if (nextRow == null) { try { if (rs.next()) { nextRow = new Row(labelRow.sizes.length, rs); if (normalizingWidths) { // perform incremental normalization nextRow.sizes = labelRow.sizes; } } else { endOfResult = true; } } catch (SQLException ex) { throw new RuntimeException(ex.toString()); } } return nextRow != null; } public Row next() { if (!hasNext() && !dispatchCallback.isCanceled()) { throw new NoSuchElementException(); } Row ret = nextRow; nextRow = null; return ret; } void normalizeWidths() { // normalize label row labelRow.sizes = maxRow.sizes; // and remind ourselves to perform incremental normalization // for each row as it is produced normalizingWidths = true; } } // End IncrementalRows.java
nvoron23/sqlline
src/main/java/sqlline/IncrementalRows.java
Java
bsd-3-clause
2,666
/*L * Copyright Duke Comprehensive Cancer Center * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catrip/LICENSE.txt for details. */ package edu.duke.cabig.tumorregistry.dataload; import edu.duke.cabig.tumorregistry.domain.*; public class FirstCourseTreatmentSummaryData extends FirstCourseTreatmentSummary { private Long sequenceNumber; public Long getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(Long sequenceNumber) { this.sequenceNumber = sequenceNumber; } }
NCIP/catrip
codebase/projects/tumor registry/test/edu/duke/cabig/tumorregistry/dataload/FirstCourseTreatmentSummaryData.java
Java
bsd-3-clause
553
package org.bouncycastle.jce.provider.test; import java.io.IOException; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.asn1.cms.GCMParameters; import org.bouncycastle.jcajce.spec.RepeatedSecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; public class AEADTest extends SimpleTest { // EAX test vector from EAXTest private byte[] K2 = Hex.decode("91945D3F4DCBEE0BF45EF52255F095A4"); private byte[] N2 = Hex.decode("BECAF043B0A23D843194BA972C66DEBD"); private byte[] A2 = Hex.decode("FA3BFD4806EB53FA"); private byte[] P2 = Hex.decode("F7FB"); private byte[] C2 = Hex.decode("19DD5C4C9331049D0BDAB0277408F67967E5"); // C2 with only 64bit MAC (default for EAX) private byte[] C2_short = Hex.decode("19DD5C4C9331049D0BDA"); private byte[] KGCM = Hex.decode("00000000000000000000000000000000"); private byte[] NGCM = Hex.decode("000000000000000000000000"); private byte[] CGCM = Hex.decode("58e2fccefa7e3061367f1d57a4e7455a"); public String getName() { return "AEAD"; } public void performTest() throws Exception { try { this.getClass().getClassLoader().loadClass("javax.crypto.spec.GCMParameterSpec"); checkCipherWithAD(K2, N2, A2, P2, C2_short); testGCMParameterSpec(K2, N2, A2, P2, C2); testGCMParameterSpecWithRepeatKey(K2, N2, A2, P2, C2); testGCMGeneric(KGCM, NGCM, new byte[0], new byte[0], CGCM); } catch (ClassNotFoundException e) { System.err.println("AEADTest disabled due to JDK"); } } private void checkCipherWithAD(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException { Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); IvParameterSpec iv = new IvParameterSpec(N); eax.init(Cipher.ENCRYPT_MODE, key, iv); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data failed."); } eax.init(Cipher.DECRYPT_MODE, key, iv); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data failed."); } } private void testGCMParameterSpec(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException { Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); // GCMParameterSpec mapped to AEADParameters and overrides default MAC // size GCMParameterSpec spec = new GCMParameterSpec(128, N); eax.init(Cipher.ENCRYPT_MODE, key, spec); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data and GCMParameterSpec failed."); } eax.init(Cipher.DECRYPT_MODE, key, spec); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data and GCMParameterSpec failed."); } AlgorithmParameters algParams = eax.getParameters(); byte[] encParams = algParams.getEncoded(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce()) || spec.getTLen() != gcmParameters.getIcvLen()) { fail("parameters mismatch"); } } private void testGCMParameterSpecWithRepeatKey(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException { Cipher eax = Cipher.getInstance("AES/EAX/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); GCMParameterSpec spec = new GCMParameterSpec(128, N); eax.init(Cipher.ENCRYPT_MODE, key, spec); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data and RepeatedSecretKeySpec failed."); } // Check GCMParameterSpec handling knows about RepeatedSecretKeySpec eax.init(Cipher.DECRYPT_MODE, new RepeatedSecretKeySpec("AES"), spec); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data and RepeatedSecretKeySpec failed."); } AlgorithmParameters algParams = eax.getParameters(); byte[] encParams = algParams.getEncoded(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce()) || spec.getTLen() != gcmParameters.getIcvLen()) { fail("parameters mismatch"); } } private void testGCMGeneric(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException { Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC"); SecretKeySpec key = new SecretKeySpec(K, "AES"); // GCMParameterSpec mapped to AEADParameters and overrides default MAC // size GCMParameterSpec spec = new GCMParameterSpec(128, N); eax.init(Cipher.ENCRYPT_MODE, key, spec); eax.updateAAD(A); byte[] c = eax.doFinal(P); if (!areEqual(C, c)) { fail("JCE encrypt with additional data and GCMParameterSpec failed."); } eax = Cipher.getInstance("GCM", "BC"); eax.init(Cipher.DECRYPT_MODE, key, spec); eax.updateAAD(A); byte[] p = eax.doFinal(C); if (!areEqual(P, p)) { fail("JCE decrypt with additional data and GCMParameterSpec failed."); } AlgorithmParameters algParams = eax.getParameters(); byte[] encParams = algParams.getEncoded(); GCMParameters gcmParameters = GCMParameters.getInstance(encParams); if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce()) || spec.getTLen() != gcmParameters.getIcvLen()) { fail("parameters mismatch"); } } public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); runTest(new AEADTest()); } }
GaloisInc/hacrypto
src/Java/BouncyCastle/BouncyCastle-1.50/prov/src/test/java/org/bouncycastle/jce/provider/test/AEADTest.java
Java
bsd-3-clause
8,521
package com.versionone; import com.versionone.utils.HashCode; /** * Class representing some duration of time */ public class Duration { /** * Valid units for Duration */ public enum Unit { Days, Weeks, Months } private int _amount; private Unit _units; /** * Default constructor * sets duration to 0 days */ public Duration() { this(0, Unit.Days); } /** * Create from amount and unit * @param amount - amount value for this instance * @param units - unit value for this instance */ public Duration(int amount, Unit units) { _units = units; setAmount(amount); } /** * Create instance from a String * Expected format is "%d {Unit}" for example "3 Days" (without the quotes) * * @param value - string value used to set amount and unit * @throws IllegalArgumentException if thre is an error in parsing the value */ public Duration(String value) { this(0, Unit.Days); if ((value == null || value.length() == 0)) { return; } try { String[] parts = value.split(" "); setAmount(Integer.parseInt(parts[0])); if (_amount != 0) _units = Unit.valueOf(parts[1]); } catch (Exception e) { throw new IllegalArgumentException("Not a valid Duration: " + value, e); } } /** * return the amount specified by this Duration * @return integer */ public int getAmount() { return _amount; } /** * return the units specified by this Duration * @return Unit */ public Unit getUnits() { return _units; } /** * Get amount of this Duration in days * @return int */ public int getDays() { switch (_units) { case Days: return _amount; case Weeks: return _amount * 7; case Months: if (_amount <= 1) return _amount * 30; else if (_amount < 12) return (_amount * 61) / 2; else return (_amount * 365) / 12; default: throw new UnsupportedOperationException(); } } /** * Compare two Duration instances * * @param a - one instance * @param b - the other instance * @return true if they are equal, false otherwise */ public static boolean compare(Duration a, Duration b) { if (null == a || null == b) return (null == a) && (null == b); return a.equals(b); } /** * Create a Duration from a String * * @param value - string used to create * @return an instance of Duration with value set from string * @see #Duration(String) */ public static Duration parse(String value) { return new Duration(value); } /** * Convert this instance to it's string representation (%d {Unit}) */ @Override public String toString() { return _amount + " " + _units.toString(); } /** * Compare this instance to another Duration * * @return true if they are equal, false otherwise */ @Override public boolean equals(Object obj) { boolean rc = false; if ((obj != null) && (obj instanceof Duration)) { Duration other = (Duration) obj; rc = (_amount == other.getAmount()) && (_units == other.getUnits()); } return rc; } /** * Get the hash code for this instance */ @Override public int hashCode() { return HashCode.Hash(_amount, _units); } private void setAmount(int amount) { if (amount < 0) { throw new IllegalArgumentException("Amount must be non-negative"); } _amount = amount; if (amount == 0) _units = Unit.Days; } }
minhhai2209/VersionOne.SDK.Java.APIClient
src/main/java/com/versionone/Duration.java
Java
bsd-3-clause
3,342
package org.cafebabepy.runtime.util; import org.cafebabepy.runtime.PyObject; import org.cafebabepy.runtime.Python; import java.util.Optional; public abstract class ASTNodeVisitor { protected final Python runtime; public ASTNodeVisitor(Python runtime) { this.runtime = runtime; } protected void visit(PyObject node) { Optional<PyObject> _fieldsOpt = this.runtime.getattrOptional(node, "_fields"); if (!_fieldsOpt.isPresent()) { if (this.runtime.isIterable(node)) { this.runtime.iter(node, this::visit); } return; } PyObject _fields = _fieldsOpt.get(); this.runtime.iter(_fields, field -> { PyObject value = this.runtime.getattr(node, field.toJava(String.class)); if (this.runtime.isInstance(value, "list")) { this.runtime.iter(value, item -> { if (this.runtime.isInstance(item, "_ast.AST")) { visit(item); } }); } else if (this.runtime.isInstance(value, "_ast.AST")) { visit(value); } }); } }
yotchang4s/cafebabepy
src/main/java/org/cafebabepy/runtime/util/ASTNodeVisitor.java
Java
bsd-3-clause
1,189
package com.compositesw.services.system.admin.resource; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import com.compositesw.services.system.util.common.AttributeList; import com.compositesw.services.system.util.common.BaseRequest; /** * <p>Java class for updateDataSourceChildInfosRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="updateDataSourceChildInfosRequest"> * &lt;complexContent> * &lt;extension base="{http://www.compositesw.com/services/system/util/common}baseRequest"> * &lt;sequence> * &lt;element name="path" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="childInfos"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="childInfo" type="{http://www.compositesw.com/services/system/admin/resource}dataSourceChildInfo" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="attributes" type="{http://www.compositesw.com/services/system/util/common}attributeList" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "updateDataSourceChildInfosRequest", propOrder = { "path", "childInfos", "attributes" }) public class UpdateDataSourceChildInfosRequest extends BaseRequest { @XmlElement(required = true) protected String path; @XmlElement(required = true) protected UpdateDataSourceChildInfosRequest.ChildInfos childInfos; protected AttributeList attributes; /** * Gets the value of the path property. * * @return * possible object is * {@link String } * */ public String getPath() { return path; } /** * Sets the value of the path property. * * @param value * allowed object is * {@link String } * */ public void setPath(String value) { this.path = value; } /** * Gets the value of the childInfos property. * * @return * possible object is * {@link UpdateDataSourceChildInfosRequest.ChildInfos } * */ public UpdateDataSourceChildInfosRequest.ChildInfos getChildInfos() { return childInfos; } /** * Sets the value of the childInfos property. * * @param value * allowed object is * {@link UpdateDataSourceChildInfosRequest.ChildInfos } * */ public void setChildInfos(UpdateDataSourceChildInfosRequest.ChildInfos value) { this.childInfos = value; } /** * Gets the value of the attributes property. * * @return * possible object is * {@link AttributeList } * */ public AttributeList getAttributes() { return attributes; } /** * Sets the value of the attributes property. * * @param value * allowed object is * {@link AttributeList } * */ public void setAttributes(AttributeList value) { this.attributes = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="childInfo" type="{http://www.compositesw.com/services/system/admin/resource}dataSourceChildInfo" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "childInfo" }) public static class ChildInfos { protected List<DataSourceChildInfo> childInfo; /** * Gets the value of the childInfo property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the childInfo property. * * <p> * For example, to add a new item, do as follows: * <pre> * getChildInfo().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DataSourceChildInfo } * * */ public List<DataSourceChildInfo> getChildInfo() { if (childInfo == null) { childInfo = new ArrayList<DataSourceChildInfo>(); } return this.childInfo; } } }
dvbu-test/PDTool
CISAdminApi7.0.0/src/com/compositesw/services/system/admin/resource/UpdateDataSourceChildInfosRequest.java
Java
bsd-3-clause
5,543
/* * Copyright (c) 2011, Regents of the University of Colorado * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.cleartk.corpus.timeml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CAS; import org.apache.uima.cas.CASException; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import org.cleartk.timeml.type.Anchor; import org.cleartk.timeml.type.DocumentCreationTime; import org.cleartk.timeml.type.Event; import org.cleartk.timeml.type.TemporalLink; import org.cleartk.timeml.type.Time; import org.cleartk.token.type.Sentence; import org.cleartk.token.type.Token; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.util.JCasUtil; import com.google.common.base.Joiner; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; /** * <br> * Copyright (c) 2011, Regents of the University of Colorado <br> * All rights reserved. * * @author Steven Bethard */ public class TempEval2010GoldAnnotator extends JCasAnnotator_ImplBase { public static AnalysisEngineDescription getDescription() throws ResourceInitializationException { return AnalysisEngineFactory.createEngineDescription(TempEval2010GoldAnnotator.class); } @ConfigurationParameter( name = PARAM_TEXT_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where document text should be placed") private String[] textViews; @ConfigurationParameter( name = PARAM_DOCUMENT_CREATION_TIME_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where DocumentCreationTime annotations should be placed") private String[] documentCreationTimeViews; @ConfigurationParameter( name = PARAM_TIME_EXTENT_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where Time annotations should be placed") private String[] timeExtentViews; @ConfigurationParameter( name = PARAM_TIME_ATTRIBUTE_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where Time annotation attributes should be placed") private String[] timeAttributeViews; @ConfigurationParameter( name = PARAM_EVENT_EXTENT_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where Event annotations should be placed") private String[] eventExtentViews; @ConfigurationParameter( name = PARAM_EVENT_ATTRIBUTE_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where Event annotation attributes should be placed") private String[] eventAttributeViews; @ConfigurationParameter( name = PARAM_TEMPORAL_LINK_EVENT_TO_DOCUMENT_CREATION_TIME_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where TemporalLink annotations between events and the document creation time should be placed") private String[] temporalLinkEventToDocumentCreationTimeViews; @ConfigurationParameter( name = PARAM_TEMPORAL_LINK_EVENT_TO_SAME_SENTENCE_TIME_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where TemporalLink annotations between events and times within the same sentence should be placed") private String[] temporalLinkEventToSameSentenceTimeViews; @ConfigurationParameter( name = PARAM_TEMPORAL_LINK_EVENT_TO_SUBORDINATED_EVENT_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where TemporalLink annotations between events and syntactically dominated events should be placed") private String[] temporalLinkEventToSubordinatedEventViews; @ConfigurationParameter( name = PARAM_TEMPORAL_LINK_MAIN_EVENT_TO_NEXT_SENTENCE_MAIN_EVENT_VIEWS, mandatory = false, defaultValue = CAS.NAME_DEFAULT_SOFA, description = "Views where TemporalLink annotations between main events in adjacent sentences should be placed") private String[] temporalLinkMainEventToNextSentenceMainEventViews; public static final String PARAM_TEXT_VIEWS = "textViews"; public static final String PARAM_DOCUMENT_CREATION_TIME_VIEWS = "documentCreationTimeViews"; public static final String PARAM_TIME_EXTENT_VIEWS = "timeExtentViews"; public static final String PARAM_TIME_ATTRIBUTE_VIEWS = "timeAttributeViews"; public static final String PARAM_EVENT_EXTENT_VIEWS = "eventExtentViews"; public static final String PARAM_EVENT_ATTRIBUTE_VIEWS = "eventAttributeViews"; public static final String PARAM_TEMPORAL_LINK_EVENT_TO_DOCUMENT_CREATION_TIME_VIEWS = "temporalLinkEventToDocumentCreationTimeViews"; public static final String PARAM_TEMPORAL_LINK_EVENT_TO_SAME_SENTENCE_TIME_VIEWS = "temporalLinkEventToSameSentenceTimeViews"; public static final String PARAM_TEMPORAL_LINK_EVENT_TO_SUBORDINATED_EVENT_VIEWS = "temporalLinkEventToSubordinatedEventViews"; public static final String PARAM_TEMPORAL_LINK_MAIN_EVENT_TO_NEXT_SENTENCE_MAIN_EVENT_VIEWS = "temporalLinkMainEventToNextSentenceMainEventViews"; @Override public void process(JCas jCas) throws AnalysisEngineProcessException { // load the sentences and tokens from the view ListMultimap<Integer, String> sentTokens = ArrayListMultimap.create(); for (String line : lines(jCas, TempEval2010CollectionReader.BASE_SEGMENTATION_VIEW_NAME)) { String[] columns = split(line, "<filename>", "<sent_no>", "<token_no>", "<text>"); int sentIndex = new Integer(columns[1]); String text = columns[3]; sentTokens.put(sentIndex, text); } // create the sentences and tokens Map<String, StringBuilder> textBuilders = new HashMap<String, StringBuilder>(); for (String viewName : this.textViews) { StringBuilder textBuilder = new StringBuilder("\n\n"); // leave line for document time JCas view = JCasUtil.getView(jCas, viewName, true); for (int i = 0; i < sentTokens.keySet().size(); ++i) { int sentBegin = textBuilder.length(); List<Token> tokens = new ArrayList<Token>(); for (String tokenText : sentTokens.get(i)) { int tokenBegin = textBuilder.length(); textBuilder.append(tokenText); int tokenEnd = textBuilder.length(); textBuilder.append(' '); Token token = new Token(view, tokenBegin, tokenEnd); token.addToIndexes(); tokens.add(token); } int sentEnd = textBuilder.length() - 1; textBuilder.setCharAt(sentEnd, '\n'); Sentence sentence = new Sentence(view, sentBegin, sentEnd); sentence.addToIndexes(); } textBuilders.put(viewName, textBuilder); } // add the document creation time for (String line : lines(jCas, TempEval2010CollectionReader.DCT_VIEW_NAME)) { String[] dctColumns = split(line, "<filename>", "<dct>"); String dctValue = dctColumns[1].replaceAll("(\\d{4})(\\d{2})(\\d{2})", "$1-$2-$3"); for (String viewName : this.documentCreationTimeViews) { JCas view = JCasUtil.getView(jCas, viewName, true); DocumentCreationTime docTime = new DocumentCreationTime(view, 1, 1); docTime.setId("t0"); docTime.setTimeType("DATE"); docTime.setValue(dctValue); docTime.setFunctionInDocument("CREATION_TIME"); docTime.addToIndexes(); } } // add Time annotations addSpans( jCas, TempEval2010CollectionReader.TIMEX_EXTENTS_VIEW_NAME, "timex3", this.timeExtentViews, new AnnotationConstructor<Time>() { @Override public Time apply(JCas aJCas, int begin, int end) { return new Time(aJCas, begin, end); } }); // add Time attributes addAttributes( jCas, TempEval2010CollectionReader.TIMEX_ATTRIBUTES_VIEW_NAME, Time.class, this.timeAttributeViews, new AttributeSetter<Time>() { @Override public void apply(Time time, String attrName, String attrValue) { if (attrName.equals("type")) { time.setTimeType(attrValue); } else if (attrName.equals("value")) { time.setValue(attrValue); } else { String message = "Unexpected TIMEX attribute %s=%s"; throw new IllegalArgumentException(String.format(message, attrName, attrValue)); } } }); // add Event annotations addSpans( jCas, TempEval2010CollectionReader.EVENT_EXTENTS_VIEW_NAME, "event", this.eventExtentViews, new AnnotationConstructor<Event>() { @Override public Event apply(JCas aJCas, int begin, int end) { return new Event(aJCas, begin, end); } }); // add Event attributes addAttributes( jCas, TempEval2010CollectionReader.EVENT_ATTRIBUTES_VIEW_NAME, Event.class, this.eventAttributeViews, new AttributeSetter<Event>() { @Override public void apply(Event event, String attrName, String attrValue) { if (attrName.equals("pos")) { event.setPos(attrValue); } else if (attrName.equals("tense")) { event.setTense(attrValue); } else if (attrName.equals("aspect")) { event.setAspect(attrValue); } else if (attrName.equals("class")) { event.setEventClass(attrValue); } else if (attrName.equals("polarity")) { event.setPolarity(attrValue); } else if (attrName.equals("modality")) { event.setModality(attrValue); } else { String message = "Unexpected EVENT attribute %s=%s"; throw new IllegalArgumentException(String.format(message, attrName, attrValue)); } } }); // add TemporalLink annotations addTemporalLinks( jCas, TempEval2010CollectionReader.TLINK_DCT_EVENT_VIEW_NAME, textBuilders, this.temporalLinkEventToDocumentCreationTimeViews); addTemporalLinks( jCas, TempEval2010CollectionReader.TLINK_TIMEX_EVENT_VIEW_NAME, textBuilders, this.temporalLinkEventToSameSentenceTimeViews); addTemporalLinks( jCas, TempEval2010CollectionReader.TLINK_SUBORDINATED_EVENTS_VIEW_NAME, textBuilders, this.temporalLinkEventToSubordinatedEventViews); addTemporalLinks( jCas, TempEval2010CollectionReader.TLINK_MAIN_EVENTS_VIEW_NAME, textBuilders, this.temporalLinkMainEventToNextSentenceMainEventViews); // set the document text for (String viewName : this.textViews) { JCas view = JCasUtil.getView(jCas, viewName, true); view.setDocumentText(textBuilders.get(viewName).toString()); } } private static String[] split(String line, String... expected) { String[] columns = line.split("\t"); if (columns.length != expected.length) { throw new IllegalArgumentException(String.format( "Expected % d items, %s, found %d items, %s", expected.length, Joiner.on('\t').join(expected), columns.length, line)); } return columns; } private static String[] lines(JCas jCas, String viewName) throws AnalysisEngineProcessException { JCas view; try { view = jCas.getView(viewName); } catch (CASException e) { throw new AnalysisEngineProcessException(e); } String text = view.getDocumentText(); if (text == null) { throw new IllegalArgumentException("no text in view " + viewName); } return text.length() > 0 ? text.split("\n") : new String[0]; } private static interface AnnotationConstructor<T extends Annotation> { public T apply(JCas jCas, int begin, int end); } private static <T extends Anchor> void addSpans( JCas jCas, String tabViewName, String elementName, String[] annotationViewNames, AnnotationConstructor<T> constructor) throws AnalysisEngineProcessException { String[] lines = lines(jCas, tabViewName); for (String annotationViewName : annotationViewNames) { JCas view = JCasUtil.getView(jCas, annotationViewName, true); Map<String, T> idMap = new HashMap<String, T>(); List<List<Token>> sentenceTokens = new ArrayList<List<Token>>(); for (Sentence sentence : JCasUtil.select(view, Sentence.class)) { sentenceTokens.add(JCasUtil.selectCovered(view, Token.class, sentence)); } for (String line : lines) { String[] columns = split( line, "<filename>", "<sent_no>", "<token_no>", elementName, "<id>", "1"); int sentIndex = Integer.parseInt(columns[1]); int tokenIndex = Integer.parseInt(columns[2]); String id = columns[4]; Token token = sentenceTokens.get(sentIndex).get(tokenIndex); if (!idMap.containsKey(id)) { T ann = constructor.apply(view, token.getBegin(), token.getEnd()); ann.setId(id); ann.addToIndexes(); idMap.put(id, ann); } else { T ann = idMap.get(id); if (token.getBegin() < ann.getBegin()) { ann.setBegin(token.getBegin()); } if (token.getEnd() > ann.getEnd()) { ann.setEnd(token.getEnd()); } } } } } private static interface AttributeSetter<T extends Annotation> { public void apply(T ann, String attrName, String attrValue); } private static <T extends Anchor> void addAttributes( JCas jCas, String tabViewName, Class<T> cls, String[] annotationViewNames, AttributeSetter<T> setter) throws AnalysisEngineProcessException { String[] lines = lines(jCas, tabViewName); for (String annotationViewName : annotationViewNames) { JCas view = JCasUtil.getView(jCas, annotationViewName, false); Map<String, T> idMap = new HashMap<String, T>(); for (T anchor : JCasUtil.select(view, cls)) { idMap.put(anchor.getId(), anchor); } for (String line : lines) { String[] columns = split( line, "<filename>", "<sent_no>", "<token_no>", "timex3", "<id>", "1", "<attribute>", "<value>"); String id = columns[4]; String attrName = columns[6]; String attrValue = columns[7]; setter.apply(idMap.get(id), attrName, attrValue); } } } private static void addTemporalLinks( JCas jCas, String tabViewName, Map<String, StringBuilder> textBuilders, String[] annotationViewNames) throws AnalysisEngineProcessException { String[] lines = lines(jCas, tabViewName); for (String annotationViewName : annotationViewNames) { JCas view = JCasUtil.getView(jCas, annotationViewName, true); Map<String, Anchor> idAnchors = new HashMap<String, Anchor>(); for (Anchor anchor : JCasUtil.select(view, Anchor.class)) { idAnchors.put(anchor.getId(), anchor); } StringBuilder textBuilder = textBuilders.get(annotationViewName); for (String line : lines) { String[] columns = split(line, "<filename>", "<eid>", "<tid>", "<relation>"); String sourceID = columns[1]; String targetID = columns[2]; String relation = columns[3]; int offset = textBuilder.length(); TemporalLink tlink = new TemporalLink(view, offset, offset); tlink.setSource(idAnchors.get(sourceID)); tlink.setTarget(idAnchors.get(targetID)); tlink.setRelationType(relation); tlink.addToIndexes(); textBuilder.append('\n'); } } } }
ClearTK/cleartk
cleartk-corpus/src/main/java/org/cleartk/corpus/timeml/TempEval2010GoldAnnotator.java
Java
bsd-3-clause
17,911
package brown.tracingplane.bdl.examples; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.google.common.collect.Sets; import brown.tracingplane.BaggageContext; import brown.tracingplane.baggageprotocol.BagKey; import brown.tracingplane.impl.BDLContext; import brown.tracingplane.impl.BDLContextProvider; import brown.tracingplane.impl.BDLContextProviderFactory; import brown.tracingplane.impl.BaggageHandlerRegistry; import brown.xtrace.XTraceBaggage; public class TestXTraceBaggage { static { // Temporary registration for testing etc. BaggageHandlerRegistry.add(BagKey.indexed(0), XTraceBaggage.Handler.instance); } private static final BDLContextProvider provider = (BDLContextProvider) new BDLContextProviderFactory().provider(); @Test public void simpleTest() { // Create an XTraceBaggage object XTraceBaggage xmd = new XTraceBaggage(); xmd.taskId = 100L; xmd.parentEventIds = Sets.<Long>newHashSet(1000L, 300L, 200L); BaggageContext a = XTraceBaggage.setIn(null, xmd); // Create another XTraceBaggage object XTraceBaggage xmd2 = new XTraceBaggage(); xmd2.taskId = 100L; xmd2.parentEventIds = Sets.<Long>newHashSet(1000L, 500L); BaggageContext b = XTraceBaggage.setIn(null, xmd2); // Merge them explicitly BaggageContext b3 = provider.join(provider.branch((BDLContext) a), provider.branch((BDLContext) b)); // Get the merged XTraceBaggage XTraceBaggage xmd3 = XTraceBaggage.getFrom(b3); assertEquals(Long.valueOf(100L), xmd3.taskId); assertEquals(Sets.newHashSet(200L, 300L, 500L, 1000L), xmd3.parentEventIds); } }
tracingplane/tracingplane-java
bdl/examples/src/test/java/brown/tracingplane/bdl/examples/TestXTraceBaggage.java
Java
bsd-3-clause
1,763
// ============================================================================ // // Copyright (C) 2006-2015 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package routines.system; import java.util.HashMap; import java.util.Map; public class GlobalResource { // let it support the top level Object public static Map<Object, Object> resourceMap = new HashMap<Object, Object>(); // when there is multiple threads wants to insert stats&logs&meta into DB, it is used as a locker. bug:22677 public static TalendMultiThreadLockMap resourceLockMap = new TalendMultiThreadLockMap(); public static class TalendMultiThreadLockMap { private Map<Object, Object> tMultiTheadLockMap = new HashMap<Object, Object>(); public Object get(Object key) { if (tMultiTheadLockMap.get(key) == null) { synchronized (TalendMultiThreadLockMap.this) { if (tMultiTheadLockMap.get(key) == null) { tMultiTheadLockMap.put(key, new Object()); } } } return tMultiTheadLockMap.get(key); } } }
blaadr/portail
jobs/i0_import_selligent_mails_0.1/i0_import_selligent_mails/src/main/java/routines/system/GlobalResource.java
Java
bsd-3-clause
1,512
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.automation.v2015_10_31; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.automation.v2015_10_31.implementation.DscConfigurationInner; import com.microsoft.azure.arm.model.Indexable; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.automation.v2015_10_31.implementation.AutomationManager; import java.util.Map; import org.joda.time.DateTime; /** * Type representing DscConfiguration. */ public interface DscConfiguration extends HasInner<DscConfigurationInner>, Indexable, Refreshable<DscConfiguration>, Updatable<DscConfiguration.Update>, HasManager<AutomationManager> { /** * @return the creationTime value. */ DateTime creationTime(); /** * @return the description value. */ String description(); /** * @return the etag value. */ String etag(); /** * @return the id value. */ String id(); /** * @return the jobCount value. */ Integer jobCount(); /** * @return the lastModifiedTime value. */ DateTime lastModifiedTime(); /** * @return the location value. */ String location(); /** * @return the logVerbose value. */ Boolean logVerbose(); /** * @return the name value. */ String name(); /** * @return the nodeConfigurationCount value. */ int nodeConfigurationCount(); /** * @return the parameters value. */ Map<String, DscConfigurationParameter> parameters(); /** * @return the provisioningState value. */ DscConfigurationProvisioningState provisioningState(); /** * @return the source value. */ ContentSource source(); /** * @return the state value. */ DscConfigurationState state(); /** * @return the tags value. */ Map<String, String> tags(); /** * @return the type value. */ String type(); /** * The entirety of the DscConfiguration definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithAutomationAccount, DefinitionStages.WithSource, DefinitionStages.WithCreate { } /** * Grouping of DscConfiguration definition stages. */ interface DefinitionStages { /** * The first stage of a DscConfiguration definition. */ interface Blank extends WithAutomationAccount { } /** * The stage of the dscconfiguration definition allowing to specify AutomationAccount. */ interface WithAutomationAccount { /** * Specifies resourceGroupName, automationAccountName. */ WithSource withExistingAutomationAccount(String resourceGroupName, String automationAccountName); } /** * The stage of the dscconfiguration definition allowing to specify Source. */ interface WithSource { /** * Specifies source. */ WithCreate withSource(ContentSource source); } /** * The stage of the dscconfiguration definition allowing to specify Description. */ interface WithDescription { /** * Specifies description. */ WithCreate withDescription(String description); } /** * The stage of the dscconfiguration definition allowing to specify Location. */ interface WithLocation { /** * Specifies location. */ WithCreate withLocation(String location); } /** * The stage of the dscconfiguration definition allowing to specify LogProgress. */ interface WithLogProgress { /** * Specifies logProgress. */ WithCreate withLogProgress(Boolean logProgress); } /** * The stage of the dscconfiguration definition allowing to specify LogVerbose. */ interface WithLogVerbose { /** * Specifies logVerbose. */ WithCreate withLogVerbose(Boolean logVerbose); } /** * The stage of the dscconfiguration definition allowing to specify Name. */ interface WithName { /** * Specifies name. */ WithCreate withName(String name); } /** * The stage of the dscconfiguration definition allowing to specify Parameters. */ interface WithParameters { /** * Specifies parameters. */ WithCreate withParameters(Map<String, DscConfigurationParameter> parameters); } /** * The stage of the dscconfiguration definition allowing to specify Tags. */ interface WithTags { /** * Specifies tags. */ WithCreate withTags(Map<String, String> tags); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<DscConfiguration>, DefinitionStages.WithDescription, DefinitionStages.WithLocation, DefinitionStages.WithLogProgress, DefinitionStages.WithLogVerbose, DefinitionStages.WithName, DefinitionStages.WithParameters, DefinitionStages.WithTags { } } /** * The template for a DscConfiguration update operation, containing all the settings that can be modified. */ interface Update extends Appliable<DscConfiguration>, UpdateStages.WithDescription, UpdateStages.WithLogProgress, UpdateStages.WithLogVerbose, UpdateStages.WithName, UpdateStages.WithParameters, UpdateStages.WithTags { } /** * Grouping of DscConfiguration update stages. */ interface UpdateStages { /** * The stage of the dscconfiguration update allowing to specify Description. */ interface WithDescription { /** * Specifies description. */ Update withDescription(String description); } /** * The stage of the dscconfiguration update allowing to specify LogProgress. */ interface WithLogProgress { /** * Specifies logProgress. */ Update withLogProgress(Boolean logProgress); } /** * The stage of the dscconfiguration update allowing to specify LogVerbose. */ interface WithLogVerbose { /** * Specifies logVerbose. */ Update withLogVerbose(Boolean logVerbose); } /** * The stage of the dscconfiguration update allowing to specify Name. */ interface WithName { /** * Specifies name. */ Update withName(String name); } /** * The stage of the dscconfiguration update allowing to specify Parameters. */ interface WithParameters { /** * Specifies parameters. */ Update withParameters(Map<String, DscConfigurationParameter> parameters); } /** * The stage of the dscconfiguration update allowing to specify Tags. */ interface WithTags { /** * Specifies tags. */ Update withTags(Map<String, String> tags); } } }
selvasingh/azure-sdk-for-java
sdk/automation/mgmt-v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/DscConfiguration.java
Java
mit
8,257
/** * Copyright MaDgIK Group 2010 - 2015. */ package madgik.exareme.utils.association; import java.io.Serializable; /** * @param <A> * @param <B> * @param <C> * @author herald */ public class Triple<A, B, C> implements Serializable { private static final long serialVersionUID = 1L; public A a; public B b; public C c; public Triple(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } public A getA() { return a; } public B getB() { return b; } public C getC() { return c; } @Override public String toString() { return "(" + a.toString() + "," + b.toString() + "," + c.toString() + ")"; } }
XristosMallios/cache
exareme-utils/src/main/java/madgik/exareme/utils/association/Triple.java
Java
mit
721
package me.prettyprint.cassandra.connection; /** * Timer For Cassandra operations */ public interface HOpTimer { /** * Start timing an operation. * * @return - a token that will be returned to the timer when stop(...) in * invoked */ Object start(String tagName); /** * * @param token * - the token returned from start * @param tagName * - the name of the tag * @param success * - did the oepration succeed */ void stop(Object token, String tagName, boolean success); }
Ursula/hector
core/src/main/java/me/prettyprint/cassandra/connection/HOpTimer.java
Java
mit
559
package ubf; public class UBFString extends UBFObject { public final String value; public UBFString(String s) { value = s; } public boolean isString() { return true; } public String toString() { return value; } public boolean equals(Object o) { return ((o instanceof UBFString) && (((UBFString)o).value.equals(this.value))); } public int hashCode() { return value.hashCode(); } }
ubf/ubf
priv/java/src/ubf/UBFString.java
Java
mit
438
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.automation.v2015_10_31.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.automation.v2015_10_31.ErrorResponseException; import com.microsoft.azure.management.automation.v2015_10_31.RunbookCreateOrUpdateParameters; import com.microsoft.azure.management.automation.v2015_10_31.RunbookUpdateParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.PATCH; import retrofit2.http.Path; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in Runbooks. */ public class RunbooksInner { /** The Retrofit service to perform REST calls. */ private RunbooksService service; /** The service client containing this operation class. */ private AutomationClientImpl client; /** * Initializes an instance of RunbooksInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public RunbooksInner(Retrofit retrofit, AutomationClientImpl client) { this.service = retrofit.create(RunbooksService.class); this.client = client; } /** * The interface defining all the services for Runbooks to be * used by Retrofit to perform actually REST calls. */ interface RunbooksService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks getContent" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}/content") Observable<Response<ResponseBody>> getContent(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Path("runbookName") String runbookName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}") Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Path("runbookName") String runbookName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}") Observable<Response<ResponseBody>> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Path("runbookName") String runbookName, @Body RunbookCreateOrUpdateParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks update" }) @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}") Observable<Response<ResponseBody>> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Path("runbookName") String runbookName, @Body RunbookUpdateParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Path("runbookName") String runbookName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks listByAutomationAccount" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks") Observable<Response<ResponseBody>> listByAutomationAccount(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("automationAccountName") String automationAccountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.automation.v2015_10_31.Runbooks listByAutomationAccountNext" }) @GET Observable<Response<ResponseBody>> listByAutomationAccountNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Retrieve the content of runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String getContent(String resourceGroupName, String automationAccountName, String runbookName) { return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).toBlocking().single().body(); } /** * Retrieve the content of runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> getContentAsync(String resourceGroupName, String automationAccountName, String runbookName, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName), serviceCallback); } /** * Retrieve the content of runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<String> getContentAsync(String resourceGroupName, String automationAccountName, String runbookName) { return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Retrieve the content of runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<ServiceResponse<String>> getContentWithServiceResponseAsync(String resourceGroupName, String automationAccountName, String runbookName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } if (runbookName == null) { throw new IllegalArgumentException("Parameter runbookName is required and cannot be null."); } final String apiVersion = "2015-10-31"; return service.getContent(this.client.subscriptionId(), resourceGroupName, automationAccountName, runbookName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() { @Override public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) { try { ServiceResponse<String> clientResponse = getContentDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<String> getContentDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<String, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<String>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Retrieve the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the RunbookInner object if successful. */ public RunbookInner get(String resourceGroupName, String automationAccountName, String runbookName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).toBlocking().single().body(); } /** * Retrieve the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<RunbookInner> getAsync(String resourceGroupName, String automationAccountName, String runbookName, final ServiceCallback<RunbookInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName), serviceCallback); } /** * Retrieve the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<RunbookInner> getAsync(String resourceGroupName, String automationAccountName, String runbookName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).map(new Func1<ServiceResponse<RunbookInner>, RunbookInner>() { @Override public RunbookInner call(ServiceResponse<RunbookInner> response) { return response.body(); } }); } /** * Retrieve the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<ServiceResponse<RunbookInner>> getWithServiceResponseAsync(String resourceGroupName, String automationAccountName, String runbookName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } if (runbookName == null) { throw new IllegalArgumentException("Parameter runbookName is required and cannot be null."); } final String apiVersion = "2015-10-31"; return service.get(this.client.subscriptionId(), resourceGroupName, automationAccountName, runbookName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RunbookInner>>>() { @Override public Observable<ServiceResponse<RunbookInner>> call(Response<ResponseBody> response) { try { ServiceResponse<RunbookInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<RunbookInner> getDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<RunbookInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<RunbookInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Create the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the RunbookInner object if successful. */ public RunbookInner createOrUpdate(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).toBlocking().single().body(); } /** * Create the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<RunbookInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters, final ServiceCallback<RunbookInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters), serviceCallback); } /** * Create the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<RunbookInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).map(new Func1<ServiceResponse<RunbookInner>, RunbookInner>() { @Override public RunbookInner call(ServiceResponse<RunbookInner> response) { return response.body(); } }); } /** * Create the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The create or update parameters for runbook. Provide either content link for a published runbook or draft, not both. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<ServiceResponse<RunbookInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookCreateOrUpdateParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } if (runbookName == null) { throw new IllegalArgumentException("Parameter runbookName is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2015-10-31"; return service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, automationAccountName, runbookName, parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RunbookInner>>>() { @Override public Observable<ServiceResponse<RunbookInner>> call(Response<ResponseBody> response) { try { ServiceResponse<RunbookInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<RunbookInner> createOrUpdateDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<RunbookInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<RunbookInner>() { }.getType()) .register(201, new TypeToken<RunbookInner>() { }.getType()) .register(400, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Update the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The update parameters for runbook. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the RunbookInner object if successful. */ public RunbookInner update(String resourceGroupName, String automationAccountName, String runbookName, RunbookUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).toBlocking().single().body(); } /** * Update the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The update parameters for runbook. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<RunbookInner> updateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookUpdateParameters parameters, final ServiceCallback<RunbookInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters), serviceCallback); } /** * Update the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The update parameters for runbook. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<RunbookInner> updateAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).map(new Func1<ServiceResponse<RunbookInner>, RunbookInner>() { @Override public RunbookInner call(ServiceResponse<RunbookInner> response) { return response.body(); } }); } /** * Update the runbook identified by runbook name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param parameters The update parameters for runbook. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the RunbookInner object */ public Observable<ServiceResponse<RunbookInner>> updateWithServiceResponseAsync(String resourceGroupName, String automationAccountName, String runbookName, RunbookUpdateParameters parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } if (runbookName == null) { throw new IllegalArgumentException("Parameter runbookName is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2015-10-31"; return service.update(this.client.subscriptionId(), resourceGroupName, automationAccountName, runbookName, parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RunbookInner>>>() { @Override public Observable<ServiceResponse<RunbookInner>> call(Response<ResponseBody> response) { try { ServiceResponse<RunbookInner> clientResponse = updateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<RunbookInner> updateDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<RunbookInner, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<RunbookInner>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Delete the runbook by name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String automationAccountName, String runbookName) { deleteWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).toBlocking().single().body(); } /** * Delete the runbook by name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String automationAccountName, String runbookName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName), serviceCallback); } /** * Delete the runbook by name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> deleteAsync(String resourceGroupName, String automationAccountName, String runbookName) { return deleteWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Delete the runbook by name. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param runbookName The runbook name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String automationAccountName, String runbookName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } if (runbookName == null) { throw new IllegalArgumentException("Parameter runbookName is required and cannot be null."); } final String apiVersion = "2015-10-31"; return service.delete(this.client.subscriptionId(), resourceGroupName, automationAccountName, runbookName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = deleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> deleteDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(204, new TypeToken<Void>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Retrieve a list of runbooks. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;RunbookInner&gt; object if successful. */ public PagedList<RunbookInner> listByAutomationAccount(final String resourceGroupName, final String automationAccountName) { ServiceResponse<Page<RunbookInner>> response = listByAutomationAccountSinglePageAsync(resourceGroupName, automationAccountName).toBlocking().single(); return new PagedList<RunbookInner>(response.body()) { @Override public Page<RunbookInner> nextPage(String nextPageLink) { return listByAutomationAccountNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieve a list of runbooks. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<RunbookInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName, final ListOperationCallback<RunbookInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByAutomationAccountSinglePageAsync(resourceGroupName, automationAccountName), new Func1<String, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(String nextPageLink) { return listByAutomationAccountNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieve a list of runbooks. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;RunbookInner&gt; object */ public Observable<Page<RunbookInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) { return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName) .map(new Func1<ServiceResponse<Page<RunbookInner>>, Page<RunbookInner>>() { @Override public Page<RunbookInner> call(ServiceResponse<Page<RunbookInner>> response) { return response.body(); } }); } /** * Retrieve a list of runbooks. * * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;RunbookInner&gt; object */ public Observable<ServiceResponse<Page<RunbookInner>>> listByAutomationAccountWithServiceResponseAsync(final String resourceGroupName, final String automationAccountName) { return listByAutomationAccountSinglePageAsync(resourceGroupName, automationAccountName) .concatMap(new Func1<ServiceResponse<Page<RunbookInner>>, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(ServiceResponse<Page<RunbookInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAutomationAccountNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieve a list of runbooks. * ServiceResponse<PageImpl<RunbookInner>> * @param resourceGroupName Name of an Azure Resource group. ServiceResponse<PageImpl<RunbookInner>> * @param automationAccountName The name of the automation account. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;RunbookInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<RunbookInner>>> listByAutomationAccountSinglePageAsync(final String resourceGroupName, final String automationAccountName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (automationAccountName == null) { throw new IllegalArgumentException("Parameter automationAccountName is required and cannot be null."); } final String apiVersion = "2015-10-31"; return service.listByAutomationAccount(this.client.subscriptionId(), resourceGroupName, automationAccountName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<RunbookInner>> result = listByAutomationAccountDelegate(response); return Observable.just(new ServiceResponse<Page<RunbookInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<RunbookInner>> listByAutomationAccountDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<RunbookInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<RunbookInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } /** * Retrieve a list of runbooks. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;RunbookInner&gt; object if successful. */ public PagedList<RunbookInner> listByAutomationAccountNext(final String nextPageLink) { ServiceResponse<Page<RunbookInner>> response = listByAutomationAccountNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<RunbookInner>(response.body()) { @Override public Page<RunbookInner> nextPage(String nextPageLink) { return listByAutomationAccountNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieve a list of runbooks. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<RunbookInner>> listByAutomationAccountNextAsync(final String nextPageLink, final ServiceFuture<List<RunbookInner>> serviceFuture, final ListOperationCallback<RunbookInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByAutomationAccountNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(String nextPageLink) { return listByAutomationAccountNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieve a list of runbooks. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;RunbookInner&gt; object */ public Observable<Page<RunbookInner>> listByAutomationAccountNextAsync(final String nextPageLink) { return listByAutomationAccountNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<RunbookInner>>, Page<RunbookInner>>() { @Override public Page<RunbookInner> call(ServiceResponse<Page<RunbookInner>> response) { return response.body(); } }); } /** * Retrieve a list of runbooks. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;RunbookInner&gt; object */ public Observable<ServiceResponse<Page<RunbookInner>>> listByAutomationAccountNextWithServiceResponseAsync(final String nextPageLink) { return listByAutomationAccountNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<RunbookInner>>, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(ServiceResponse<Page<RunbookInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAutomationAccountNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieve a list of runbooks. * ServiceResponse<PageImpl<RunbookInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;RunbookInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<RunbookInner>>> listByAutomationAccountNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listByAutomationAccountNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RunbookInner>>>>() { @Override public Observable<ServiceResponse<Page<RunbookInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<RunbookInner>> result = listByAutomationAccountNextDelegate(response); return Observable.just(new ServiceResponse<Page<RunbookInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<RunbookInner>> listByAutomationAccountNextDelegate(Response<ResponseBody> response) throws ErrorResponseException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<RunbookInner>, ErrorResponseException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<RunbookInner>>() { }.getType()) .registerError(ErrorResponseException.class) .build(response); } }
selvasingh/azure-sdk-for-java
sdk/automation/mgmt-v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbooksInner.java
Java
mit
47,125
/******************************************************************************* * ENdoSnipe 5.0 - (https://github.com/endosnipe) * * The MIT License (MIT) * * Copyright (c) 2012 Acroquest Technology Co.,Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package jp.co.acroquest.endosnipe.javelin.conf; /** * トランスフォーム対象から除外するクラスもしくはメソッドを示す設定。 * * @author yamasaki */ public class ExcludeConversionConfig extends AbstractConversionConfig { // Do Nothing. }
ryokato/ENdoSnipe
Javelin/src/main/java/jp/co/acroquest/endosnipe/javelin/conf/ExcludeConversionConfig.java
Java
mit
1,687
package com.loopj.android.HttpUtil; import org.apache.http.Header; import cn.eoe.android.libraries.entity.LibProducts; import cn.eoe.android.libraries.entity.LibSlides; import com.google.gson.Gson; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.BaseJsonHttpResponseHandler; public class HttpTest { /** * 测试 获取插件列表 获取与解析 */ public static void TestLibProduct() { final Gson gson = new Gson(); String urlString="http://www.1sters.com/api/v1/libraries/list?sort=pop&page=1"; HttpUtil.get(urlString, new BaseJsonHttpResponseHandler<LibProducts>() { @Override public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, LibProducts response) { System.out.println("suc"); System.err.println(response.getBackground()); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, LibProducts errorResponse) { System.out.println("fail"); } @Override protected LibProducts parseResponse(String rawJsonData, boolean isFailure) throws Throwable { // TODO Auto-generated method stub return gson.fromJson(rawJsonData, LibProducts.class); }; }); } /** * 测试 获取插件列表 获取与解析 */ public static void TestSlide() { final Gson gson = new Gson(); String urlString="http://www.1sters.com/api/v1/libraries/slides"; HttpUtil.get(urlString, new BaseJsonHttpResponseHandler<LibSlides>() { @Override public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, LibSlides response) { System.out.println("suc"); System.err.println(response.getData().get(0).getItems().get(0).getLabel()); } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, LibSlides errorResponse) { System.out.println("fail"); } @Override protected LibSlides parseResponse(String rawJsonData, boolean isFailure) throws Throwable { // TODO Auto-generated method stub return gson.fromJson(rawJsonData, LibSlides.class); }; }); } }
shengge/eoe-Libraries-for-Android-Developers
src/com/loopj/android/HttpUtil/HttpTest.java
Java
mit
2,241
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.compute; /** * The popular Azure Linux images. */ public enum KnownLinuxVirtualMachineImage { /** UbuntuServer 14.04LTS. */ UBUNTU_SERVER_14_04_LTS("Canonical", "UbuntuServer", "14.04.4-LTS"), /** UbuntuServer 16.04LTS. */ UBUNTU_SERVER_16_04_LTS("Canonical", "UbuntuServer", "16.04.0-LTS"), /** Debian 8. */ DEBIAN_8("credativ", "Debian", "8"), /** CentOS 7.2. */ CENTOS_7_2("OpenLogic", "CentOS", "7.2"), /** OpenSUSE-Leap 42.1. */ OPENSUSE_LEAP_42_1("SUSE", "openSUSE-Leap", "42.1"), /** SLES 12-SP1. */ SLES_12_SP1("SUSE", "SLES", "12-SP1"); private final String publisher; private final String offer; private final String sku; KnownLinuxVirtualMachineImage(String publisher, String offer, String sku) { this.publisher = publisher; this.offer = offer; this.sku = sku; } /** * @return the name of the image publisher */ public String publisher() { return this.publisher; } /** * @return the name of the image offer */ public String offer() { return this.offer; } /** * @return the name of the image SKU */ public String sku() { return this.sku; } /** * @return the image reference */ public ImageReference imageReference() { return new ImageReference() .withPublisher(publisher()) .withOffer(offer()) .withSku(sku()) .withVersion("latest"); } }
jianghaolu/azure-sdk-for-java
azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/KnownLinuxVirtualMachineImage.java
Java
mit
1,740
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.network.models.ConnectionStatus; import com.azure.resourcemanager.network.models.ConnectivityHop; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Information on the connectivity status. */ @Immutable public final class ConnectivityInformationInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(ConnectivityInformationInner.class); /* * List of hops between the source and the destination. */ @JsonProperty(value = "hops", access = JsonProperty.Access.WRITE_ONLY) private List<ConnectivityHop> hops; /* * The connection status. */ @JsonProperty(value = "connectionStatus", access = JsonProperty.Access.WRITE_ONLY) private ConnectionStatus connectionStatus; /* * Average latency in milliseconds. */ @JsonProperty(value = "avgLatencyInMs", access = JsonProperty.Access.WRITE_ONLY) private Integer avgLatencyInMs; /* * Minimum latency in milliseconds. */ @JsonProperty(value = "minLatencyInMs", access = JsonProperty.Access.WRITE_ONLY) private Integer minLatencyInMs; /* * Maximum latency in milliseconds. */ @JsonProperty(value = "maxLatencyInMs", access = JsonProperty.Access.WRITE_ONLY) private Integer maxLatencyInMs; /* * Total number of probes sent. */ @JsonProperty(value = "probesSent", access = JsonProperty.Access.WRITE_ONLY) private Integer probesSent; /* * Number of failed probes. */ @JsonProperty(value = "probesFailed", access = JsonProperty.Access.WRITE_ONLY) private Integer probesFailed; /** * Get the hops property: List of hops between the source and the destination. * * @return the hops value. */ public List<ConnectivityHop> hops() { return this.hops; } /** * Get the connectionStatus property: The connection status. * * @return the connectionStatus value. */ public ConnectionStatus connectionStatus() { return this.connectionStatus; } /** * Get the avgLatencyInMs property: Average latency in milliseconds. * * @return the avgLatencyInMs value. */ public Integer avgLatencyInMs() { return this.avgLatencyInMs; } /** * Get the minLatencyInMs property: Minimum latency in milliseconds. * * @return the minLatencyInMs value. */ public Integer minLatencyInMs() { return this.minLatencyInMs; } /** * Get the maxLatencyInMs property: Maximum latency in milliseconds. * * @return the maxLatencyInMs value. */ public Integer maxLatencyInMs() { return this.maxLatencyInMs; } /** * Get the probesSent property: Total number of probes sent. * * @return the probesSent value. */ public Integer probesSent() { return this.probesSent; } /** * Get the probesFailed property: Number of failed probes. * * @return the probesFailed value. */ public Integer probesFailed() { return this.probesFailed; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (hops() != null) { hops().forEach(e -> e.validate()); } } }
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/ConnectivityInformationInner.java
Java
mit
3,762
/** * EdDSA-Java by str4d * * To the extent possible under law, the person who associated CC0 with * EdDSA-Java has waived all copyright and related or neighboring rights * to EdDSA-Java. * * You should have received a copy of the CC0 legalcode along with this * work. If not, see <https://creativecommons.org/publicdomain/zero/1.0/>. * */ package net.i2p.crypto.eddsa; import net.i2p.crypto.eddsa.spec.EdDSAParameterSpec; /** * Common interface for all EdDSA keys. * @author str4d */ public interface EdDSAKey { /** * The reported key algorithm for all EdDSA keys */ String KEY_ALGORITHM = "EdDSA"; /** * @return a parameter specification representing the EdDSA domain * parameters for the key. */ EdDSAParameterSpec getParams(); }
tarcieri/red25519
ext/ed25519_jruby/net/i2p/crypto/eddsa/EdDSAKey.java
Java
mit
798
package net.glowstone.util.nbt; /** * The {@code TAG_Long} tag. */ final class LongTag extends Tag<Long> { /** * The value. */ private final long value; /** * Creates the tag. * * @param value The value. */ public LongTag(long value) { super(TagType.LONG); this.value = value; } @Override public Long getValue() { return value; } }
jimmikaelkael/GlowstonePlusPlus
src/main/java/net/glowstone/util/nbt/LongTag.java
Java
mit
426