Esempio n. 1
0
  /**
   * Called before window creation, descendants should override to initialize the data, initialize
   * params.
   */
  void preInit(XCreateWindowParams params) {
    state_lock = new StateLock();
    initialising = InitialiseState.NOT_INITIALISED;
    embedded = Boolean.TRUE.equals(params.get(EMBEDDED));
    visible = Boolean.TRUE.equals(params.get(VISIBLE));

    Object parent = params.get(PARENT);
    if (parent instanceof XBaseWindow) {
      parentWindow = (XBaseWindow) parent;
    } else {
      Long parentWindowID = (Long) params.get(PARENT_WINDOW);
      if (parentWindowID != null) {
        parentWindow = XToolkit.windowToXWindow(parentWindowID);
      }
    }

    Long eventMask = (Long) params.get(EVENT_MASK);
    if (eventMask != null) {
      long mask = eventMask.longValue();
      mask |= SubstructureNotifyMask;
      params.put(EVENT_MASK, mask);
    }

    screen = -1;
  }
 private void writeState(final Element element) {
   JDOMExternalizerUtil.writeField(
       element, INSTRUMENTATION_TYPE_NAME, myInstrumentationType.toString());
   JDOMExternalizerUtil.writeField(element, LANGUAGE_ANNOTATION_NAME, myLanguageAnnotation);
   JDOMExternalizerUtil.writeField(element, PATTERN_ANNOTATION_NAME, myPatternAnnotation);
   JDOMExternalizerUtil.writeField(element, SUBST_ANNOTATION_NAME, mySubstAnnotation);
   if (myIncludeUncomputablesAsLiterals) {
     JDOMExternalizerUtil.writeField(element, INCLUDE_UNCOMPUTABLES_AS_LITERALS, "true");
   }
   if (mySourceModificationAllowed) {
     JDOMExternalizerUtil.writeField(element, SOURCE_MODIFICATION_ALLOWED, "true");
   }
   switch (myDfaOption) {
     case OFF:
       break;
     case RESOLVE:
       JDOMExternalizerUtil.writeField(element, RESOLVE_REFERENCES, Boolean.TRUE.toString());
       break;
     case ASSIGNMENTS:
       JDOMExternalizerUtil.writeField(
           element, LOOK_FOR_VAR_ASSIGNMENTS, Boolean.TRUE.toString());
       break;
     case DFA:
       JDOMExternalizerUtil.writeField(element, USE_DFA_IF_AVAILABLE, Boolean.TRUE.toString());
       break;
   }
 }
Esempio n. 3
0
  /**
   * If authorization mode is v2, then pass it through authorizer so that it can apply any security
   * configuration changes.
   */
  public void applyAuthorizationPolicy() throws HiveException {
    if (!isAuthorizationModeV2()) {
      // auth v1 interface does not have this functionality
      return;
    }

    // avoid processing the same config multiple times, check marker
    if (conf.get(CONFIG_AUTHZ_SETTINGS_APPLIED_MARKER, "").equals(Boolean.TRUE.toString())) {
      return;
    }

    authorizerV2.applyAuthorizationConfigPolicy(conf);
    // set a marker that this conf has been processed.
    conf.set(CONFIG_AUTHZ_SETTINGS_APPLIED_MARKER, Boolean.TRUE.toString());
  }
Esempio n. 4
0
  /**
   * Creates window using parameters <code>params</code> If params contain flag DELAYED doesn't do
   * anything. Note: Descendants can call this method to create the window at the time different to
   * instance construction.
   */
  protected final void init(XCreateWindowParams params) {
    awtLock();
    initialising = InitialiseState.INITIALISING;
    awtUnlock();

    try {
      if (!Boolean.TRUE.equals(params.get(DELAYED))) {
        preInit(params);
        create(params);
        postInit(params);
      } else {
        instantPreInit(params);
        delayedParams = params;
      }
      awtLock();
      initialising = InitialiseState.INITIALISED;
      awtLockNotifyAll();
      awtUnlock();
    } catch (RuntimeException re) {
      awtLock();
      initialising = InitialiseState.FAILED_INITIALISATION;
      awtLockNotifyAll();
      awtUnlock();
      throw re;
    } catch (Throwable t) {
      log.log(Level.WARNING, "Exception during peer initialization", t);
      awtLock();
      initialising = InitialiseState.FAILED_INITIALISATION;
      awtLockNotifyAll();
      awtUnlock();
    }
  }
