/*
//////////////////////////////////////////////////////////
Non-public methods
//////////////////////////////////////////////////////////
166443
@Override
    protected XMLValidationSchema loadSchema(InputSource src, Object sysRef)
        throws XMLStreamException
    {
        /* 26-Oct-2007, TSa: Are sax parser factories safe to share?
         *   If not, should just create new instances for each
         *   parsed schema.
         */
        SAXParserFactory saxFactory = getSaxFactory();

        MyGrammarController ctrl = new MyGrammarController();
        XMLSchemaGrammar grammar = XMLSchemaReader.parse(src, saxFactory, ctrl);
        if (grammar == null) {
            String msg = "Failed to load W3C Schema from '"+sysRef+"'";
            String emsg = ctrl.mErrorMsg;
            if (emsg != null) {
                msg = msg + ": "+emsg;
            }
            throw new XMLStreamException(msg);
        }
        return new W3CSchema(grammar);
    }
126459
void initInputsByIdMap() {
    inputsById.clear();
    for (CompilerInput input : externs) {
      InputId id = input.getInputId();
      CompilerInput previous = putCompilerInput(id, input);
      if (previous != null) {
        report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName()));
      }
    }
    for (CompilerInput input : moduleGraph.getAllInputs()) {
      InputId id = input.getInputId();
      CompilerInput previous = putCompilerInput(id, input);
      if (previous != null) {
        report(JSError.make(DUPLICATE_INPUT, input.getName()));
      }
    }
  }
456962
@Override
    protected void checkParameters() {
        super.checkParameters();

        if (outputFile == null) {
            throw new BuildException("output attribute is required", getLocation());
        }

        if (inputFile == null) {
            throw new BuildException("inputFile element is required");
        }

        checkBoolean(withMessages, "withMessages");
        checkBoolean(resetSource, "resetSource");
    }
1049972
public static void main(String[] args) throws ClassNotFoundException {
        LogConfig.initMinimal();
        if (args.length < 4 || args.length > 7) {
            die("Expected 4 to 7 arguments", true);
        }
        File sourceDir = new File(args[0]);
        if (!sourceDir.isDirectory()) {
            die("Not a directory: " + sourceDir.getPath(), false);
        }
        File destDir = new File(args[1]);

        @SuppressWarnings("unchecked")
        Class<DODeserializer> deserializer = (Class<DODeserializer>) Class.forName(args[2]);
        @SuppressWarnings("unchecked")
        Class<DOSerializer> serializer = (Class<DOSerializer>) Class.forName(args[3]);

        // So DOTranslationUtility works...
        System.setProperty("fedora.hostname", "localhost");
        System.setProperty("fedora.port", "8080");
        System.setProperty("fedora.appServerContext", Constants.FEDORA_DEFAULT_APP_CONTEXT);

        boolean pretty = args.length > 4 && args[4].equals("true");

        String inExt = "xml";
        if (args.length > 5) inExt = args[5];

        String outExt = "xml";
        if (args.length > 6) outExt = args[6];

        ConvertObjectSerialization converter =
                new ConvertObjectSerialization(deserializer,
                                               serializer,
                                               pretty,
                                               inExt,
                                               outExt);
        converter.convert(sourceDir, destDir);

        TripleIteratorFactory.defaultInstance().shutdown();
    }