Esempio n. 5
0
 /**
  * 判断条件是否永真
  *
  * @param expr
  * @return
  */
 public static boolean isConditionAlwaysTrue(SQLExpr expr) {
   Object o = WallVisitorUtils.getValue(expr);
   if (Boolean.TRUE.equals(o)) {
     return true;
   }
   return false;
 }
 public boolean loadInitialCheckBoxState() {
   PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject);
   return Boolean.TRUE
           .toString()
           .equals(propertiesComponent.getValue("GoToAction.toSaveAllIncluded"))
       && propertiesComponent.isTrueValue("GoToAction.allIncluded");
 }
  @Transactional(propagation = Propagation.NOT_SUPPORTED)
  public List<AccessKey> list(
      Long userId,
      String label,
      String labelPattern,
      Integer type,
      String sortField,
      Boolean sortOrderAsc,
      Integer take,
      Integer skip) {
    CriteriaBuilder cb = genericDAO.criteriaBuilder();
    CriteriaQuery<AccessKey> cq = cb.createQuery(AccessKey.class);
    Root<AccessKey> from = cq.from(AccessKey.class);

    Predicate[] predicates =
        CriteriaHelper.accessKeyListPredicates(
            cb, from, userId, ofNullable(label), ofNullable(labelPattern), ofNullable(type));
    cq.where(predicates);
    CriteriaHelper.order(cb, cq, from, ofNullable(sortField), Boolean.TRUE.equals(sortOrderAsc));

    TypedQuery<AccessKey> query = genericDAO.createQuery(cq);
    ofNullable(skip).ifPresent(query::setFirstResult);
    ofNullable(take).ifPresent(query::setMaxResults);
    genericDAO.cacheQuery(query, of(CacheConfig.bypass()));
    return query.getResultList();
  }
Esempio n. 8
0
		public void actionPerformed(ActionEvent evt)
		{
			JEditTextArea textArea = getTextArea(evt);

			int caret = textArea.getCaretPosition();

			int firstLine = textArea.getFirstLine();

			int firstOfLine = textArea.getLineStartOffset(
				textArea.getCaretLine());
			int firstVisibleLine = (firstLine == 0 ? 0 :
				firstLine + textArea.getElectricScroll());
			int firstVisible = textArea.getLineStartOffset(
				firstVisibleLine);

			if(caret == 0)
			{
				textArea.getToolkit().beep();
				return;
			}
			else if(!Boolean.TRUE.equals(textArea.getClientProperty(
				SMART_HOME_END_PROPERTY)))
				caret = firstOfLine;
			else if(caret == firstVisible)
				caret = 0;
			else if(caret == firstOfLine)
				caret = firstVisible;
			else
				caret = firstOfLine;

			if(select)
				textArea.select(textArea.getMarkPosition(),caret);
			else
				textArea.setCaretPosition(caret);
		}
  public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
    if (isReferenceTo(element)) return getElement();

    final String newName;
    if (element instanceof PsiClass) {
      PsiClass psiClass = (PsiClass) element;
      final boolean jvmFormat =
          Boolean.TRUE.equals(JavaClassReferenceProvider.JVM_FORMAT.getValue(getOptions()));
      newName = jvmFormat ? ClassUtil.getJVMClassName(psiClass) : psiClass.getQualifiedName();
    } else if (element instanceof PsiPackage) {
      PsiPackage psiPackage = (PsiPackage) element;
      newName = psiPackage.getQualifiedName();
    } else {
      throw new IncorrectOperationException("Cannot bind to " + element);
    }
    assert newName != null;

    TextRange range =
        new TextRange(
            myJavaClassReferenceSet.getReference(0).getRangeInElement().getStartOffset(),
            getRangeInElement().getEndOffset());
    final ElementManipulator<PsiElement> manipulator = getManipulator(getElement());
    if (manipulator != null) {
      final PsiElement finalElement = manipulator.handleContentChange(getElement(), range, newName);
      range = new TextRange(range.getStartOffset(), range.getStartOffset() + newName.length());
      myJavaClassReferenceSet.reparse(finalElement, range);
      return finalElement;
    }
    return element;
  }
Esempio n. 10
0
 public void saveInitialCheckBoxState(boolean state) {
   PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject);
   if (Boolean.TRUE
       .toString()
       .equals(propertiesComponent.getValue("GoToAction.toSaveAllIncluded"))) {
     propertiesComponent.setValue("GoToAction.allIncluded", Boolean.toString(state));
   }
 }
  /**
   * If we are in a constructor, that is static compiled, but in a class, that is not, it may happen
   * that init code from object initializers, fields or properties is added into the constructor
   * code. The backend assumes a purely static contructor, so it may fail if it encounters dynamic
   * code here. Thus we make this kind of code fail
   */
  private void checkForConstructorWithCSButClassWithout(MethodNode node) {
    if (!(node instanceof ConstructorNode)) return;
    Object meta = node.getNodeMetaData(STATIC_COMPILE_NODE);
    if (!Boolean.TRUE.equals(meta)) return;
    ClassNode clz = typeCheckingContext.getEnclosingClassNode();
    meta = clz.getNodeMetaData(STATIC_COMPILE_NODE);
    if (Boolean.TRUE.equals(meta)) return;
    if (clz.getObjectInitializerStatements().isEmpty()
        && clz.getFields().isEmpty()
        && clz.getProperties().isEmpty()) {
      return;
    }

    addStaticTypeError(
        "Cannot statically compile constructor implicitly including non static elements from object initializers, properties or fields.",
        node);
  }
 /** @see org.eclipse.jface.preference.PreferencePage#applyData(java.lang.Object) */
 public void applyData(Object data) {
   if (data instanceof Map) {
     fPageData = (Map) data;
     if (link != null && fPageData.containsKey(NO_LINK)) {
       link.setVisible(!Boolean.TRUE.equals(((Map) data).get(NO_LINK)));
     }
   }
 }
Esempio n. 13
0
 static boolean hasOpaqueBeenExplicitlySet(final JComponent c) {
   final Method method = getJComponentGetFlagMethod.get();
   if (method == null) return false;
   try {
     return Boolean.TRUE.equals(method.invoke(c, OPAQUE_SET_FLAG));
   } catch (final Throwable ignored) {
     return false;
   }
 }
  public SolrInputDocument toContactSolrDocument(
      ContactDTO contactDTO, String docType, SolrIdPrefix solrIdPrefix) throws Exception {
    PingyinInfo pingyinInfo = null;
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", solrIdPrefix + "_" + contactDTO.getId());
    doc.addField("doc_type", docType);
    doc.addField("shop_id", this.shop_id);
    doc.addField("customer_or_supplier_id", this.id);

    String name = this.name;
    if (StringUtils.isBlank(name)) {
      name = contactDTO.getName();
    }
    doc.addField("name", name);
    if (StringUtils.isNotBlank(name)) {
      pingyinInfo = PinyinUtil.getPingyinInfo(name);
      this.name_fl = pingyinInfo.firstLetters;
      this.name_py = pingyinInfo.pingyin;
      this.name_fl_sort = pingyinInfo.firstLetter;
      doc.addField("name_fl", name_fl);
      doc.addField("name_py", name_py);
      doc.addField("name_fl_sort", name_fl_sort);
    }

    if (StringUtils.isNotBlank(contactDTO.getName())) {
      doc.addField("contact", contactDTO.getName());
      pingyinInfo = PinyinUtil.getPingyinInfo(contactDTO.getName());
      String contact_fl = pingyinInfo.firstLetters;
      String contact_py = pingyinInfo.pingyin;
      doc.addField("contact_fl", contact_fl);
      doc.addField("contact_py", contact_py);
    }
    if (StringUtils.isNotBlank(contactDTO.getMobile())) {
      doc.addField("mobile", contactDTO.getMobile());
    }
    List<ContactGroupType> contactGroupTypeList = new ArrayList<ContactGroupType>();
    if ("customer".equals(this.getCustomer_or_supplier())) {
      contactGroupTypeList.add(ContactGroupType.CUSTOMER);
    }
    if ("supplier".equals(this.getCustomer_or_supplier())) {
      contactGroupTypeList.add(ContactGroupType.SUPPLIER);
    }
    if (StringUtils.isNotBlank(this.getMember_no())) {
      contactGroupTypeList.add(ContactGroupType.MEMBER);
    }
    if (Boolean.TRUE.equals(contactDTO.getApp())) {
      contactGroupTypeList.add(ContactGroupType.APP_CUSTOMER);
    }
    if (CollectionUtils.isNotEmpty(contactGroupTypeList)) {
      for (ContactGroupType contactGroupType : contactGroupTypeList) {
        doc.addField("contact_group_type", contactGroupType);
      }
    } else {
      doc.addField("contact_group_type", ContactGroupType.OTHERS);
    }
    return doc;
  }