445318
protected final void init() {

    Type genericComponentType = null;
    Type genericKeyType = null;
    if (this.type instanceof GenericArrayType) {
      GenericArrayType arrayType = (GenericArrayType) this.type;
      genericComponentType = arrayType.getGenericComponentType();
    }
    if (genericComponentType == null) {
      TypeVariable<?> keyTypeVariable = null;
      TypeVariable<?> componentTypeVariable = null;
      if (this.retrievalClass.isArray()) {
        genericComponentType = this.retrievalClass.getComponentType();
      } else if (Collection.class.isAssignableFrom(this.retrievalClass)) {
        componentTypeVariable = CommonTypeVariables.TYPE_VARIABLE_COLLECTION_ELEMENT;
      } else if (Map.class.isAssignableFrom(this.retrievalClass)) {
        componentTypeVariable = CommonTypeVariables.TYPE_VARIABLE_MAP_VALUE;
        keyTypeVariable = CommonTypeVariables.TYPE_VARIABLE_MAP_KEY;
      }
      if (componentTypeVariable != null) {
        genericComponentType = resolveTypeVariable(componentTypeVariable, this);
        if (genericComponentType == null) {
          genericComponentType = componentTypeVariable;
        }
      }
      if (keyTypeVariable != null) {
        genericKeyType = resolveTypeVariable(keyTypeVariable, this);
        if (genericKeyType == null) {
          genericKeyType = keyTypeVariable;
        }
      }
    }
    if (genericComponentType == null) {
      this.componentType = null;
    } else {
      this.componentType = create(genericComponentType, this.definingType);
    }
    if (genericKeyType == null) {
      this.keyType = null;
    } else {
      this.keyType = create(genericKeyType, this.definingType);
    }
  }
507142
@Override
  @SuppressWarnings("unchecked")
  public void initialize() {
    LOG.initializeExecution(this);

    ScopeImpl scope = getScopeActivity();
    ensureParentInitialized();

    List<VariableDeclaration> variableDeclarations = (List<VariableDeclaration>) scope.getProperty(BpmnParse.PROPERTYNAME_VARIABLE_DECLARATIONS);
    if (variableDeclarations != null) {
      for (VariableDeclaration variableDeclaration : variableDeclarations) {
        variableDeclaration.initialize(this, parent);
      }
    }

    if (isProcessInstanceExecution()) {
      String initiatorVariableName = (String) processDefinition.getProperty(BpmnParse.PROPERTYNAME_INITIATOR_VARIABLE_NAME);
      if (initiatorVariableName != null) {
        String authenticatedUserId = Context.getCommandContext().getAuthenticatedUserId();
        setVariable(initiatorVariableName, authenticatedUserId);
      }
    }

    // create event subscriptions for the current scope
    for (EventSubscriptionDeclaration declaration : EventSubscriptionDeclaration.getDeclarationsForScope(scope).values()) {
      if(!declaration.isStartEvent()) {
        declaration.createSubscriptionForExecution(this);
      }
    }
  }
573770
@Override
    public final String optString(final String key, final String defaultValue) {
        String result = optString(key);
        return result == null ? defaultValue : result;
    }
1006943
@Override
    public void init(NamedList args) {

        Object regex = args.remove(PARAM_REGEX);
        if (null == regex) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REGEX);
        }
        try {
            m_regex = Pattern.compile(regex.toString());
        } catch (PatternSyntaxException e) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Invalid regex: " + regex, e);
        }

        Object replacement = args.remove(PARAM_REPLACEMENT);
        if (null == replacement) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REPLACEMENT);
        }
        m_replacement = replacement.toString();

        Object source = args.remove(PARAM_SOURCE);
        if (null == source) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_SOURCE);
        }
        m_source = source.toString();

        Object target = args.remove(PARAM_TARGET);
        if (null == target) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_TARGET);
        }
        m_target = target.toString();

    }
1289783
private void recurseAndAddFiles(GraphRewrite event, FileService fileService, WindupJavaConfigurationService javaConfigurationService, FileModel file)
    {
        if (javaConfigurationService.checkIfIgnored(event, file))
            return;

        String filePath = file.getFilePath();
        File fileReference = new File(filePath);
        Long directorySize = new Long(0);

        if (fileReference.isDirectory())
        {
            File[] subFiles = fileReference.listFiles();
            if (subFiles != null)
            {
                for (File reference : subFiles)
                {
                    FileModel subFile = fileService.createByFilePath(file, reference.getAbsolutePath());
                    recurseAndAddFiles(event, fileService, javaConfigurationService, subFile);
                    if (subFile.isDirectory())
                    {
                        directorySize = directorySize + subFile.getDirectorySize();
                    }
                    else
                    {
                        directorySize = directorySize + subFile.getSize();
                    }
                }
            }
            file.setDirectorySize(directorySize);
        }
    }