Esempio n. 15
0
 /**
  * Checks whether the specified component or one of its ancestors has the specified client
  * property set to {@link Boolean#TRUE}.
  *
  * @param c Component.
  * @param clientPropName Client property name.
  * @return <code>true</code> if the specified component or one of its ancestors has the
  *     specified client property set to {@link Boolean#TRUE}, <code>false</code> otherwise.
  */
 private boolean hasClientPropertySetToTrue(Component c, String clientPropName) {
   while (c != null) {
     if (c instanceof JComponent) {
       JComponent jc = (JComponent) c;
       if (Boolean.TRUE.equals(jc.getClientProperty(clientPropName))) return true;
     }
     c = c.getParent();
   }
   return false;
 }
 /**
  * Executes a {@link Function} on each item in a Collection and collects all the entries for which
  * the result of the function is equal to {@link Boolean} <tt>true</tt>.
  *
  * @param collection the collection to process
  * @param func the Function to execute
  * @return a list of objects for which the function was true
  */
 public static List select(Collection collection, Function func) {
   List result = new ArrayList();
   for (Iterator i = collection.iterator(); i.hasNext(); ) {
     Object item = i.next();
     if (Boolean.TRUE.equals(func.execute(item))) {
       result.add(item);
     }
   }
   return result;
 }
    private boolean closeQuery() {
      final RunContentDescriptor descriptor = getRunContentDescriptorByContent(myContent);

      if (descriptor == null) {
        return true;
      }

      final ProcessHandler processHandler = descriptor.getProcessHandler();
      if (processHandler == null
          || processHandler.isProcessTerminated()
          || processHandler.isProcessTerminating()) {
        return true;
      }
      final boolean destroyProcess;
      if (processHandler.isSilentlyDestroyOnClose()
          || Boolean.TRUE.equals(
              processHandler.getUserData(ProcessHandler.SILENTLY_DESTROY_ON_CLOSE))) {
        destroyProcess = true;
      } else {
        // todo[nik] this is a temporary solution for the following problem: some configurations
        // should not allow user to choose between 'terminating' and 'detaching'
        final boolean useDefault =
            Boolean.TRUE.equals(
                processHandler.getUserData(ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY));
        final TerminateRemoteProcessDialog terminateDialog =
            new TerminateRemoteProcessDialog(
                myProject,
                descriptor.getDisplayName(),
                processHandler.detachIsDefault(),
                useDefault);
        terminateDialog.show();
        if (terminateDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) return false;
        destroyProcess = terminateDialog.forceTermination();
      }
      if (destroyProcess) {
        processHandler.destroyProcess();
      } else {
        processHandler.detachProcess();
      }
      waitForProcess(descriptor);
      return true;
    }
 static boolean shouldLoadPlugins() {
   try {
     // no plugins during bootstrap
     Class.forName("com.intellij.openapi.extensions.Extensions");
   } catch (ClassNotFoundException e) {
     return false;
   }
   //noinspection HardCodedStringLiteral
   final String loadPlugins = System.getProperty("idea.load.plugins");
   return loadPlugins == null || Boolean.TRUE.toString().equals(loadPlugins);
 }