175690
@Override
    public void contextInitialized(ServletContextEvent evt) {
        File usersDir = new File(SetupOptions.getBaseConfigDirectory(), "users");
        if (!usersDir.isDirectory()) {
            return;
        }
        DocumentBuilder domBuilder = null;
        try {
            domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGR.warning(e.getMessage());
            return;
        }
        DOMImplementationLS lsFactory = buildDOM3LoadAndSaveFactory();
        LSSerializer serializer = lsFactory.createLSSerializer();
        serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
        serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
        LSOutput output = lsFactory.createLSOutput();
        output.setEncoding("UTF-8");
        for (File userDir : usersDir.listFiles()) {
            File userFile = new File(userDir, "user.xml");
            if (!userFile.isFile()) {
                continue;
            }
            try {
                Document doc = domBuilder.parse(userFile);
                Node pwNode = doc.getElementsByTagName("password").item(0);
                if (null == pwNode) {
                    continue;
                }
                String password = pwNode.getTextContent();
                if (password.split(":").length == 5) {
                    break;
                }
                pwNode.setTextContent(PasswordStorage.createHash(password));
                // overwrite contents of file
                // Fortify Mod: Make sure that the output stream is closed
                // output.setByteStream(new FileOutputStream(userFile, false));
                FileOutputStream os = new FileOutputStream(userFile, false);
                output.setByteStream(os);
                serializer.write(doc, output);
                os.close();
            } catch (Exception e) {
                LOGR.info(e.getMessage());
                continue;
            }
        }
    }
340663
static void forEachColumnInContentValue(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, String columnSetString, boolean generateColumnNameCheck, OnColumnListener listener) {
		methodBuilder.beginControlFlow("for (String columnName:$L)", columnSetString);
		if (generateColumnNameCheck) {
			methodBuilder.beginControlFlow("if (!$L.contains(columnName))", method.contentProviderMethodName + "ColumnSet");
			methodBuilder.addStatement("throw new $T(String.format(\"For URI '$L', column '%s' does not exists in table '%s' or can not be defined in this $L operation\", columnName, $S ))",
					KriptonRuntimeException.class, method.contentProviderUriTemplate, method.jql.operationType, method.getEntity().getTableName());
			methodBuilder.endControlFlow();
		}
		if (listener != null)
			listener.onColumnCheck(methodBuilder, "columnName");
		methodBuilder.endControlFlow();
	}
1296870
@Override
    public void init() throws ServletException {

        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_INIT_WEBDAV_SERVLET_0));
        }

        String value = null;

        // init parameter: listings
        try {
            value = getServletConfig().getInitParameter(INIT_PARAM_LIST);
            if (value != null) {
                m_listings = Boolean.valueOf(value).booleanValue();
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(
                    Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_LIST, value),
                    e);
            }
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(
                Messages.get().getBundle().key(
                    Messages.LOG_READ_INIT_PARAM_2,
                    INIT_PARAM_LIST,
                    Boolean.valueOf(m_listings)));
        }

        // init parameter: read only
        try {
            value = getServletConfig().getInitParameter(INIT_PARAM_READONLY);
            if (value != null) {
                m_readOnly = Boolean.valueOf(value).booleanValue();
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(
                    Messages.get().getBundle().key(Messages.LOG_READ_INIT_PARAM_ERROR_2, INIT_PARAM_READONLY, value),
                    e);
            }
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(
                Messages.get().getBundle().key(
                    Messages.LOG_READ_INIT_PARAM_2,
                    INIT_PARAM_READONLY,
                    Boolean.valueOf(m_readOnly)));
        }

        // Load the MD5 helper used to calculate signatures.
        try {
            m_md5Helper = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0), e);
            }

            throw new UnavailableException(Messages.get().getBundle().key(Messages.ERR_MD5_NOT_AVAILABLE_0));
        }

        // Instantiate repository from init-param
        String repositoryName = getInitParameter(INIT_PARAM_REPOSITORY);
        if (repositoryName == null) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY));
            }

            throw new ServletException(
                Messages.get().getBundle().key(Messages.ERR_INIT_PARAM_MISSING_1, INIT_PARAM_REPOSITORY));
        }

        m_repository = OpenCms.getRepositoryManager().getRepository(repositoryName, A_CmsRepository.class);
        if (m_repository == null) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName));
            }

            throw new ServletException(
                Messages.get().getBundle().key(Messages.ERR_REPOSITORY_NOT_FOUND_1, repositoryName));
        }

        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_USE_REPOSITORY_1, repositoryName));
        }
    }