Esempio n. 19
0
  public StubTree calcStubTree() {
    FileElement fileElement = calcTreeElement();
    synchronized (myStubFromTreeLock) {
      SoftReference<StubTree> ref = fileElement.getUserData(STUB_TREE_IN_PARSED_TREE);
      StubTree tree = SoftReference.dereference(ref);

      if (tree == null) {
        ApplicationManager.getApplication().assertReadAccessAllowed();
        IElementType contentElementType = getContentElementType();
        if (!(contentElementType instanceof IStubFileElementType)) {
          VirtualFile vFile = getVirtualFile();
          String message =
              "ContentElementType: "
                  + contentElementType
                  + "; file: "
                  + this
                  + "\n\t"
                  + "Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = "
                  + Boolean.TRUE.equals(getUserData(BUILDING_STUB))
                  + "\n\t"
                  + "getTreeElement() = "
                  + getTreeElement()
                  + "\n\t"
                  + "vFile instanceof VirtualFileWithId = "
                  + (vFile instanceof VirtualFileWithId)
                  + "\n\t"
                  + "StubUpdatingIndex.canHaveStub(vFile) = "
                  + StubTreeLoader.getInstance().canHaveStub(vFile);
          rebuildStub();
          throw new AssertionError(message);
        }

        StubElement currentStubTree =
            ((IStubFileElementType) contentElementType).getBuilder().buildStubTree(this);
        if (currentStubTree == null) {
          throw new AssertionError(
              "Stub tree wasn't built for " + contentElementType + "; file: " + this);
        }

        tree = new StubTree((PsiFileStub) currentStubTree);
        tree.setDebugInfo("created in calcStubTree");
        try {
          TreeUtil.bindStubsToTree(this, tree);
        } catch (TreeUtil.StubBindingException e) {
          rebuildStub();
          throw new RuntimeException("Stub and PSI element type mismatch in " + getName(), e);
        }

        fileElement.putUserData(STUB_TREE_IN_PARSED_TREE, new SoftReference<StubTree>(tree));
      }

      return tree;
    }
  }
 public boolean isUpToDate(final Change change) {
   final List<File> files = ChangesUtil.getIoFilesFromChanges(Collections.singletonList(change));
   synchronized (myLock) {
     for (File file : files) {
       final String path = file.getAbsolutePath();
       final Pair<Boolean, VcsRoot> data = myChanged.get(path);
       if (data != null && Boolean.TRUE.equals(data.getFirst())) return false;
     }
   }
   return true;
 }
Esempio n. 21
0
  public void run() {
    Deque<VisitingContext> stack = new ArrayDeque<>();

    stack.add(new VisitingContext(rootNode));
    boolean goOn = stack.peek().hasNext();

    if (goOn) {
      do {
        Map.Entry<String, JsonValue> current = stack.peek().nextElement();

        if (!(current.getValue() instanceof JsonStructure)) {
          String key = stack.peek().getNSPrefix() + current.getKey();
          String value = null;
          JsonValue jsonValue = current.getValue();
          switch (jsonValue.getValueType()) {
            case NULL:
              value = null;
              break;
            case FALSE:
              value = Boolean.FALSE.toString();
              break;
            case TRUE:
              Boolean.TRUE.toString();
              break;
            case NUMBER:
              value = jsonValue.toString();
              break;
            case STRING:
              value = ((JsonString) jsonValue).getString();
              break;
            default:
              throw new ConfigException("Internal failure while processing JSON document.");
          }

          targetStore.put(key, value);
        } else if (current.getValue() instanceof JsonObject) {
          String key = stack.peek().getNSPrefix() + current.getKey();
          JsonObject node = (JsonObject) current.getValue();
          stack.push(new VisitingContext(node, key));
        } else if (current.getValue() instanceof JsonArray) {
          throw new ConfigException("Arrays are not supported at the moment.");
        } else {
          throw new ConfigException("Internal failure while processing JSON document.");
        }

        goOn = stack.peek().hasNext();

        while (!goOn && stack.size() > 0) {
          stack.remove();
          goOn = (stack.size() > 0) && stack.peek().hasNext();
        }
      } while (goOn);
    }
  }
Esempio n. 22
0
 private static NCube prepareCube(NCube cube) {
   applyAdvices(cube.getApplicationID(), cube);
   String cubeName = cube.getName().toLowerCase();
   if (!cube.getMetaProperties().containsKey("cache")
       || Boolean.TRUE.equals(
           cube.getMetaProperty(
               "cache"))) { // Allow cubes to not be cached by specified 'cache':false as a cube
                            // meta-property.
     getCacheForApp(cube.getApplicationID()).put(cubeName, cube);
   }
   return cube;
 }
  private boolean getAddedFilesPlaceOption() {
    final SvnConfiguration configuration = SvnConfiguration.getInstance(myVcs.getProject());
    boolean add = Boolean.TRUE.equals(configuration.isKeepNewFilesAsIsForTreeConflictMerge());
    if (configuration.isKeepNewFilesAsIsForTreeConflictMerge() != null) {
      return add;
    }
    if (!containAdditions(myTheirsChanges) && !containAdditions(myTheirsBinaryChanges)) {
      return false;
    }
    return Messages.YES
        == MessageDialogBuilder.yesNo(
                TreeConflictRefreshablePanel.TITLE,
                "Keep newly created file(s) in their original place?")
            .yesText("Keep")
            .noText("Move")
            .doNotAsk(
                new DialogWrapper.DoNotAskOption() {
                  @Override
                  public boolean isToBeShown() {
                    return true;
                  }

                  @Override
                  public void setToBeShown(boolean value, int exitCode) {
                    if (!value) {
                      if (exitCode == 0) {
                        // yes
                        configuration.setKeepNewFilesAsIsForTreeConflictMerge(true);
                      } else {
                        configuration.setKeepNewFilesAsIsForTreeConflictMerge(false);
                      }
                    }
                  }

                  @Override
                  public boolean canBeHidden() {
                    return true;
                  }

                  @Override
                  public boolean shouldSaveOptionsOnCancel() {
                    return true;
                  }

                  @NotNull
                  @Override
                  public String getDoNotShowMessage() {
                    return CommonBundle.message("dialog.options.do.not.ask");
                  }
                })
            .show();
  }