1157283
@Override
	public void visit(SQLiteDaoDefinition value) throws Exception {
		currentDaoDefinition = value;

		// check if we need to generate or not
		if (value.getElement().getAnnotation(BindDaoMany2Many.class) != null && value.getElement().getAnnotation(BindGeneratedDao.class) == null) {
			return;
		}

		String classTableName = daoName(value);

		PackageElement pkg = elementUtils.getPackageOf(value.getElement());
		String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDao.class, packageName, classTableName);

		builder = TypeSpec.classBuilder(classTableName).superclass(Dao.class).addSuperinterface(typeName(value.getElement())).addModifiers(Modifier.PUBLIC);

		for (TypeName item : value.implementedInterface) {
			builder.addSuperinterface(item);
		}

		BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, classTableName), Modifier.PRIVATE);
		String entityName = BindDataSourceSubProcessor.generateEntityName(value, value.getEntity());

		// javadoc for class
		builder.addJavadoc("<p>");
		builder.addJavadoc("\nDAO implementation for entity <code>$L</code>, based on interface <code>$L</code>\n", entityName, value.getElement().getSimpleName().toString());
		builder.addJavadoc("</p>\n\n");
		JavadocUtility.generateJavadocGeneratedBy(builder);
		builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getEntityClassName()));
		builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getElement().getQualifiedName().toString()));
		builder.addJavadoc(" @see $T\n", BindTableGenerator.tableClassName(value, value.getEntity()));

		{
			// constructor
			MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(BindDaoFactoryBuilder.generateDaoFactoryClassName(value.getParent()),
					"daoFactory");
			methodBuilder.addStatement("super(daoFactory.context())");

			if (value.hasRelations()) {
				methodBuilder.addStatement("this.daoFactory=daoFactory");
				builder.addField(BindDaoFactoryBuilder.generateDaoFactoryClassName(value.getParent()), "daoFactory", Modifier.PRIVATE);
			}

			builder.addMethod(methodBuilder.build());
		}

		// define column typeName set
		for (SQLiteModelMethod item : value.getCollection()) {
			item.accept(this);
		}

		// generate live data support methods
		if (value.hasLiveData()) {
			// method sendEvent
			{
				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_EVENT).addModifiers(Modifier.PROTECTED).addParameter(Integer.TYPE, "affectedRows");
				methodBuilder.beginControlFlow("if (affectedRows==0)");
				methodBuilder.addStatement("return");
				methodBuilder.endControlFlow();

				methodBuilder.beginControlFlow("if (_context.isInSession())");
				methodBuilder.addStatement("_context.registrySQLEvent($T.$L)", BindDataSourceBuilder.generateDataSourceName(value.getParent()), value.daoUidName);
				methodBuilder.nextControlFlow("else");
				methodBuilder.addStatement("invalidateLiveData()");
				methodBuilder.endControlFlow();

				builder.addMethod(methodBuilder.build());
			}

			// field liveDatas
			{
				FieldSpec.Builder liveDataBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Collection.class),
						ParameterizedTypeName.get(ClassName.get(WeakReference.class),
								// ParameterizedTypeName.get(ClassName.get(LiveDataHandler.class),
								// WildcardTypeName.subtypeOf(Object.class)))),
								ClassName.get(LiveDataHandler.class))),
						"liveDatas").addModifiers(Modifier.STATIC)
						.initializer(CodeBlock.builder().add("new $T()", ParameterizedTypeName.get(ClassName.get(CopyOnWriteArraySet.class),
								ParameterizedTypeName.get(ClassName.get(WeakReference.class), ClassName.get(LiveDataHandler.class)))).build());
				builder.addField(liveDataBuilder.build());
			}

			// registryLiveData
			{
				// .addParameter(ParameterizedTypeName.get(ClassName.get(LiveDataHandler.class),
				// WildcardTypeName.subtypeOf(Object.class)), "value");
				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_LIVE_DATA).addModifiers(Modifier.PROTECTED).addParameter(ClassName.get(LiveDataHandler.class),
						"value");
				methodBuilder.addStatement("liveDatas.add(new $T(value))", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ClassName.get(LiveDataHandler.class)));
				builder.addMethod(methodBuilder.build());
			}

			// invalidateLiveData
			{
				// check datasource and dao package must be the same, otherwise
				// invalidate must be public

				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_INVALIDATE_LIVE_DATA).addJavadoc("<p>Invalidate livedata.</p>\n\n").addModifiers(Modifier.PUBLIC);
				methodBuilder.beginControlFlow("for ($T item: liveDatas)",
						ParameterizedTypeName.get(ClassName.get(WeakReference.class),
								// ParameterizedTypeName.get(ClassName.get(KriptonLiveDataManager.getInstance().getLiveDataHandlerClazz()),
								// WildcardTypeName.subtypeOf(Object.class))));
								ClassName.get(LiveDataHandler.class)));
				methodBuilder.beginControlFlow("if (item.get()!=null)");
				methodBuilder.addStatement("item.get().invalidate()");
				methodBuilder.endControlFlow();
				methodBuilder.endControlFlow();
				builder.addMethod(methodBuilder.build());
			}

		}

		// generate serializer params
		for (Entry<TypeName, String> item : currentDaoDefinition.managedParams.entrySet()) {
			BindTransformer.checkIfIsInUnsupportedPackage(item.getKey());

			ManagedPropertyPersistenceHelper.generateParamSerializer(context, item.getValue(), item.getKey(), PersistType.BYTE);
			ManagedPropertyPersistenceHelper.generateParamParser(context, item.getValue(), item.getKey(), PersistType.BYTE);
		}

		// generate subject
		if (currentDaoDefinition.getParent().generateRx) {
			ParameterizedTypeName subjectTypeName = ParameterizedTypeName.get(ClassName.get(PublishSubject.class), ClassName.get(SQLiteEvent.class));

			// subject
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getSubject").addModifiers(Modifier.PUBLIC);
			methodBuilder.addStatement("return subject").returns(subjectTypeName);
			builder.addMethod(methodBuilder.build());

			// subject instance
			FieldSpec.Builder fieldBuilder = FieldSpec.builder(subjectTypeName, "subject", Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC).initializer("$T.create()",
					ClassName.get(PublishSubject.class));
			builder.addField(fieldBuilder.build());
		}

		// generate prepared statement cleaner
		{

			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(Void.TYPE);
			for (String item : value.preparedStatementNames) {
				methodBuilder.beginControlFlow("if ($L!=null)", item);
				methodBuilder.addStatement("$L.close()", item);
				methodBuilder.addStatement("$L=null", item);
				methodBuilder.endControlFlow();
			}

			builder.addMethod(methodBuilder.build());
		}

		TypeSpec typeSpec = builder.build();

		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
	}