Esempio n. 24
0
  private int attemptPrecompiledScriptExecute(
      CommandLine commandLine,
      String scriptName,
      String env,
      GantBinding binding,
      List<File> allScripts) {
    console.updateStatus("Running pre-compiled script");

    // Must be called before the binding is initialised.
    setRunningEnvironment(commandLine, env);

    // Get Gant to load the class by name using our class loader.
    ScriptBindingInitializer bindingInitializer =
        new ScriptBindingInitializer(
            commandLine, classLoader, settings, pluginPathSupport, isInteractive);
    Gant gant = new Gant(bindingInitializer.initBinding(binding, scriptName), classLoader);

    try {
      loadScriptClass(gant, scriptName);
    } catch (ScriptNotFoundException e) {
      if (!isInteractive || InteractiveMode.isActive()) {
        throw e;
      }
      scriptName = fixScriptName(scriptName, allScripts);
      if (scriptName == null) {
        throw e;
      }

      try {
        loadScriptClass(gant, scriptName);
      } catch (ScriptNotFoundException ce) {
        return executeScriptWithCaching(commandLine, scriptName, env);
      }

      // at this point if they were calling a script that has a non-default
      // env (e.g. war or test-app) it wouldn't have been correctly set, so
      // set it now, but only if they didn't specify the env (e.g. "grails test war" -> "grails test
      // war")

      if (Boolean.TRUE.toString().equals(System.getProperty(Environment.DEFAULT))) {
        commandLine.setCommand(GrailsNameUtils.getScriptName(scriptName));
        env = commandLine.lookupEnvironmentForCommand();
        binding.setVariable("grailsEnv", env);
        settings.setGrailsEnv(env);
        System.setProperty(Environment.KEY, env);
        settings.setDefaultEnv(false);
        System.setProperty(Environment.DEFAULT, Boolean.FALSE.toString());
      }
    }

    return executeWithGantInstance(gant, DO_NOTHING_CLOSURE, binding).exitCode;
  }
  public void reverseDirection() {
    Boolean direction = (Boolean) _logicalContext.get(MESSAGE_OUTBOUND_PROPERTY);

    if (direction != null) {
      if (Boolean.TRUE.equals(direction)) {
        _logicalContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.FALSE);
        _soapContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.FALSE);
      } else {
        _logicalContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE);
        _soapContext.put(MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE);
      }
    }
  }
Esempio n. 26
0
  /**
   * 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题.
   *
   * @param callable
   * @return 通过future.get()获取返回结果.
   */
  @SuppressWarnings("unchecked")
  public <T> Future<T> asyncCall(Callable<T> callable) {
    try {
      try {
        setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString());
        final T o = callable.call();
        // local调用会直接返回结果.
        if (o != null) {
          FutureTask<T> f =
              new FutureTask<T>(
                  new Callable<T>() {
                    public T call() throws Exception {
                      return o;
                    }
                  });
          f.run();
          return f;
        } else {

        }
      } catch (Exception e) {
        throw new RpcException(e);
      } finally {
        removeAttachment(Constants.ASYNC_KEY);
      }
    } catch (final RpcException e) {
      return new Future<T>() {
        public boolean cancel(boolean mayInterruptIfRunning) {
          return false;
        }

        public boolean isCancelled() {
          return false;
        }

        public boolean isDone() {
          return true;
        }

        public T get() throws InterruptedException, ExecutionException {
          throw new ExecutionException(e.getCause());
        }

        public T get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
          return get();
        }
      };
    }
    return ((Future<T>) getContext().getFuture());
  }
Esempio n. 27
0
  /** Main client entry point for stand-alone operation. */
  public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d [%-25t] %-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option output = parser.addStringOption('o', "output");
    CmdLineParser.Option iface = parser.addStringOption('i', "iface");

    try {
      parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
      System.err.println(oe.getMessage());
      usage(System.err);
      System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals(parser.getOptionValue(help))) {
      usage(System.out);
      System.exit(0);
    }

    String outputValue = (String) parser.getOptionValue(output, DEFAULT_OUTPUT_DIRECTORY);
    String ifaceValue = (String) parser.getOptionValue(iface);

    String[] otherArgs = parser.getRemainingArgs();
    if (otherArgs.length != 1) {
      usage(System.err);
      System.exit(1);
    }

    try {
      Client c = new Client(getIPv4Address(ifaceValue));
      SharedTorrent torrent =
          SharedTorrent.fromFile(new File(otherArgs[0]), new File(outputValue), false);
      c.addTorrent(torrent);

      // Set a shutdown hook that will stop the sharing/seeding and send
      // a STOPPED announce request.
      Runtime.getRuntime().addShutdownHook(new Thread(new ClientShutdown(c, null)));

      c.share();
      if (ClientState.ERROR.equals(torrent.getClientState())) {
        System.exit(1);
      }
    } catch (Exception e) {
      logger.error("Fatal error: {}", e.getMessage(), e);
      System.exit(2);
    }
  }