121588
@Override
	public Void visitInt(int i, String p) {
		//System.out.printf(">> %s intValue: %d\n", p, i);

		if (inTasks && AnnotationAttributeType.VERSION.getValue().equals(p)) {
			// add value
			currentValue = (currentValue == null) ? new Pair<Integer, String>() : currentValue;			
			currentValue.value0=i;
			
			if (currentValue.value0!=null && StringUtils.hasText(currentValue.value1)) {
				tasks.add(currentValue);
				currentValue=null;
			}
		}

		return null;
	}
725327
@Override
	public final void onCreate(SQLiteDatabase db) {
		ConnectionSource cs = getConnectionSource();
		/*
		 * The method is called by Android database helper's get-database calls when Android detects that we need to
		 * create or update the database. So we have to use the database argument and save a connection to it on the
		 * AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource().
		 */
		DatabaseConnection conn = cs.getSpecialConnection(null);
		boolean clearSpecial = false;
		if (conn == null) {
			conn = new AndroidDatabaseConnection(db, true, cancelQueriesEnabled);
			try {
				cs.saveSpecialConnection(conn);
				clearSpecial = true;
			} catch (SQLException e) {
				throw new IllegalStateException("Could not save special connection", e);
			}
		}
		try {
			onCreate(db, cs);
		} finally {
			if (clearSpecial) {
				cs.clearSpecialConnection(conn);
			}
		}
	}
380828
public static void init(String[] args) throws UnknownHostException {
        boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;
        boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
        boolean mlst = false, mlsd = false;
        boolean lenient = false;
        long keepAliveTimeout = -1;
        int controlKeepAliveReplyTimeout = -1;
        int minParams = 5; // listings require 3 params
        String protocol = null; // SSL protocol
        String doCommand = null;
        String trustmgr = null;
        String proxyHost = null;
        int proxyPort = 80;
        String proxyUser = null;
        String proxyPassword = null;
        String username = null;
        String password = null;

        int base = 0;
        for (base = 0; base < args.length; base++) {
            if (args[base].equals("-s")) {
                storeFile = true;
            } else if (args[base].equals("-a")) {
                localActive = true;
            } else if (args[base].equals("-A")) {
                username = "anonymous";
                password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
            } else if (args[base].equals("-b")) {
                binaryTransfer = true;
            } else if (args[base].equals("-c")) {
                doCommand = args[++base];
                minParams = 3;
            } else if (args[base].equals("-d")) {
                mlsd = true;
                minParams = 3;
            } else if (args[base].equals("-e")) {
                useEpsvWithIPv4 = true;
            } else if (args[base].equals("-f")) {
                feat = true;
                minParams = 3;
            } else if (args[base].equals("-h")) {
                hidden = true;
            } else if (args[base].equals("-k")) {
                keepAliveTimeout = Long.parseLong(args[++base]);
            } else if (args[base].equals("-l")) {
                listFiles = true;
                minParams = 3;
            } else if (args[base].equals("-L")) {
                lenient = true;
            } else if (args[base].equals("-n")) {
                listNames = true;
                minParams = 3;
            } else if (args[base].equals("-p")) {
                protocol = args[++base];
            } else if (args[base].equals("-t")) {
                mlst = true;
                minParams = 3;
            } else if (args[base].equals("-w")) {
                controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
            } else if (args[base].equals("-T")) {
                trustmgr = args[++base];
            } else if (args[base].equals("-PrH")) {
                proxyHost = args[++base];
                String[] parts = proxyHost.split(":");
                if (parts.length == 2) {
                    proxyHost = parts[0];
                    proxyPort = Integer.parseInt(parts[1]);
                }
            } else if (args[base].equals("-PrU")) {
                proxyUser = args[++base];
            } else if (args[base].equals("-PrP")) {
                proxyPassword = args[++base];
            } else if (args[base].equals("-#")) {
                printHash = true;
            } else {
                break;
            }
        }

        int remain = args.length - base;
        if (username != null) {
            minParams -= 2;
        }
        if (remain < minParams) // server, user, pass, remote, local [protocol]
        {
            System.err.println(USAGE);
            System.exit(1);
        }

        String server = args[base++];
        int port = 0;
        String[] parts = server.split(":");
        if (parts.length == 2) {
            server = parts[0];
            port = Integer.parseInt(parts[1]);
        }
        if (username == null) {
            username = args[base++];
            password = args[base++];
        }

        String remote = null;
        if (args.length - base > 0) {
            remote = args[base++];
        }

        String local = null;
        if (args.length - base > 0) {
            local = args[base++];
        }

        final FTPClient ftp;
        if (protocol == null) {
            if (proxyHost != null) {
                System.out.println("Using HTTP proxy server: " + proxyHost);
                ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
            } else {
                ftp = new FTPClient();
            }
        } else {
            FTPSClient ftps;
            if (protocol.equals("true")) {
                ftps = new FTPSClient(true);
            } else if (protocol.equals("false")) {
                ftps = new FTPSClient(false);
            } else {
                String[] prot = protocol.split(",");
                if (prot.length == 1) { // Just protocol
                    ftps = new FTPSClient(protocol);
                } else { // protocol,true|false
                    ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
                }
            }
            ftp = ftps;
            if ("all".equals(trustmgr)) {
                ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
            } else if ("valid".equals(trustmgr)) {
                ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
            } else if ("none".equals(trustmgr)) {
                ftps.setTrustManager(null);
            }
        }

        if (printHash) {
            ftp.setCopyStreamListener(createListener());
        }
        if (keepAliveTimeout >= 0) {
            ftp.setControlKeepAliveTimeout(keepAliveTimeout);
        }
        if (controlKeepAliveReplyTimeout >= 0) {
            ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
        }
        ftp.setListHiddenFiles(hidden);

        // suppress login details
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        try {
            int reply;
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
            System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

            // After connection attempt, you should check the reply code to
            // verify
            // success.
            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

        __main: try {
            if (!ftp.login(username, password)) {
                ftp.logout();
                error = true;
                break __main;
            }

            System.out.println("Remote system is " + ftp.getSystemType());

            if (binaryTransfer) {
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
            } else {
                // in theory this should not be necessary as servers should
                // default to ASCII
                // but they don't all do so - see NET-500
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            if (localActive) {
                ftp.enterLocalActiveMode();
            } else {
                ftp.enterLocalPassiveMode();
            }

            ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

            if (storeFile) {
                InputStream input;

                input = new FileInputStream(local);

                ftp.storeFile(remote, input);

                input.close();
            } else if (listFiles) {
                if (lenient) {
                    FTPClientConfig config = new FTPClientConfig();
                    config.setLenientFutureDates(true);
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString());
                }
            } else if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString());
                }
            } else if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString());
                }
            } else if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            } else if (feat) {
                // boolean feature check
                if (remote != null) { // See if the command is present
                    if (ftp.hasFeature(remote)) {
                        System.out.println("Has feature: " + remote);
                    } else {
                        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                            System.out.println("FEAT " + remote + " was not detected");
                        } else {
                            System.out.println("Command failed: " + ftp.getReplyString());
                        }
                    }

                    // Strings feature check
                    String[] features = ftp.featureValues(remote);
                    if (features != null) {
                        for (String f : features) {
                            System.out.println("FEAT " + remote + "=" + f + ".");
                        }
                    } else {
                        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                            System.out.println("FEAT " + remote + " is not present");
                        } else {
                            System.out.println("Command failed: " + ftp.getReplyString());
                        }
                    }
                } else {
                    if (ftp.features()) {
                        // Command listener has already printed the output
                    } else {
                        System.out.println("Failed: " + ftp.getReplyString());
                    }
                }
            } else if (doCommand != null) {
                if (ftp.doCommand(doCommand, remote)) {
                    // Command listener has already printed the output
                    // for(String s : ftp.getReplyStrings()) {
                    // System.out.println(s);
                    // }
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            } else {
                OutputStream output;

                output = new FileOutputStream(local);

                ftp.retrieveFile(remote, output);

                output.close();
            }

            ftp.noop(); // check that control connection is working OK

            ftp.logout();
        } catch (FTPConnectionClosedException e) {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
        }

        System.exit(error ? 1 : 0);
    }
131986
@Override
    protected void parse() {
		getConnectionParam().load(getConfig());
	    getProxyParam().load(getConfig());
		getCertificateParam().load(getConfig());
		getViewParam().load(getConfig());
		getCheckForUpdatesParam().load(getConfig());
		getApiParam().load(getConfig());
		getGlobalExcludeURLParam().load(getConfig());
		getExperimentalFeaturesParam().load(getConfig());
        getDatabaseParam().load(getConfig());
        getExtensionParam().load(getConfig());
		
		String userDir = null;
		try {
			userDir = getConfig().getString(USER_DIR);
			if (userDir != null) {
				this.userDirectory = new File(userDir);
			}
		} catch (Exception e) {
			// In a previous release the userdir was set as a file
			try {
				File file = (File) getConfig().getProperty(USER_DIR);
				if (file != null && file.isDirectory()) {
					this.userDirectory = file;
				}
			} catch (Exception e1) {
				logger.error(e1.getMessage(), e1);
			}
		}
    }