Esempio n. 28
0
    // {{{ setValueAt() method
    @Override
    public void setValueAt(Object aValue, int row, int column) {
      if (column != 0) return;

      Object obj = filteredEntries.get(row);
      if (obj instanceof String) return;

      Entry entry = (Entry) obj;
      boolean before = entry.install;
      entry.install = Boolean.TRUE.equals(aValue);
      if (before == entry.install) return;
      if (!entry.install) deselectParents(entry);

      List<PluginList.Dependency> deps = entry.plugin.getCompatibleBranch().deps;

      for (int i = 0; i < deps.size(); i++) {
        PluginList.Dependency dep = deps.get(i);
        if ("plugin".equals(dep.what)) {
          boolean found = false;
          for (int j = 0; j < filteredEntries.size(); j++) {
            Entry temp = (Entry) filteredEntries.get(j);
            if (temp.plugin == dep.plugin) {
              found = true;
              if (entry.install) {
                temp.parents.add(entry);
                setValueAt(Boolean.TRUE, j, 0);
              } else temp.parents.remove(entry);

              break;
            }
          }
          if (!found) {
            // the dependency was not found in the filtered list so we search in
            // global list.
            for (int a = 0; a < entries.size(); a++) {
              Entry temp = (Entry) entries.get(a);
              if (temp.plugin == dep.plugin) {
                if (entry.install) {
                  temp.parents.add(entry);
                  temp.install = true;
                } else temp.parents.remove(entry);
                break;
              }
            }
          }
        }
      }
      updateFilteredEntries();
    } // }}}
Esempio n. 29
0
 @Override
 public String correctObjectName(
     final String objectName, final Class<? extends DatabaseObject> objectType) {
   if (quotingStrategy == ObjectQuotingStrategy.QUOTE_ALL_OBJECTS
       || unquotedObjectsAreUppercased == null
       || objectName == null
       || (objectName.startsWith(quotingStartCharacter)
           && objectName.endsWith(quotingEndCharacter))) {
     return objectName;
   } else if (Boolean.TRUE.equals(unquotedObjectsAreUppercased)) {
     return objectName.toUpperCase();
   } else {
     return objectName.toLowerCase();
   }
 }
  public GeneralHighlightingPass(
      @NotNull Project project,
      @NotNull PsiFile file,
      @NotNull Document document,
      int startOffset,
      int endOffset,
      boolean updateAll,
      @NotNull ProperTextRange priorityRange,
      @Nullable Editor editor) {
    super(project, document, PRESENTABLE_NAME, file, true);
    myStartOffset = startOffset;
    myEndOffset = endOffset;
    myUpdateAll = updateAll;
    myPriorityRange = priorityRange;
    myEditor = editor;

    LOG.assertTrue(file.isValid());
    setId(Pass.UPDATE_ALL);
    myHasErrorElement =
        !isWholeFileHighlighting() && Boolean.TRUE.equals(myFile.getUserData(HAS_ERROR_ELEMENT));
    FileStatusMap fileStatusMap =
        ((DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(myProject)).getFileStatusMap();
    myErrorFound = !isWholeFileHighlighting() && fileStatusMap.wasErrorFound(myDocument);

    myApplyCommand =
        new Runnable() {
          @Override
          public void run() {
            ProperTextRange range = new ProperTextRange(myStartOffset, myEndOffset);
            MarkupModel model = DocumentMarkupModel.forDocument(myDocument, myProject, true);
            UpdateHighlightersUtil.cleanFileLevelHighlights(myProject, Pass.UPDATE_ALL, myFile);
            final EditorColorsScheme colorsScheme = getColorsScheme();
            UpdateHighlightersUtil.setHighlightersInRange(
                myProject,
                myDocument,
                range,
                colorsScheme,
                myHighlights,
                (MarkupModelEx) model,
                Pass.UPDATE_ALL);
          }
        };

    // initial guess to show correct progress in the traffic light icon
    setProgressLimit(document.getTextLength() / 2); // approx number of PSI elements = file length/2
    myGlobalScheme = EditorColorsManager.getInstance().getGlobalScheme();
  }