text:
date: '2015-12-20 22:00:00 GMT-3'
excerpt: 'Se você tem qualquer dúvida sobre como baixar o Linux, essa página está aqui para ajudar!'
layout: post
published: true
title: 'Como baixar o Linux'
image: /files/2015/12/download-linux-firefox-1-pt.jpg
nickname: 'how-to-download-linux'
---

{% markdown %}

Se você tem qualquer dúvida sobre como baixar o Linux, essa página está aqui para ajudar!

Observe que as instruções podem variar de acordo com o navegador e o sistema operacional que você usa.

Identifique seu navegador na lista abaixo e clique nele para mais informações.

{% endmarkdown %}

                 Google Chrome para computadores (Linux, Windows e Mac OS X)

{% markdown %}

Na página de *downloads*, clique no *link* desejado:

{% include image.html src="/files/2015/12/download-linux-chrome-1-pt.jpg" %}

Se o *download* for oferecido pelo Projeto Linux Kamarada, você será redirecionado para uma página do SourceForge.net, que é onde os *downloads* do Projeto Linux Kamarada são hospedados, mas o *download* deve começar automaticamente. Caso isso não aconteça, clique em **direct link** na página do SourceForge.net:

{% include image.html src="/files/2015/12/download-linux-chrome-2.jpg" %}

O *download* vai começar. Você pode acompanhar seu andamento na parte inferior da janela:

{% include image.html src="/files/2015/12/download-linux-chrome-3-pt.jpg" %}

Quando o *download* terminar, o ícone piscará, indicando que o arquivo já se encontra em seu computador:

{% include image.html src="/files/2015/12/download-linux-chrome-4.jpg" %}

Abra a pasta **Downloads** do seu computador e o arquivo estará lá:

{% include image.html src="/files/2015/12/download-linux-downloads-pt.jpg" %}

Agora que você já sabe como baixar o Linux usando o Google Chrome, pode acessar a [página de *downloads*](/pt/download/) do Projeto Linux Kamarada e baixar esse incrível sistema operacional!

{% endmarkdown %}

Fechar as instruções para o Google Chrome

                 Microsoft Edge (Windows)

{% markdown %}

Na página de *downloads*, clique no *link* desejado:

{% include image.html src="/files/2015/12/download-linux-edge-1-pt.jpg" %}

Se o *download* for oferecido pelo Projeto Linux Kamarada, você será redirecionado para uma página do SourceForge.net, que é onde os *downloads* do Projeto Linux Kamarada são hospedados, mas o *download* deve começar automaticamente. Caso isso não aconteça, clique em **direct link** na página do SourceForge.net:

{% include image.html src="/files/2015/12/download-linux-edge-2-pt.jpg" %}

O *download* vai começar. Você pode acompanhar seu andamento na parte inferior da janela:

{% include image.html src="/files/2015/12/download-linux-edge-3-pt.jpg" %}

O navegador avisará quando o *download* terminar, indicando que o arquivo já se encontra em seu computador. Clique em **Exibir downloads**:

{% include image.html src="/files/2015/12/download-linux-edge-4-pt.jpg" %}

Clique em **Abrir pasta**:

{% include image.html src="/files/2015/12/download-linux-edge-5-pt.jpg" %}

Você verá o arquivo na pasta **Downloads** do seu computador:

{% include image.html src="/files/2015/12/download-linux-downloads-pt.jpg" %}

Agora que você já sabe como baixar o Linux usando o Microsoft Edge, pode acessar a [página de *downloads*](/pt/download/) do Projeto Linux Kamarada e baixar esse incrível sistema operacional!

{% endmarkdown %}

Fechar as instruções para o Microsoft Edge

                 Mozilla Firefox para computadores (Linux, Windows e Mac OS X)

{% markdown %}

Na página de *downloads*, clique no *link* desejado:

{% include image.html src="/files/2015/12/download-linux-firefox-1-pt.jpg" %}

Se o *download* for oferecido pelo Projeto Linux Kamarada, você será redirecionado para uma página do SourceForge.net, que é onde os *downloads* do Projeto Linux Kamarada são hospedados, mas o *download* deve começar automaticamente. Caso isso não aconteça, clique em **direct link** na página do SourceForge.net:

{% include image.html src="/files/2015/12/download-linux-firefox-2-pt.jpg" %}

Marque a opção **Download** e clique em **OK**:

{% include image.html src="/files/2015/12/download-linux-firefox-3-pt.jpg" %}

O *download* vai começar. Você pode acompanhar seu andamento clicando no ícone **Andamento dos downloads** na parte superior direita da janela:

{% include image.html src="/files/2015/12/download-linux-firefox-4-pt.jpg" %}

Quando o *download* terminar, o ícone **Andamento dos downloads** se tornará azul, indicando que o arquivo já se encontra em seu computador. Clique no ícone **Abrir pasta**:

{% include image.html src="/files/2015/12/download-linux-firefox-5-pt.jpg" %}

Você verá o arquivo na pasta **Downloads** do seu computador:

{% include image.html src="/files/2015/12/download-linux-downloads-pt.jpg" %}

Agora que você já sabe como baixar o Linux usando o Mozilla Firefox, pode acessar a [página de *downloads*](/pt/download/) do Projeto Linux Kamarada e baixar esse incrível sistema operacional!

{% endmarkdown %}

Fechar as instruções para o Mozilla Firefox


text:
package io.sitoolkit.wt.domain.debug;

import java.nio.file.Path;

public interface DebugListener {

  void onDebugging(Path scriptPath, int nextStepIndex, int caseIndex);

  void onCaseEnd(Path scriptPath, int caseIndex);

  void onClose();

}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace App\Http\Controllers;

use App\Models\Log;
use App\Models\Option;
use App\Services\TemplateService;
use App\Services\Util;
use Exception;
use Input;
use Redirect;
use Validator;

class OptionController extends Controller
{

	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$options = Option::all();

		return view('options.index')->with([
			'page_title' => trans('app.options'),
			'options' => $options,
		]);
	}

	public function update()
	{
		$rules = [
			'global_admin-mail' => 'required|email',
			'session_lifetime' => 'required|numeric|min:10',
			'global_min-password' => 'required|numeric',
			'global_invoice-offset' => 'required|numeric',
		];

		$validator = Validator::make(Input::all(), $rules);

		if ($validator->fails()) {
			return Redirect::to('options')
				->withErrors($validator)
				->withInput();
		} else {

			$templates = [
				'thankyou' => 'mail_template_thankyou',
				'generic' => 'mail_template_generic',
			];

			foreach (Input::except(['_token'] + $templates) as $key => $value) {

				try {
					Option::updateOrCreate(['key' => str_replace('_', '.', $key)], ['value' => $value]);
				} catch (\Exception $e) {
					Log::writeException($e);
					return Redirect::to('options')
						->withErrors($e->getMessage())
						->withInput();
				}
			}

			// templates are critical, try them first
			foreach($templates as $key => $value) {
				$TemplateService = new TemplateService();
				$TemplateService->loadSystemTemplate($key);
				$TemplateService->setContent(Input::get($value));
				if($TemplateService->render() === false) {
					return Redirect::to('options')
						->withErrors(trans('app.template_error'))
						->withInput();
				} else {
					Option::updateOrCreate(['key' => str_replace('_', '.', $value)], ['value' => Input::get($value)]);
				}
			}

			flash()->success(trans('app.success'));
			return Redirect::to('options');

		}
	}

	public function mailTest()
	{
		$TemplateService = new TemplateService();
		$TemplateService->loadSystemTemplate('generic');

		$ret = Util::sendMail(config('global.admin-mail'), trans('app.information'), $TemplateService->render());

		if(!$ret) {
			flash()->error(trans('app.error').', '.trans('app.check_logs'));
		} else {
			flash()->success(trans('app.mail_test_success'));
		}

		return Redirect::to('options');
	}

	public function templateSendMail($template)
	{
		$TemplateService = new TemplateService();
		$TemplateService->loadSystemTemplate($template);

		return Util::sendMail(config('global.admin-mail'), trans('app.information'), $TemplateService->render()) ? trans('app.mail_test_success') : trans('app.fail');
	}

}


text:
package inspect

import (
	"context"
	"io"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/config"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/inspect"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
)

type testList struct {
	Tests []interface{} `json:"tests"`
}

// CustomTest entries are handled by CustomTest struct, there is no StructureTest so structureTestEntry is required
type structureTestEntry struct {
	TestType          string   `json:"testType"`
	StructureTest     string   `json:"structureTest"`
	StructureTestArgs []string `json:"structureTestArgs"`
}

type customTestEntry struct {
	TestType string `json:"testType"`
	latest.CustomTest
}

func PrintTestsList(ctx context.Context, out io.Writer, opts inspect.Options) error {
	formatter := inspect.OutputFormatter(out, opts.OutFormat)
	cfgs, err := inspect.GetConfigSet(ctx, config.SkaffoldOptions{
		ConfigurationFile:   opts.Filename,
		ConfigurationFilter: opts.Modules,
		RepoCacheDir:        opts.RepoCacheDir,
		Profiles:            opts.Profiles,
		PropagateProfiles:   opts.PropagateProfiles,
	})
	if err != nil {
		formatter.WriteErr(err)
		return err
	}

	// TODO(aaron-prindle) add a field 'testType' to both objects
	l := &testList{Tests: []interface{}{}}
	for _, c := range cfgs {
		for _, t := range c.Test {
			for _, ct := range t.CustomTests {
				l.Tests = append(l.Tests, customTestEntry{"custom-test", ct})
			}
			for _, st := range t.StructureTests {
				l.Tests = append(l.Tests, structureTestEntry{"structure-test", st, t.StructureTestArgs})
			}
		}
	}
	return formatter.Write(l)
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace PortiLog.Monitor
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {

                string logFilename = args[0];
                if (string.IsNullOrEmpty(logFilename))
                    return;

                if (!File.Exists(logFilename))
                    return;

                SelectLogFile(logFilename);
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new ProgramForm());
        }

        public static string LogFileName;

        public static void SelectLogFile(string fileName)
        {
            Program.LogFileName = fileName;

            ReloadRecent();

            Recent.RemoveAll(r => string.Equals(r, fileName, StringComparison.InvariantCultureIgnoreCase));

            Recent.Insert(0, fileName);

            if (Recent.Count > 20)
                Recent.RemoveAt(20);

            Properties.Settings.Default.Filename = Program.LogFileName;
            Properties.Settings.Default.Recent = Recent.ToArray();
            Properties.Settings.Default.Save();
        }

        public static List<string> Recent = new List<string>();

        public static void ReloadRecent()
        {
            Program.Recent.Clear();
            var recent = Properties.Settings.Default.Recent;
            if (recent != null && recent.Length > 0)
                Program.Recent.AddRange(Properties.Settings.Default.Recent);
        }
    }
}


text:
from msrest.serialization import Model

class SubnetOverrideFragment(Model):
    """Property overrides on a subnet of a virtual network.

    :param resource_id: The resource ID of the subnet.
    :type resource_id: str
    :param lab_subnet_name: The name given to the subnet within the lab.
    :type lab_subnet_name: str
    :param use_in_vm_creation_permission: Indicates whether this subnet can be
     used during virtual machine creation (i.e. Allow, Deny). Possible values
     include: 'Default', 'Deny', 'Allow'
    :type use_in_vm_creation_permission: str or :class:`UsagePermissionType
     <azure.mgmt.devtestlabs.models.UsagePermissionType>`
    :param use_public_ip_address_permission: Indicates whether public IP
     addresses can be assigned to virtual machines on this subnet (i.e. Allow,
     Deny). Possible values include: 'Default', 'Deny', 'Allow'
    :type use_public_ip_address_permission: str or :class:`UsagePermissionType
     <azure.mgmt.devtestlabs.models.UsagePermissionType>`
    :param shared_public_ip_address_configuration: Properties that virtual
     machines on this subnet will share.
    :type shared_public_ip_address_configuration:
     :class:`SubnetSharedPublicIpAddressConfigurationFragment
     <azure.mgmt.devtestlabs.models.SubnetSharedPublicIpAddressConfigurationFragment>`
    :param virtual_network_pool_name: The virtual network pool associated with
     this subnet.
    :type virtual_network_pool_name: str
    """

    _attribute_map = {
        'resource_id': {'key': 'resourceId', 'type': 'str'},
        'lab_subnet_name': {'key': 'labSubnetName', 'type': 'str'},
        'use_in_vm_creation_permission': {'key': 'useInVmCreationPermission', 'type': 'str'},
        'use_public_ip_address_permission': {'key': 'usePublicIpAddressPermission', 'type': 'str'},
        'shared_public_ip_address_configuration': {'key': 'sharedPublicIpAddressConfiguration', 'type': 'SubnetSharedPublicIpAddressConfigurationFragment'},
        'virtual_network_pool_name': {'key': 'virtualNetworkPoolName', 'type': 'str'},
    }

    def __init__(self, resource_id=None, lab_subnet_name=None, use_in_vm_creation_permission=None, use_public_ip_address_permission=None, shared_public_ip_address_configuration=None, virtual_network_pool_name=None):
        self.resource_id = resource_id
        self.lab_subnet_name = lab_subnet_name
        self.use_in_vm_creation_permission = use_in_vm_creation_permission
        self.use_public_ip_address_permission = use_public_ip_address_permission
        self.shared_public_ip_address_configuration = shared_public_ip_address_configuration
        self.virtual_network_pool_name = virtual_network_pool_name


text:
title: Images Stored in a DataBase in RadTileList
description: Images Stored in a DataBase in RadTileList. Check it now!
type: how-to
page_title: Images Stored in a DataBase in RadTileList
slug: tilelist-images-stored-in-a-database
res_type: kb
---

## Problem

How to show **images** from a **database** in a **RadTileList**.

[RadTileList's built-in data binding]({%slug tilelist/data-binding/overview%}) allows for URLs to be set to the file system.

## Solution

There are three possible approaches you can take:

- Point the ImageUrl to a **custom handler that will take some argument and return the image**.

 The result would be something like:

 ````
 <img src="myhandler.ashx?imageId=1234" />
 ````

 where the needed **URL data (direct links to the handler) can be stored in the data source and provided to the tile list via its data binding properties**:

 ````
 <CommonTileBinding DataBadgeImageUrlField="badgeUrls" DataTitleImageUrlField="titleUrls" />
<ImageTileBinding DataImageUrlField="imageUrls" />
 ````

 With this approach the database queries will not run synchronously for each item in the TileDataBound event, but the browser will call the handler as many times as needed when it renders images. This will improve the page performance and can even improve caching (depending on your handler specifics).

- **Create your own structure** in a [RadContentTemplateTile]({%slug tilelist/tiles/contenttemplate-tile%}). This lets you use **data binding expressions** to fetch the **image from a custom handler**, for example:

 ````
 <ContentTemplateTileBinding>
    <ContentTemplate>
        <img src='myImageHandler.ashx?id=<%# DataBinder.Eval(Container.DataItem, "imageId") %>' />
    </ContentTemplate>
</ContentTemplateTileBinding>
 ````

- Add a [RadBinaryImage]({%slug controls/radbinaryimage%})in a [RadContentTemplateTile]({%slug tilelist/tiles/contenttemplate-tile%}). You can **provide** it with a **byte array of image data in the [TileDataBound event]({%slug tilelist/server-side-programming/server-side-events/ontiledatabound%})**. This will have worse performance than the options above because all queries will have to run synchronously.

 ````ASPX
 <telerik:RadTileList RenderMode="Lightweight" runat="server" ID="RadTileList1" Width="634px" OnTileDataBound="RadTileList1_TileDataBound">
    <DataBindings>
        <CommonTileBinding TileType="RadContentTemplateTile" />
        <ContentTemplateTileBinding>
            <ContentTemplate>
                <telerik:RadBinaryImage runat="server" ID="theImage"  />
            </ContentTemplate>
        </ContentTemplateTileBinding>
    </DataBindings>
</telerik:RadTileList>
 ````

 ````C#
 protected void RadTileList1_TileDataBound(object sender, TileListEventArgs e)
{
    //get the actual image, this is a sample with an image in the file system
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/images/someImage.png"));
    byte[] arr;
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        arr = ms.ToArray();
    }
     //end get of image, you should have a byte array with the image data at this point
    ((e.Tile as RadContentTemplateTile).ContentContainer.FindControl("theImage") as RadBinaryImage).DataValue = arr;
}
protected void Page_Load(object sender, EventArgs e)
{
    RadTileList1.DataSource = new[] { 1, 2, 3 };
    RadTileList1.DataBind();
}
 ````


text:
workspace "ADKomA80"
	configurations { "Debug", "Release" }
	location(_ACTION)

project "ToolSuite"
	kind "ConsoleApp"
	language "C++"
	targetname "tools"
	targetdir ".."

	files { "../Sources/**.cpp" }
	includedirs { "../Sources" }

	buildoptions { "-std=c++17", "-stdlib=libc++", "-Weverything", "-Werror", "-Wno-weak-vtables", "-Wno-padded", "-Wno-newline-eof", "-Wno-pedantic", "-Wno-c++98-compat", "-Wno-c++98-compat-pedantic", "-Wno-implicit-fallthrough", "-Wno-global-constructors", "-Wno-exit-time-destructors", "-Wno-documentation", "-Wno-documentation-unknown-command" }

	linkoptions { "-std=c++1z", "-stdlib=libc++" }

	filter "configurations:Debug"
		buildoptions { "-fsanitize=undefined", "-fsanitize=address", "-g", "-fno-limit-debug-info" }
		linkoptions { "-fsanitize=undefined", "-fsanitize=address", "-g", "-fno-limit-debug-info" }
		targetname "toolsd"

	filter "configurations:Release"
		buildoptions { "-O3" }
		linkoptions { "-O3" }


text:
require 'spec_helper'

module GoodData
  describe Schedule do
    subject { Schedule }

    describe "::create" do
      it "should initialize and save a schedule" do
        schedule = double('Schedule')
        expect(schedule).to receive(:save)
        expect(subject).to receive(:new).with(:attrs).and_return(schedule)
        subject.create(:attrs)
      end
    end

    describe "::new" do
      it "should set all attributes" do
        schedule = subject.new(project_id: 1, account_id: 2)
        expect(schedule.project_id).to eq(1)
        expect(schedule.account_id).to eq(2)
      end
    end

    describe "#save" do
      it "should persist object to backend" do
        schedule = subject.new
        schedule.project_id = 123
        schedule.account_id = 321
        schedule.process_id = 'process_id'
        schedule.creds = {S3_ACCESSKEY: 'key',S3_SECRETKEY: 'secret'}
        schedule.graph = 'graph_path'
        expect(GoodData).to receive(:post).with('/gdc/projects/123/schedules', {
          schedule: {
            type: "MSETL",
            timezone: "UTC",
            cron: "0 12 * * *",
            params: {
              PROCESS_ID: "process_id",
              GRAPH: "graph_path",
              S3_SUBFOLDER: "production",
              S3_ID: 321,
              S3_ACCESSKEY: 'key',
              MODE: "DEMANDBASE/PRODUCTION"
            },
            hiddenParams: {
              S3_SECRETKEY: 'secret'
            }
          }
        })
        schedule.save
      end
    end
  end
end


text:
package uk.joshiejack.harvestcore.command;

import uk.joshiejack.harvestcore.world.mine.Mine;
import uk.joshiejack.harvestcore.world.mine.dimension.MineTeleporter;
import uk.joshiejack.penguinlib.util.PenguinLoader;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;

import javax.annotation.Nonnull;

@PenguinLoader
public class CommandMine extends HCComand {
    @Nonnull
    @Override
    public String getName() {
        return "mine";
    }

    @Nonnull
    @Override
    public String getUsage(@Nonnull ICommandSender sender) {
        return "";
    }

    @Override
    public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] args) throws CommandException {
        if (sender instanceof EntityPlayer) {
            if (args.length == 1 || args.length == 2) {
                try {

                    int dim = Mine.BY_NAME.getInt(args[0]);
                    if (dim != 0) {
                        int id = args.length == 2 ? Integer.parseInt(args[1]) : 0;
                        ((EntityPlayer) sender).changeDimension(dim, new MineTeleporter(Mine.BY_ID.get(dim), id));
                    }
                } catch (NumberFormatException ex) {
                    throw new CommandException("Didn't use a valid number for the mine command");
                }
            }
        }
    }
}


text:
Meteor.startup(() => {
	RocketChat.MessageAction.addButton({
		id: 'mark-message-as-unread',
		icon: 'flag',
		label: 'Mark_as_unread',
		context: ['message', 'message-mobile'],
		action() {
			const message = this._arguments[1];
			return Meteor.call('unreadMessages', message, function(error) {
				if (error) {
					return handleError(error);
				}
				const subscription = ChatSubscription.findOne({
					rid: message.rid
				});
				if (subscription == null) {
					return;
				}
				RoomManager.close(subscription.t + subscription.name);
				return FlowRouter.go('home');
			});
		},
		condition(message) {
			return message.u._id !== Meteor.user()._id;
		},
		order: 22,
		group: 'menu'
	});
});


text:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;

namespace SurfaceGameBasics
{
	public class ViewModel : INotifyPropertyChanged
	{
		public void Dispatch(Action action)
		{
			Application.Current.Dispatcher.BeginInvoke(action);
		}

		public void NotifyChanged(string memberName)
		{
			var pc = PropertyChanged;
			if (pc != null)
			{
				pc(this, new PropertyChangedEventArgs(memberName));
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;
	}

	public class Command : ICommand
	{
		Action<object> _action;
		public Command(Action<object> action)
		{
			_action = action;
		}

		public event EventHandler CanExecuteChanged;

		public bool CanExecute(object parameter)
		{
			return true;
		}

		public void Execute(object parameter)
		{
			_action(parameter);
		}
	}
}


text:
package org.auraframework.http.resource;

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.auraframework.Aura;
import org.auraframework.clientlibrary.ClientLibraryService;
import org.auraframework.def.DefDescriptor;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Format;

public class ClientLibraryJs extends AuraResourceImpl {
    private ClientLibraryService clientLibraryService = Aura.getClientLibraryService();

    public ClientLibraryJs() {
        super("resources.js", Format.JS, false);
    }

    @Override
    public void write(HttpServletRequest request, HttpServletResponse response, AuraContext context) throws IOException {

        Set<DefDescriptor<?>> dependencies = servletUtilAdapter.verifyTopLevel(request, response, context);
        if (dependencies == null) {
            return;
        }
        try {
            clientLibraryService.writeJs(context, response.getWriter());
        } catch (Throwable t) {
            servletUtilAdapter.handleServletException(t, true, context, request, response, true);
        }
    }

    /**
     * @param clientLibraryService the clientLibraryService to set
     */
    public void setClientLibraryService(ClientLibraryService clientLibraryService) {
        this.clientLibraryService = clientLibraryService;
    }
}


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// 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.
//
//==============================================================================
//
// Author: Sushma Fernandes, Hewlett Packard Company (sushma_fernandes@hp.com)
//
// Modified By: Nag Boranna, Hewlett-Packard Company (nagaraja_boranna@hp.com)
//              Carol Ann Krug Graves, Hewlett-Packard Company
//                  (carolann_graves@hp.com)
//              Amit K Arora, IBM (amita@in.ibm.com) for PEP-101
//              Alagaraja Ramasubramanian, IBM (alags_raj@in.ibm.com) - PEP-167
//              Amit K Arora, IBM (amita@in.ibm.com) - Bug#2311,#2333,#2351
//              Josephine Eskaline Joyce, IBM (jojustin@in.ibm.com) - Bug#2756
//              David Dillard, VERITAS Software Corp.
//                  (david.dillard@veritas.com)
//              Josephine Eskaline Joyce, IBM (jojustin@in.ibm.com) for Bug#3032
//
//%/////////////////////////////////////////////////////////////////////////////

#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/Constants.h>
#include <iostream>
#include <Clients/cliutils/Command.h>
#include <Clients/cliutils/CommandException.h>
#include <Pegasus/getoopt/getoopt.h>
#include <Pegasus/Client/CIMClient.h>
#include <Pegasus/Common/CIMProperty.h>
#include <Pegasus/Common/CIMObjectPath.h>
#include <Pegasus/Common/CIMStatusCode.h>
#include <Pegasus/Common/String.h>
#include <Pegasus/Common/System.h>
#include <Pegasus/Common/PegasusVersion.h>
#include <Pegasus/Common/AutoPtr.h>

PEGASUS_USING_STD;

PEGASUS_NAMESPACE_BEGIN

//l10n
/**
 * The CLI message resource name
 */

static const char MSG_PATH [] = "pegasus/pegasusCLI";

/**
    The command name.
*/
static const char COMMAND_NAME []              = "cimuser";

/**
    This constant represents the name of the User name property in the schema
*/
static const CIMName PROPERTY_NAME_USER_NAME            = CIMName ("Username");

/**
    This constant represents the name of the Password property in the schema
*/
static const CIMName PROPERTY_NAME_PASSWORD             = CIMName ("Password");

/**
    The usage string for this command.  This string is displayed
    when an error occurs in parsing or validating the command line.
*/
static const char USAGE []                     = "Usage: ";

/**
    This constant represents the getoopt argument designator
*/
static const char GETOPT_ARGUMENT_DESIGNATOR   = ':';

/*
    These constants represent the operation modes supported by the CLI.
    Any new operation should be added here.
*/

/**
    This constant signifies that an operation option has not been recorded
*/
static const Uint32 OPERATION_TYPE_UNINITIALIZED  = 0;

/**
    This constant represents a add user operation
*/
static const Uint32 OPERATION_TYPE_ADD            = 1;

/**
    This constant represents a add user operation
*/
static const Uint32 OPERATION_TYPE_MODIFY         = 2;

/**
    This constant represents a remove user operation
*/
static const Uint32 OPERATION_TYPE_REMOVE         = 3;

/**
    This constant represents a list operation
*/
static const Uint32 OPERATION_TYPE_LIST           = 4;

/**
    This constant represents a help operation
*/
static const Uint32 OPERATION_TYPE_HELP           = 5;

/**
    This constant represents a version display operation
*/
static const Uint32 OPERATION_TYPE_VERSION        = 6;

/**
    The constants representing the messages.
*/

//l10n

static const char NOT_PRIVILEGED_USER [] =
    "You must have superuser privilege to run this command.";

static const char NOT_PRIVILEGED_USER_KEY [] =
    "Clients.cimuser.CIMUserCommand.NOT_PRIVILEGED_USER";

static const char CIMOM_NOT_RUNNING [] =
    "CIM Server may not be running.";

static const char CIMOM_NOT_RUNNING_KEY [] =
    "Clients.cimuser.CIMUserCommand.CIMOM_NOT_RUNNING";

static const char ADD_USER_FAILURE [] =
    "Failed to add user.";

static const char ADD_USER_FAILURE_KEY [] =
    "Clients.cimuser.CIMUserCommand.ADD_USER_FAILURE";

static const char REMOVE_USER_FAILURE [] =
    "Failed to remove user.";

static const char REMOVE_USER_FAILURE_KEY [] =
    "Clients.cimuser.CIMUserCommand.REMOVE_USER_FAILURE";

static const char CHANGE_PASSWORD_FAILURE [] =
    "Failed to change password.";

static const char CHANGE_PASSWORD_FAILURE_KEY [] =
    "Clients.cimuser.CIMUserCommand.CHANGE_PASSWORD_FAILURE";

static const char LIST_USERS_FAILURE [] =
    "Failed to list the users. ";

static const char LIST_USERS_FAILURE_KEY [] =
    "Clients.cimuser.CIMUserCommand.LIST_USERS_FAILURE";

static const char ADD_USER_SUCCESS [] =
    "User added successfully.";

static const char ADD_USER_SUCCESS_KEY [] =
    "Clients.cimuser.CIMUserCommand.ADD_USER_SUCCESS";

static const char REMOVE_USER_SUCCESS[] =
    "User removed successfully.";

static const char REMOVE_USER_SUCCESS_KEY[] =
    "Clients.cimuser.CIMUserCommand.REMOVE_USER_SUCCESS";

static const char CHANGE_PASSWORD_SUCCESS [] =
    "Password changed successfully.";

static const char CHANGE_PASSWORD_SUCCESS_KEY [] =
    "Clients.cimuser.CIMUserCommand.CHANGE_PASSWORD_SUCCESS";

static const char PASSWORD_BLANK [] =
    "Password cannot be blank. Please re-enter your password.";

static const char PASSWORD_BLANK_KEY [] =
    "Clients.cimuser.CIMUserCommand.PASSWORD_BLANK";

static const char NO_USERS_FOUND[] =
    "No users found for listing.";

static const char NO_USERS_FOUND_KEY[] =
    "Clients.cimuser.CIMUserCommand.NO_USERS_FOUND";

static const char AUTH_SCHEMA_NOT_LOADED [] =
    "Please restore the internal repository on the CIM Server.";

static const char AUTH_SCHEMA_NOT_LOADED_KEY [] =
    "Clients.cimuser.CIMUserCommand.AUTH_SCHEMA_NOT_LOADED";

static const char REQUIRED_ARGS_MISSING [] =
    "Required arguments missing.";

static const char REQUIRED_ARGS_MISSING_KEY [] =
    "Clients.cimuser.CIMUserCommand.REQUIRED_ARGS_MISSING";

static const char INVALID_ARGS [] =
    "Invalid arguments.";

static const char INVALID_ARGS_KEY [] =
    "Clients.cimuser.CIMUserCommand.INVALID_ARGS";

static const char USER_ALREADY_EXISTS [] =
    "Specified user name already exist.";

static const char USER_ALREADY_EXISTS_KEY [] =
    "Clients.cimuser.CIMUserCommand.USER_ALREADY_EXISTS";

static const char USER_NOT_FOUND [] =
    "Specified user name was not found.";

static const char USER_NOT_FOUND_KEY [] =
    "Clients.cimuser.CIMUserCommand.USER_NOT_FOUND";

static const char USERNAME_REQUIRED [] =
    "User name is required.";

static const char USERNAME_REQUIRED_KEY [] =
    "Clients.cimuser.CIMUserCommand.USERNAME_REQUIRED";

/**
    The option character used to specify add user.
*/
static const char   OPTION_ADD                 = 'a';

/**
    The option character used to specify modify user.
*/
static const char   OPTION_MODIFY              = 'm';

/**
    The option character used to specify user name.
*/
static const char   OPTION_USER_NAME           = 'u';

/**
    The option character used to specify password.
*/
static const char   OPTION_PASSWORD            = 'w';

/**
    The option character used to specify new password.
*/
static const char   OPTION_NEW_PASSWORD        = 'n';

/**
    The option character used to specify remove user.
*/
static const char   OPTION_REMOVE              = 'r';

/**
    The option character used to specify listing of users.
*/
static const char   OPTION_LIST                = 'l';

/**
    The option character used to display help info.
*/
static const char   OPTION_HELP                = 'h';

/**
    The option character used to display version info.
*/
static const char   OPTION_VERSION             = 'v';

/**
    The name of the Method that implements modify password
*/
static const CIMName   MODIFY_METHOD            = CIMName ("modifyPassword");

/**
    The input parameter name for old password
*/
static const char   OLD_PASS_PARAM[]             = "OldPassword";

/**
    The input parameter name for new password
*/
static const char   NEW_PASS_PARAM[]             = "NewPassword";

static const char   PASSWORD_PROMPT []  =
                        "Please enter your password: ";

static const char   PASSWORD_PROMPT_KEY [] = "Clients.cimuser.CIMUserCommand.PASSWORD_PROMPT";

static const char   OLD_PASSWORD_PROMPT []  =
                        "Please enter your old password: ";

static const char   OLD_PASSWORD_PROMPT_KEY []  ="Clients.cimuser.CIMUserCommand.OLD_PASSWORD_PROMPT";

static const char   RE_ENTER_PROMPT []  =
                        "Please re-enter your password: ";

static const char   RE_ENTER_PROMPT_KEY []  ="Clients.cimuser.CIMUserCommand.RE_ENTER_PROMPT";

static const char   NEW_PASSWORD_PROMPT []  =
                        "Please enter your new password: ";

static const char   NEW_PASSWORD_PROMPT_KEY []  ="Clients.cimuser.CIMUserCommand.NEW_PASSWORD_PROMPT";

static const char   PASSWORD_DOES_NOT_MATCH []  =
                        "Passwords do not match. Please Re-enter.";

static const char   PASSWORD_DOES_NOT_MATCH_KEY []  = "Clients.cimuser.CIMUserCommand.PASSWORD_DOES_NOT_MATCH";

static const char   PASSWORD_SAME_ERROR []  =
                        "Error, new and old passwords cannot be same.";

static const char   PASSWORD_SAME_ERROR_KEY []  = "Clients.cimuser.CIMUserCommand.PASSWORD_SAME_ERROR";

static const char ERR_OPTION_NOT_SUPPORTED [] = "Invalid option. Use '--help' to obtain command syntax.";

static const char ERR_OPTION_NOT_SUPPORTED_KEY [] = "Clients.cimuser.CIMUserCommand.ERR_OPTION_NOT_SUPPORTED";

static const char ERR_USAGE [] = "Incorrect usage. Use '--help' to obtain command syntax.";

static const char ERR_USAGE_KEY [] = "Clients.cimuser.CIMUserCommand.ERR_USAGE";

static const char   LONG_HELP []  = "help";

static const char   LONG_VERSION []  = "version";
/**
This is a CLI used to manage users of the CIM Server.  This command supports
operations to add, modify, list and remove users.

@author Sushma Fernandes, Hewlett-Packard Company
*/

class CIMUserCommand : public Command
{

public:

    /**
        Constructs a CIMUserCommand and initializes instance variables.
    */
    CIMUserCommand ();

    //
    // Overrides the virtual function setCommand from Command class
    // This is defined as an empty function.
    //
    void setCommand (
        Uint32 argc,
        char* argv[])
    {
        // Empty function
    }

    /**
    Parses the command line, validates the options, and sets instance
    variables based on the option arguments. This implementation of
    setCommand includes the parameters for output and error stream.

    @param  ostream    The stream to which command output is written.
    @param  ostream    The stream to which command errors are written.
    @param  args       The string array containing the command line arguments
    @param  argc       The int containing the arguments count

    @throws  CommandFormatException  if an error is encountered in parsing
                                     the command line
    */
    void setCommand (
      ostream& outPrintWriter,
      ostream& errPrintWriter,
      Uint32 argc,
      char* argv[]);

    /**
    Executes the command and writes the results to the output streams.

    @param ostream    The stream to which command output is written.
    @param ostream    The stream to which command errors are written.
    @return  0        if the command is successful
             1        if an error occurs in executing the command
    */
    Uint32 execute (
        ostream& outPrintWriter,
        ostream& errPrintWriter);

private:

    //
    // Add a new user to the CIM Server
    //
    // @param ostream        The stream to which command output is written.
    // @param ostream        The stream to which command errors are written.
    //
    // @exception Exception  if failed to add user
    //
    void _AddUser
        (
        ostream& outPrintWriter,
        ostream& errPrintWriter
        );

    //
    // Modify an existing user's password.
    //
    // @param ostream          The stream to which command output is written.
    // @param ostream          The stream to which command errors are written.
    //
    // @exception Exception  if failed to modify password
    //
    void _ModifyUser
        (
        ostream&                 outPrintWriter,
        ostream&                 errPrintWriter
        );

    //
    // Remove an existing user from the CIM Server
    //
    // @param ostream          The stream to which command output is written.
    // @param ostream          The stream to which command errors are written.
    //
    // @exception Exception  if failed to remove user
    //
    void _RemoveUser
        (
        ostream& outPrintWriter,
        ostream& errPrintWriter
        );

    //
    // List all users.
    //
    // @param ostream        The stream to which command output is written.
    // @param ostream        The stream to which command errors are written.
    //
    void _ListUsers
    (
        ostream& outPrintWriter,
        ostream& errPrintWriter
    );

    //
    // The CIM Client reference
    //

    AutoPtr<CIMClient> _client; //PEP101

    //
    // The host name.
    //
    String _hostName;

    //
    // The name of the user.
    //
    String _userName;

    //
    // The password of the user.
    //
    String _password;

    //
    // The new password of the user.
    //
    String _newpassword;

    //
    // The type of operation specified on the command line.
    //
    Uint32 _operationType;

    //
    // Flags for command options
    //
    Boolean _userNameSet;
    Boolean _passwordSet;
    Boolean _newpasswordSet;

    String usage;

};

/**
    Constructs a CIMUserCommand and initializes instance variables.
*/
CIMUserCommand::CIMUserCommand ()
{
    /**
        Initialize the instance variables.
    */
    _operationType       = OPERATION_TYPE_UNINITIALIZED;
    _userName            = String::EMPTY;
    _password            = String::EMPTY;
    _newpassword         = String::EMPTY;
    _hostName            = String::EMPTY;
    _passwordSet         = false;
    _newpasswordSet      = false;
    _userNameSet         = false;

    /**
        Build the usage string for the config command.
    */
    usage.reserveCapacity(200);
    usage.append(USAGE);
    usage.append(COMMAND_NAME);

    usage.append(" -").append(OPTION_ADD);
    usage.append(" -").append(OPTION_USER_NAME).append(" username");
    usage.append(" [ -").append(OPTION_PASSWORD).append(" password")
         .append(" ] \n");

    usage.append("               -").append(OPTION_MODIFY);
    usage.append(" -").append(OPTION_USER_NAME).append(" username");
    usage.append(" [ -").append(OPTION_PASSWORD).append(" old password")
         .append(" ]");
    usage.append(" [ -").append(OPTION_NEW_PASSWORD).append(" new password")
         .append(" ] \n");

    usage.append("               -").append(OPTION_REMOVE);
    usage.append(" -").append(OPTION_USER_NAME).append(" username \n");

    usage.append("               -").append(OPTION_LIST).append(" \n");
    usage.append("               -").append(OPTION_HELP).append(" \n");
    usage.append("               --").append(LONG_HELP).append(" \n");
    usage.append("               --").append(LONG_VERSION).append(" \n");

    usage.append("Options : \n");
    usage.append("    -a         - Add a new CIM user\n");
    usage.append("    -h, --help - Display this help message\n");
    usage.append("    -l         - List the names of CIM users\n");
    usage.append("    -m         - Modify a CIM user's password\n");
    usage.append("    -n         - Supply a new password for the specified user name\n");
    usage.append("    -r         - Remove the specified CIM user\n");
    usage.append("    -u         - Specify a CIM user name\n");
    usage.append("    --version  - Display CIM Server version number\n");
    usage.append("    -w         - Supply a password for the specified user name\n");

    usage.append("\nUsage note: The cimuser command requires that the CIM Server is running.\n");
    setUsage (usage);
}

/**
    Parses the command line, validates the options, and sets instance
    variables based on the option arguments.
*/
void CIMUserCommand::setCommand (
    ostream& outPrintWriter,
    ostream& errPrintWriter,
    Uint32 argc,
    char* argv[])
{
    Uint32            i                = 0;
    Uint32            c                = 0;
    String            badOptionString  = String ();
    String            optString        = String ();

    //
    //  Construct optString
    //
    optString.append(OPTION_ADD);
    optString.append(OPTION_USER_NAME);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_PASSWORD);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_MODIFY);
    optString.append(OPTION_USER_NAME);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_PASSWORD);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_NEW_PASSWORD);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_REMOVE);
    optString.append(OPTION_USER_NAME);
    optString.append(getoopt::GETOPT_ARGUMENT_DESIGNATOR);
    optString.append(OPTION_LIST);
    optString.append(OPTION_HELP);

    //
    //  Initialize and parse options
    //
    getoopt options ("");
    options.addFlagspec(optString);

    //PEP#167 - adding long flag for options : 'help' and 'version'
    options.addLongFlagspec(LONG_HELP,getoopt::NOARG);
    options.addLongFlagspec(LONG_VERSION,getoopt::NOARG);

    options.parse (argc, argv);
    if (options.hasErrors ())
    {
        throw CommandFormatException(options.getErrorStrings()[0]);
    }
    _operationType = OPERATION_TYPE_UNINITIALIZED;

    //
    //  Get options and arguments from the command line
    //
    for (i =  options.first (); i <  options.last (); i++)
    {
        if (options[i].getType () == Optarg::LONGFLAG)
        {
            if (options[i].getopt () == LONG_HELP)
            {
                if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                {
                    String param = String (LONG_HELP);
                    //
                    // More than one operation option was found
                    //
                    throw UnexpectedOptionException(param);
                }

               _operationType = OPERATION_TYPE_HELP;
            }
            else if (options[i].getopt () == LONG_VERSION)
            {
                if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                {
                    String param = String (LONG_VERSION);
                    //
                    // More than one operation option was found
                    //
                    throw UnexpectedOptionException(param);
                }

               _operationType = OPERATION_TYPE_VERSION;
            }
        }
        else if (options [i].getType () == Optarg::REGULAR)
        {
            //
            //  The cimuser command has no non-option argument options
            //
            throw UnexpectedArgumentException(options[i].Value());
        }
        else /* if (options [i].getType () == Optarg::FLAG) */
        {

            c = options [i].getopt () [0];

            switch (c)
            {
                case OPTION_ADD:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_ADD);
                    }

                    if (options.isSet (OPTION_ADD) > 1)
                    {
                        //
                        // More than one add user option was found
                        //
                        throw DuplicateOptionException(OPTION_ADD);
                    }

                    _operationType = OPERATION_TYPE_ADD;

                    break;
                }
                case OPTION_MODIFY:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_MODIFY);
                    }

                    if (options.isSet (OPTION_MODIFY) > 1)
                    {
                        //
                        // More than one modify user option was found
                        //
                        throw DuplicateOptionException(OPTION_MODIFY);
                    }

                    _operationType = OPERATION_TYPE_MODIFY;

                    break;
                }
                case OPTION_USER_NAME:
                {
                    if (options.isSet (OPTION_USER_NAME) > 1)
                    {
                        //
                        // More than one username option was found
                        //
                        throw DuplicateOptionException(OPTION_USER_NAME);
                    }

                    _userName = options [i].Value ();

                    _userNameSet = true;

                    break;
                }
                case OPTION_PASSWORD:
                {
                    if (options.isSet (OPTION_PASSWORD) > 1)
                    {
                        //
                        // More than one password option was found
                        //
                        throw DuplicateOptionException(OPTION_PASSWORD);
                    }

                    String password = options [i].Value ();
                    _password = password.subString(0,8);

                    _passwordSet = true;

                    break;
                }
                case OPTION_NEW_PASSWORD:
                {
                    if (options.isSet (OPTION_NEW_PASSWORD) > 1)
                    {
                        //
                        // More than one new password option was found
                        //
                        throw DuplicateOptionException(OPTION_NEW_PASSWORD);
                    }

                    String newpassword = options [i].Value ();
                    _newpassword = newpassword.subString(0,8);

                    _newpasswordSet = true;

                    break;
                }
                case OPTION_REMOVE:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_REMOVE);
                    }

                    if (options.isSet (OPTION_REMOVE) > 1)
                    {
                        //
                        // More than one remove user option was found
                        //
                        throw DuplicateOptionException(OPTION_REMOVE);
                    }

                    _operationType = OPERATION_TYPE_REMOVE;

                    break;
                }

                case OPTION_LIST:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_LIST);
                    }

                    if (options.isSet (OPTION_LIST) > 1)
                    {
                        //
                        // More than one list option was found
                        //
                        throw DuplicateOptionException(OPTION_LIST);
                    }
                    _operationType = OPERATION_TYPE_LIST;
                    break;
                }
                //PEP#167 - 2 new cases added below for HELP and VERSION
                case OPTION_HELP:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_HELP);
                    }

                    if (options.isSet (OPTION_HELP) > 1)
                    {
                        //
                        // More than one list option was found
                        //
                        throw DuplicateOptionException(OPTION_HELP);
                    }
                    _operationType = OPERATION_TYPE_HELP;
                    break;
                }
                case OPTION_VERSION:
                {
                    if (_operationType != OPERATION_TYPE_UNINITIALIZED)
                    {
                        //
                        // More than one operation option was found
                        //
                        throw UnexpectedOptionException(OPTION_VERSION);
                    }

                    if (options.isSet (OPTION_VERSION) > 1)
                    {
                        //
                        // More than one list option was found
                        //
                        throw DuplicateOptionException(OPTION_VERSION);
                    }
                    _operationType = OPERATION_TYPE_VERSION;
                    break;
                }

                default:
                {
                    //
                    // Should never get here
                    //
                    break;
                }
            }
        }
    }

    //
    // Some more validations
    //
    if (_operationType == OPERATION_TYPE_UNINITIALIZED)
    {
        //
        // No operation type was specified
        // Show the usage
        //
        //l10n
        //CommandFormatException e (REQUIRED_ARGS_MISSING);
        throw CommandFormatException(localizeMessage(
            MSG_PATH, REQUIRED_ARGS_MISSING_KEY, REQUIRED_ARGS_MISSING));
    }

    if (_operationType == OPERATION_TYPE_LIST &&
        (_userNameSet || _passwordSet || _newpasswordSet))
    {
        //l10n
        MessageLoaderParms parms("Clients.cimuser.CIMUserCommand.UNEXPECTED_OPTION",
            "Unexpected Option.");
        //CommandFormatException e("Unexpected Option.");
        throw CommandFormatException(parms);
    }

    if (_operationType == OPERATION_TYPE_ADD)
    {
        if (_newpasswordSet)
        {
            //
            // An invalid option was encountered
            //
            throw UnexpectedOptionException(OPTION_NEW_PASSWORD);
        }
        if (!_userNameSet)
        {
            //
            // An invalid option was encountered
            //
            throw MissingOptionException(OPTION_USER_NAME);
        }
        if (!_passwordSet)
        {
            //
            // Password is not set, prompt for the password
            //
            String pw = String::EMPTY;
            do
            {
                pw = System::getPassword(PASSWORD_PROMPT);

                if (pw == String::EMPTY || pw == "")
                {
                    //l10n
                    //errPrintWriter << PASSWORD_BLANK << endl;
                    errPrintWriter << localizeMessage(MSG_PATH,PASSWORD_BLANK_KEY,PASSWORD_BLANK) << endl;
                    pw = String::EMPTY;
                    continue;
                }
                if (pw != System::getPassword(RE_ENTER_PROMPT))
                {
                    //l10n
                    //errPrintWriter << PASSWORD_DOES_NOT_MATCH << endl;
                    errPrintWriter << localizeMessage(MSG_PATH,PASSWORD_DOES_NOT_MATCH_KEY,PASSWORD_DOES_NOT_MATCH_KEY) << endl;
                    pw = String::EMPTY;
                }
            }
            while (pw == String::EMPTY);

            _password = pw ;
        }
    }

    if (_operationType == OPERATION_TYPE_MODIFY)
    {
        if (!_userNameSet)
        {
            //
            // An invalid option was encountered
            //
            throw MissingOptionException(OPTION_USER_NAME);
        }
        if (_passwordSet && _newpasswordSet)
        {
            if (_newpassword == _password)
            {
                //l10n
                //cerr << PASSWORD_SAME_ERROR << endl;
                cerr << localizeMessage(MSG_PATH,PASSWORD_SAME_ERROR_KEY,PASSWORD_SAME_ERROR) << endl;
                exit (1);
            }
        }
        if (!_passwordSet)
        {
            //
            // Password is not set, prompt for the old password once
            //
            String pw = String::EMPTY;
            do
            {
                pw = System::getPassword(OLD_PASSWORD_PROMPT);
                if (pw == String::EMPTY || pw == "")
                {
                    //l10n
                    //errPrintWriter << PASSWORD_BLANK << endl;
                    errPrintWriter << localizeMessage(MSG_PATH,PASSWORD_BLANK_KEY,PASSWORD_BLANK) << endl;
                    pw = String::EMPTY;
                    continue;
                }
            }
            while (pw == String::EMPTY);
            _password = pw ;
        }
        if (!_newpasswordSet)
        {
            //
            // Password is not set, prompt for the new password twice
            //
            String newPw = String::EMPTY;
            do
            {
                newPw = System::getPassword(NEW_PASSWORD_PROMPT);
                if (newPw == String::EMPTY || newPw == "")
                {
                    //l10n
                    //errPrintWriter << PASSWORD_BLANK << endl;
                    errPrintWriter << localizeMessage(MSG_PATH,PASSWORD_BLANK_KEY,PASSWORD_BLANK) << endl;
                    newPw = String::EMPTY;
                    continue;
                }

                if (newPw != System::getPassword(RE_ENTER_PROMPT))
                {
                    //l10n
                    //errPrintWriter << PASSWORD_DOES_NOT_MATCH << endl;
                    errPrintWriter << localizeMessage(MSG_PATH,PASSWORD_DOES_NOT_MATCH_KEY,PASSWORD_DOES_NOT_MATCH) << endl;
                    newPw = String::EMPTY;
                }
            }
            while (newPw == String::EMPTY);
            _newpassword = newPw ;
            if (_newpassword == _password)
            {
                //l10n
                //cerr << PASSWORD_SAME_ERROR << endl;
                cerr << localizeMessage(MSG_PATH,PASSWORD_SAME_ERROR_KEY, PASSWORD_SAME_ERROR) << endl;
                exit (-1);
            }
        }
    }

    if (_operationType == OPERATION_TYPE_REMOVE)
    {
        if (!_userNameSet)
        {
            //
            // An invalid option was encountered
            //
            throw MissingOptionException(OPTION_USER_NAME);
        }
        if (_passwordSet)
        {
            //
            // An invalid option was encountered
            //
            throw UnexpectedOptionException(OPTION_PASSWORD);
        }
        if (_newpasswordSet)
        {
            //
            // An invalid option was encountered
            //
            throw UnexpectedOptionException(OPTION_NEW_PASSWORD);
        }
    }
}

/**
    Executes the command and writes the results to the PrintWriters.
*/
Uint32 CIMUserCommand::execute (
    ostream& outPrintWriter,
    ostream& errPrintWriter)
{
    if (_operationType == OPERATION_TYPE_UNINITIALIZED)
    {
        //
        // The command was not initialized
        //
        return 1;
    }
    //PEP#167 - Added Options HELP and VERSION
    //PEP#167 - CIMServer need not be running for these to work
    else if (_operationType == OPERATION_TYPE_HELP)
    {
        cerr << usage << endl;
        return (RC_SUCCESS);
    }
    else if(_operationType == OPERATION_TYPE_VERSION)
    {
        cerr << "Version " << PEGASUS_PRODUCT_VERSION << endl;
        return (RC_SUCCESS);
    }

    //
    // Get local host name
    //
    _hostName.assign(System::getHostName());

    try
    {
        // Construct the CIMClient and set to request server messages
        // in the default language of this client process.
        _client.reset(new CIMClient);
        _client->setRequestDefaultLanguages(); //l10n
    }
    catch (Exception & e)
    {
        errPrintWriter << e.getMessage() << endl;
        return (RC_ERROR);
    }

    try
    {
        //
        // Open connection with CIMSever
        //
        _client->connectLocal();
    }
    catch(const Exception&)
    {
        //l10n
        //outPrintWriter << CIMOM_NOT_RUNNING << endl;
        outPrintWriter << localizeMessage(MSG_PATH,CIMOM_NOT_RUNNING_KEY,CIMOM_NOT_RUNNING) << endl;
        return 1;
    }

    //
    // Perform the requested operation
    //
    switch (_operationType)
    {
        case OPERATION_TYPE_ADD:
            try
            {
                _AddUser(outPrintWriter, errPrintWriter);
            }
            catch (CIMException& e)
            {
                CIMStatusCode code = e.getCode();

                if (code == CIM_ERR_FAILED)
                {
                    //l10n
                    //outPrintWriter << ADD_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,ADD_USER_FAILURE_KEY,ADD_USER_FAILURE) << endl;
                    errPrintWriter << e.getMessage() << endl;
                }
                else if (code == CIM_ERR_NOT_SUPPORTED)
                {
                    //l10n
                    //outPrintWriter << ADD_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,ADD_USER_FAILURE_KEY,ADD_USER_FAILURE) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_ALREADY_EXISTS)
                {
                    //l10n
                    //outPrintWriter << ADD_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,ADD_USER_FAILURE_KEY,ADD_USER_FAILURE) << endl;
                    //outPrintWriter << USER_ALREADY_EXISTS << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,USER_ALREADY_EXISTS_KEY,USER_ALREADY_EXISTS) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_INVALID_CLASS)
                {
                    //l10n
                    //outPrintWriter << ADD_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,ADD_USER_FAILURE_KEY,ADD_USER_FAILURE) << endl;
                    //outPrintWriter << AUTH_SCHEMA_NOT_LOADED << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,AUTH_SCHEMA_NOT_LOADED_KEY,AUTH_SCHEMA_NOT_LOADED) << endl;
                }
                else
                {
                    errPrintWriter << e.getMessage() << endl;
                }
                return (RC_ERROR);
            }
            catch (Exception& e)
            {
                //l10n
                //outPrintWriter << ADD_USER_FAILURE << endl <<
                    //e.getMessage() << endl;
                outPrintWriter << localizeMessage(MSG_PATH,ADD_USER_FAILURE_KEY,ADD_USER_FAILURE) <<
                    endl << e.getMessage() << endl;
                return (RC_ERROR);
            }
            break;

            case OPERATION_TYPE_MODIFY:
            try
            {
                _ModifyUser(outPrintWriter, errPrintWriter);
            }
            catch (CIMException& e)
            {
                CIMStatusCode code = e.getCode();
                if (code == CIM_ERR_FAILED)
                {
                    //l10n
                    //outPrintWriter << CHANGE_PASSWORD_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_FAILURE_KEY,CHANGE_PASSWORD_FAILURE) << endl;
                    errPrintWriter << e.getMessage() << endl;
                }
                else if (code == CIM_ERR_NOT_SUPPORTED)
                {
                    //l10n
                    //outPrintWriter << CHANGE_PASSWORD_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_FAILURE_KEY,CHANGE_PASSWORD_FAILURE) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_NOT_FOUND)
                {
                    //l10n
                    //outPrintWriter << CHANGE_PASSWORD_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_FAILURE_KEY,CHANGE_PASSWORD_FAILURE) << endl;
                    //outPrintWriter << USER_NOT_FOUND          << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,USER_NOT_FOUND_KEY,USER_NOT_FOUND) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_INVALID_CLASS)
                {
                    //l10n
                    //outPrintWriter << CHANGE_PASSWORD_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_FAILURE_KEY,CHANGE_PASSWORD_FAILURE) << endl;
                    //outPrintWriter << AUTH_SCHEMA_NOT_LOADED << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,AUTH_SCHEMA_NOT_LOADED_KEY,AUTH_SCHEMA_NOT_LOADED) << endl;
                }
                else
                {
                    errPrintWriter << e.getMessage() << endl;
                }
                return (RC_ERROR);
            }
            catch (Exception& e)
            {
                //l10n
                //outPrintWriter << CHANGE_PASSWORD_FAILURE << endl <<
                    //e.getMessage() << endl;
                outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_FAILURE_KEY,CHANGE_PASSWORD_FAILURE) <<
                    endl << e.getMessage() << endl;
                return (RC_ERROR);
            }
            break;

        case OPERATION_TYPE_REMOVE:
            try
            {
                _RemoveUser(outPrintWriter, errPrintWriter);
            }
            catch (CIMException& e)
            {
                CIMStatusCode code = e.getCode();
                if (code == CIM_ERR_FAILED)
                {
                    //l10n
                    //outPrintWriter << REMOVE_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_FAILURE_KEY,REMOVE_USER_FAILURE) << endl;
                    errPrintWriter << e.getMessage() << endl;
                }
                else if (code == CIM_ERR_NOT_SUPPORTED)
                {
                    //l10n
                    //outPrintWriter << REMOVE_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_FAILURE_KEY,REMOVE_USER_FAILURE) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_NOT_FOUND)
                {
                    //l10n
                    //outPrintWriter << REMOVE_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_FAILURE_KEY,REMOVE_USER_FAILURE) << endl;
                    //outPrintWriter << USER_NOT_FOUND          << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,USER_NOT_FOUND_KEY,USER_NOT_FOUND) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_INVALID_CLASS)
                {
                    //l10n
                    //outPrintWriter << REMOVE_USER_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_FAILURE_KEY,REMOVE_USER_FAILURE) << endl;
                    //outPrintWriter << AUTH_SCHEMA_NOT_LOADED << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,AUTH_SCHEMA_NOT_LOADED_KEY,AUTH_SCHEMA_NOT_LOADED) << endl;
                }
                else
                {
                    errPrintWriter << e.getMessage() << endl;
                }
                return (RC_ERROR);
            }
            catch (Exception& e)
            {
                //l10n
                //outPrintWriter << REMOVE_USER_FAILURE << endl <<
                    //e.getMessage() << endl;
                outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_FAILURE_KEY,REMOVE_USER_FAILURE) <<
                endl << e.getMessage() << endl;
                return (RC_ERROR);
            }
            break;

        case OPERATION_TYPE_LIST:
            try
            {
                _ListUsers(outPrintWriter, errPrintWriter);
            }
            catch (CIMException& e)
            {
                CIMStatusCode code = e.getCode();
                if (code == CIM_ERR_FAILED)
                {
                    //l10n
                    //outPrintWriter << LIST_USERS_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,LIST_USERS_FAILURE_KEY,LIST_USERS_FAILURE) << endl;
                    errPrintWriter << e.getMessage() << endl;
                }
                else if (code == CIM_ERR_NOT_SUPPORTED)
                {
                    //l10n
                    //outPrintWriter << LIST_USERS_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,LIST_USERS_FAILURE_KEY,LIST_USERS_FAILURE) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_ALREADY_EXISTS)
                {
                    //l10n
                    //outPrintWriter << LIST_USERS_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,LIST_USERS_FAILURE_KEY,LIST_USERS_FAILURE) << endl;
                    errPrintWriter << e.getMessage()  << endl;
                }
                else if (code == CIM_ERR_INVALID_CLASS)
                {
                    //l10n
                    //outPrintWriter << LIST_USERS_FAILURE << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,LIST_USERS_FAILURE_KEY,LIST_USERS_FAILURE) << endl;
                    //outPrintWriter << AUTH_SCHEMA_NOT_LOADED << endl;
                    outPrintWriter << localizeMessage(MSG_PATH,AUTH_SCHEMA_NOT_LOADED_KEY,AUTH_SCHEMA_NOT_LOADED) << endl;
                }
                else
                {
                    errPrintWriter << e.getMessage() << endl;
                }
                return (RC_ERROR);
            }
            catch (Exception& e)
            {
                //l10n
                //outPrintWriter << LIST_USERS_FAILURE << endl <<
                    //e.getMessage() << endl;
                outPrintWriter << localizeMessage(MSG_PATH,LIST_USERS_FAILURE_KEY,LIST_USERS_FAILURE) <<
                    endl << e.getMessage() << endl;
                return (RC_ERROR);
            }
            break;

        default:
            //
            // Should never get here
            //
            break;
    }

    return (RC_SUCCESS);
}

/**
    Add the user to the CIM Server.
*/
void CIMUserCommand::_AddUser
    (
    ostream& outPrintWriter,
    ostream& errPrintWriter
    )
{
    CIMProperty prop;

    CIMInstance newInstance(PEGASUS_CLASSNAME_USER);
    newInstance.addProperty(
        CIMProperty(PROPERTY_NAME_USER_NAME, _userName));
    newInstance.addProperty(
        CIMProperty(PROPERTY_NAME_PASSWORD , _password));

    _client->createInstance(PEGASUS_NAMESPACENAME_USER, newInstance);
    //l10n
    //outPrintWriter << ADD_USER_SUCCESS << endl;
    outPrintWriter <<
        localizeMessage(MSG_PATH,ADD_USER_SUCCESS_KEY,ADD_USER_SUCCESS) << endl;
}

//
// Modify the password for a user
//
void CIMUserCommand::_ModifyUser
    (
    ostream& outPrintWriter,
    ostream& errPrintWriter
    )
{
    Array<CIMKeyBinding>      kbArray;
    CIMKeyBinding             kb;
    Array<CIMParamValue>   inParams;
    Array<CIMParamValue>   outParams;

    //
    // Build the input params
    //
    inParams.append(CIMParamValue(OLD_PASS_PARAM,
        CIMValue(_password)));
    inParams.append(CIMParamValue(NEW_PASS_PARAM,
        CIMValue(_newpassword)));

    kb.setName(CIMName ("Username"));
    kb.setValue(_userName);
    kb.setType(CIMKeyBinding::STRING);

    kbArray.append(kb);

    CIMObjectPath reference(
        _hostName, PEGASUS_NAMESPACENAME_USER,
        PEGASUS_CLASSNAME_USER, kbArray);

    //
    // Call the invokeMethod with the input parameters
    //

    //
    // Not checking for return code as all error conditions will
    // throw exceptions and will be handled by the catch block. If new
    // return codes are added in future, they need to be handled here.
    //
    CIMValue retValue = _client->invokeMethod(
        PEGASUS_NAMESPACENAME_USER,
        reference,
        MODIFY_METHOD,
        inParams,
        outParams);
    //l10n
    //outPrintWriter << CHANGE_PASSWORD_SUCCESS << endl;
    outPrintWriter << localizeMessage(MSG_PATH,CHANGE_PASSWORD_SUCCESS_KEY,CHANGE_PASSWORD_SUCCESS) << endl;
}

//
// Remove a user
//
void CIMUserCommand::_RemoveUser
    (
    ostream& outPrintWriter,
    ostream& errPrintWriter
    )
{
    Array<CIMKeyBinding> kbArray;
    CIMKeyBinding kb;

    kb.setName(PROPERTY_NAME_USER_NAME);
    kb.setValue(_userName);
    kb.setType(CIMKeyBinding::STRING);

    kbArray.append(kb);

    CIMObjectPath reference(
        _hostName, PEGASUS_NAMESPACENAME_USER,
        PEGASUS_CLASSNAME_USER, kbArray);

    _client->deleteInstance(PEGASUS_NAMESPACENAME_USER, reference);
    //l10n
    //outPrintWriter << REMOVE_USER_SUCCESS << endl;
    outPrintWriter << localizeMessage(MSG_PATH,REMOVE_USER_SUCCESS_KEY,REMOVE_USER_SUCCESS) << endl;
}

/**
    get a list of all user names from the CIM Server.
 */
void CIMUserCommand::_ListUsers
    (
    ostream& outPrintWriter,
    ostream& errPrintWriter
    )
{
    //
    // get all the instances of class PG_User
    //
    Array<CIMObjectPath> instanceNames =
        _client->enumerateInstanceNames(
            PEGASUS_NAMESPACENAME_USER,
            PEGASUS_CLASSNAME_USER);

    if (instanceNames.size() == 0)
    {
         //l10n
         //outPrintWriter << NO_USERS_FOUND << endl;
         outPrintWriter <<
             localizeMessage(MSG_PATH,NO_USERS_FOUND_KEY,NO_USERS_FOUND) <<
             endl;
    }
    else
    {
        //
        // List all the users.
        //
        for (Uint32 i = 0; i < instanceNames.size(); i++)
        {
            Array<CIMKeyBinding> kbArray = instanceNames[i].getKeyBindings();

            if (kbArray.size() > 0)
            {
                outPrintWriter << kbArray[0].getValue() << endl;
            }
        }
    }
}

PEGASUS_NAMESPACE_END

//
// exclude main from the Pegasus Namespace
//
PEGASUS_USING_PEGASUS;

PEGASUS_USING_STD;

///////////////////////////////////////////////////////////////////////////////
/**
    Parses the command line, and execute the command.

    @param   args  the string array containing the command line arguments
*/
///////////////////////////////////////////////////////////////////////////////

int main (int argc, char* argv[])
{
    AutoPtr<CIMUserCommand>  command;
    Uint32               retCode;

    MessageLoader::_useProcessLocale = true; //l10n set message loading to process locale
    MessageLoader::setPegasusMsgHomeRelative(argv[0]);

    //
    // Check if root is issuing the command
    //
    if (!System::isPrivilegedUser(System::getEffectiveUserName()))
    {
        MessageLoaderParms parms(NOT_PRIVILEGED_USER_KEY, NOT_PRIVILEGED_USER);
        parms.msg_src_path = MSG_PATH;
        cerr << MessageLoader::getMessage(parms) << endl;
        return 1;
    }

    command.reset(new CIMUserCommand ());

    try
    {
        command->setCommand ( cout, cerr, argc, argv);
    }
    catch (CommandFormatException& cfe)
    {
        String msg(cfe.getMessage());

        cerr << COMMAND_NAME << ": " << msg <<  endl;

        if (msg.find(String("Unknown flag")) != PEG_NOT_FOUND)
         {
           MessageLoaderParms parms(ERR_OPTION_NOT_SUPPORTED_KEY,ERR_OPTION_NOT_SUPPORTED);
           parms.msg_src_path = MSG_PATH;
           cerr << COMMAND_NAME <<
             ": " << MessageLoader::getMessage(parms) << endl;
         }
        else
         {
           MessageLoaderParms parms(ERR_USAGE_KEY,ERR_USAGE);
           parms.msg_src_path = MSG_PATH;
           cerr << COMMAND_NAME <<
             ": " << MessageLoader::getMessage(parms) << endl;
         }

        return 1;
    }

    retCode = command->execute (cout, cerr);

    return (retCode);
}


text:
package org.jboss.vfs;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSigner;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.jboss.vfs.util.FilterVirtualFileVisitor;
import org.jboss.vfs.util.MatchAllVirtualFileFilter;
import org.jboss.vfs.util.PathTokenizer;

/**
 * A virtual file.  This is a symbolic reference to a location in the virtual file system hierarchy.  Holding a {@code
 * VirtualFile} instance gives no guarantees as to the presence or immutability of the referenced file or any of its
 * parent path elements.
 *
 * @author Scott.Stark@jboss.org
 * @author adrian@jboss.org
 * @author Ales.Justin@jboss.org
 * @author David M. Lloyd
 * @version $Revision: 44334 $
 */
public final class VirtualFile implements Serializable {

    private static final long serialVersionUID = 1L;
    private final String name;
    private final String lcname;
    private final VirtualFile parent;
    private final int hashCode;
    private String pathName;

    VirtualFile(String name, VirtualFile parent) {
        this.name = name;
        lcname = name.toLowerCase();
        this.parent = parent;
        int result = parent == null ? 1 : parent.hashCode();
        result = 31 * result + name.hashCode();
        hashCode = result;
    }

    /**
     * Get the simple VF name (X.java)
     *
     * @return the simple file name
     */
    public String getName() {
        return name;
    }

    /**
     * Get the simple VF name mapped to lowercase (x.java) (used by case-insensitive filesystems like ZIP).
     *
     * @return the lowercase simple file name
     * @deprecated should not be used anymore, as the code is case-sensitive from JBVFS-170
     */
    public String getLowerCaseName() {
        return lcname;
    }

    /**
     * Get the absolute VFS full path name (/xxx/yyy/foo.ear/baz.jar/org/jboss/X.java)
     *
     * @return the VFS full path name
     */
    public String getPathName() {
        return getPathName(false);
    }

    /**
     * Get the path name relative to a parent virtual file.  If the given virtual file is not a parent of
     * this virtual file, then an {@code IllegalArgumentException} is thrown.
     *
     * @param parent the parent virtual file
     * @return the relative path name as a string
     * @throws IllegalArgumentException if the given virtual file is not a parent of this virtual file
     */
    public String getPathNameRelativeTo(VirtualFile parent) throws IllegalArgumentException {
        final StringBuilder builder = new StringBuilder(160);
        getPathNameRelativeTo(parent, builder);
        return builder.toString();
    }

    private void getPathNameRelativeTo(VirtualFile parent, StringBuilder builder) {
        if (this.parent == null) {
            throw VFSMessages.MESSAGES.parentIsNotAncestor(parent);
        }
        if (this.equals(parent)) {
            return;
        }
        if (!this.parent.equals(parent)) {
            this.parent.getPathNameRelativeTo(parent, builder);
            builder.append('/');
        }
        builder.append(name);
    }

    /**
     * Get the absolute VFS full path name. If this is a URL then directory entries will have a trailing slash.
     *
     * @param url whether or not this path is being used for a URL
     * @return the VFS full path name
     */
    String getPathName(boolean url) {
        if (pathName == null || pathName.isEmpty()) {
            VirtualFile[] path = getParentFiles();
            final StringBuilder builder = new StringBuilder(path.length * 30 + 50);
            for (int i = path.length - 1; i > -1; i--) {
                final VirtualFile parent = path[i].parent;
                if (parent == null) {
                    builder.append(path[i].name);
                } else {
                    if (parent.parent != null) {
                        builder.append('/');
                    }
                    builder.append(path[i].name);
                }
            }
            pathName = builder.toString();
        }
        // Perhaps this should be cached to avoid the fs stat call?
        return (url && isDirectory()) ? pathName.concat("/") : pathName;
    }

    /**
     * When the file was last modified
     *
     * @return the last modified time
     */
    public long getLastModified() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Long>) () -> mount.getFileSystem().getLastModified(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().getLastModified(mount.getMountPoint(), this);
    }

    /**
     * Get the size
     *
     * @return the size
     */
    public long getSize() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Long>) () -> mount.getFileSystem().getSize(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().getSize(mount.getMountPoint(), this);
    }

    /**
     * Tests whether the underlying implementation file still exists.
     *
     * @return true if the file exists, false otherwise.
     */
    public boolean exists() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Boolean>) () -> mount.getFileSystem().exists(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().exists(mount.getMountPoint(), this);
    }

    /**
     * Determines whether this virtual file represents a true root of a file system.
     * On UNIX, there is only one root "/". Howevever, on Windows there are an infinite
     * number of roots that correspond to drives, or UNC paths.
     *
     * @return {@code true} if this represents a root.
     */
    public boolean isRoot() {
        return parent == null;
    }

    /**
     * Whether it is a simple leaf of the VFS, i.e. whether it can contain other files
     *
     * @return {@code true} if a simple file
     * @deprecated use {@link #isDirectory()} or {@link #isFile()} instead
     */
    @Deprecated
    public boolean isLeaf() {
        return isFile();
    }

    /**
     * Determine whether the named virtual file is a plain file.
     *
     * @return {@code true} if it is a plain file, {@code false} otherwise
     */
    public boolean isFile() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Boolean>) () -> mount.getFileSystem().isFile(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().isFile(mount.getMountPoint(), this);
    }

    /**
     * Determine whether the named virtual file is a directory.
     *
     * @return {@code true} if it is a directory, {@code false} otherwise
     */
    public boolean isDirectory() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Boolean>) () -> mount.getFileSystem().isDirectory(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().isDirectory(mount.getMountPoint(), this);
    }

    /**
     * Access the file contents.
     *
     * @return an InputStream for the file contents.
     * @throws IOException for any error accessing the file system
     */
    public InputStream openStream() throws IOException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        if (isDirectory()) {
            return new VirtualJarInputStream(this);
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return doIoPrivileged(() -> mount.getFileSystem().openInputStream(mount.getMountPoint(), this));
        }
        return mount.getFileSystem().openInputStream(mount.getMountPoint(), this);
    }

    /**
     * Delete this virtual file
     *
     * @return {@code true} if file was deleted
     */
    public boolean delete() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "delete"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return AccessController.doPrivileged(
                    (PrivilegedAction<Boolean>) () -> mount.getFileSystem().delete(mount.getMountPoint(), this)
            );
        }
        return mount.getFileSystem().delete(mount.getMountPoint(), this);
    }

    /**
     * Get a physical file for this virtual file.  Depending on the underlying file system type, this may simply return
     * an already-existing file; it may create a copy of a file; or it may reuse a preexisting copy of the file.
     * Furthermore, the returned file may or may not have any relationship to other files from the same or any other
     * virtual directory.
     *
     * @return the physical file
     * @throws IOException if an I/O error occurs while producing the physical file
     */
    public File getPhysicalFile() throws IOException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "getfile"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        if (sm != null) {
            return doIoPrivileged(() -> mount.getFileSystem().getFile(mount.getMountPoint(), this));
        }
        return mount.getFileSystem().getFile(mount.getMountPoint(), this);
    }

    private static <T> T doIoPrivileged(PrivilegedExceptionAction<T> action) throws IOException {
        try {
            return AccessController.doPrivileged(action);
        } catch (PrivilegedActionException pe) {
            try {
                throw pe.getException();
            } catch (IOException | RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new UndeclaredThrowableException(e);
            }
        }
    }

    /**
     * Get a {@code VirtualFile} which represents the parent of this instance.
     *
     * @return the parent or {@code null} if there is no parent
     */
    public VirtualFile getParent() {
        return parent;
    }

    /**
     * Get the all the parent files of this virtual file from this file to the root.  The leafmost file will be at the
     * start of the array, and the rootmost will be at the end.
     *
     * @return the array of parent files
     */
    public VirtualFile[] getParentFiles() {
        return getParentFiles(0);
    }

    /**
     * Get the all the parent files of this virtual file from this file to the root as a list.  The leafmost file will be
     * at the start of the list, and the rootmost will be at the end.
     *
     * @return the list of parent files
     */
    public List<VirtualFile> getParentFileList() {
        return Arrays.asList(getParentFiles());
    }

    private VirtualFile[] getParentFiles(int idx) {
        final VirtualFile[] array;
        if (parent == null) {
            array = new VirtualFile[idx + 1];
        } else {
            array = parent.getParentFiles(idx + 1);
        }
        array[idx] = this;
        return array;
    }

    /**
     * Get the children.  This is the combined list of real children within this directory, as well as virtual children
     * created by submounts.
     *
     * @return the children
     */
    public List<VirtualFile> getChildren() {
        // isDirectory does the read security check
        if (!isDirectory()) { return Collections.emptyList(); }
        final VFS.Mount mount = VFS.getMount(this);
        final Set<String> submounts = VFS.getSubmounts(this);
        final List<String> names = mount.getFileSystem().getDirectoryEntries(mount.getMountPoint(), this);
        final List<VirtualFile> virtualFiles = new ArrayList<VirtualFile>(names.size() + submounts.size());
        for (String name : names) {
            final VirtualFile child = new VirtualFile(name, this);
            virtualFiles.add(child);
            submounts.remove(name);
        }
        for (String name : submounts) {
            final VirtualFile child = new VirtualFile(name, this);
            virtualFiles.add(child);
        }
        return virtualFiles;
    }

    /**
     * Get the children
     *
     * @param filter to filter the children
     * @return the children
     * @throws IOException           for any problem accessing the virtual file system
     * @throws IllegalStateException if the file is closed or it is a leaf node
     */
    public List<VirtualFile> getChildren(VirtualFileFilter filter) throws IOException {
        // isDirectory does the read security check
        if (!isDirectory()) { return Collections.emptyList(); }
        if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }
        FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, null);
        visit(visitor);
        return visitor.getMatched();
    }

    /**
     * Get all the children recursively

     *

     * This always uses {@link VisitorAttributes#RECURSE}
     *
     * @return the children
     * @throws IOException           for any problem accessing the virtual file system
     * @throws IllegalStateException if the file is closed
     */
    public List<VirtualFile> getChildrenRecursively() throws IOException {
        return getChildrenRecursively(null);
    }

    /**
     * Get all the children recursively

     *

     * This always uses {@link VisitorAttributes#RECURSE}
     *
     * @param filter to filter the children
     * @return the children
     * @throws IOException           for any problem accessing the virtual file system
     * @throws IllegalStateException if the file is closed or it is a leaf node
     */
    public List<VirtualFile> getChildrenRecursively(VirtualFileFilter filter) throws IOException {
        // isDirectory does the read security check
        if (!isDirectory()) { return Collections.emptyList(); }
        if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }
        FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, VisitorAttributes.RECURSE);
        visit(visitor);
        return visitor.getMatched();
    }

    /**
     * Visit the virtual file system
     *
     * @param visitor the visitor
     * @throws IOException              for any problem accessing the virtual file system
     * @throws IllegalArgumentException if the visitor is null
     * @throws IllegalStateException    if the file is closed
     */
    public void visit(VirtualFileVisitor visitor) throws IOException {
        visit(visitor, true);
    }

    private void visit(VirtualFileVisitor visitor, boolean root) throws IOException {
        final VisitorAttributes visitorAttributes = visitor.getAttributes();
        if (root && visitorAttributes.isIncludeRoot()) { visitor.visit(this); }
        // isDirectory does the read security check
        if (!isDirectory()) { return; }
        for (VirtualFile child : getChildren()) {
            // Always visit a leaf, and visit directories when leaves only is false
            if (!child.isDirectory() || !visitorAttributes.isLeavesOnly()) { visitor.visit(child); }
            if (child.isDirectory() && visitorAttributes.isRecurse(child)) { child.visit(visitor, false); }
        }
    }

    /**
     * Get a child virtual file.  The child may or may not exist in the virtual filesystem.
     *
     * @param path the path
     * @return the child
     * @throws IllegalArgumentException if the path is null
     */
    public VirtualFile getChild(String path) {
        if (path == null) {
            throw VFSMessages.MESSAGES.nullArgument("path");
        }
        final List<String> pathParts = PathTokenizer.getTokens(path);
        VirtualFile current = this;
        for (String part : pathParts) {
            if (PathTokenizer.isReverseToken(part)) {
                final VirtualFile parent = current.parent;
                current = parent == null ? current : parent;
            } else if (PathTokenizer.isCurrentToken(part) == false) {
                current = new VirtualFile(part, current);
            }
        }
        return current;
    }

    /**
     * Get file's current URL.  Note: if this VirtualFile refers to a directory at the time of this
     * method invocation, a trailing slash will be appended to the URL; this means that invoking
     * this method may require a filesystem access, and in addition, may not produce consistent results
     * over time.
     *
     * @return the current url
     * @throws MalformedURLException if the URL is somehow malformed
     * @see VirtualFile#asDirectoryURL()
     * @see VirtualFile#asFileURL()
     */
    public URL toURL() throws MalformedURLException {
        return VFSUtils.getVirtualURL(this);
    }

    /**
     * Get file's current URI.  Note: if this VirtualFile refers to a directory at the time of this
     * method invocation, a trailing slash will be appended to the URI; this means that invoking
     * this method may require a filesystem access, and in addition, may not produce consistent results
     * over time.
     *
     * @return the current uri
     * @throws URISyntaxException if the URI is somehow malformed
     * @see VirtualFile#asDirectoryURI()
     * @see VirtualFile#asFileURI()
     */
    public URI toURI() throws URISyntaxException {
        return VFSUtils.getVirtualURI(this);
    }

    /**
     * Get file's URL as a directory.  There will always be a trailing {@code "/"} character.
     *
     * @return the url
     * @throws MalformedURLException if the URL is somehow malformed
     */
    public URL asDirectoryURL() throws MalformedURLException {
        final String pathName = getPathName(false);
        return new URL(VFSUtils.VFS_PROTOCOL, "", -1, parent == null ? pathName : pathName + "/", VFSUtils.VFS_URL_HANDLER);
    }

    /**
     * Get file's URI as a directory.  There will always be a trailing {@code "/"} character.
     *
     * @return the uri
     * @throws URISyntaxException if the URI is somehow malformed
     */
    public URI asDirectoryURI() throws URISyntaxException {
        final String pathName = getPathName(false);
        return new URI(VFSUtils.VFS_PROTOCOL, "", parent == null ? pathName : pathName + "/", null);
    }

    /**
     * Get file's URL as a file.  There will be no trailing {@code "/"} character unless this {@code VirtualFile}
     * represents a root.
     *
     * @return the url
     * @throws MalformedURLException if the URL is somehow malformed
     */
    public URL asFileURL() throws MalformedURLException {
        return new URL(VFSUtils.VFS_PROTOCOL, "", -1, getPathName(false), VFSUtils.VFS_URL_HANDLER);
    }

    /**
     * Get file's URI as a file.  There will be no trailing {@code "/"} character unless this {@code VirtualFile}
     * represents a root.
     *
     * @return the url
     * @throws URISyntaxException if the URI is somehow malformed
     */
    public URI asFileURI() throws URISyntaxException {
        return new URI(VFSUtils.VFS_PROTOCOL, "", getPathName(false), null);
    }

    /**
     * Get the {@link CodeSigner}s for a the virtual file.
     *
     * @return the {@link CodeSigner}s for the virtual file, or {@code null} if not signed
     */
    public CodeSigner[] getCodeSigners() {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
        }
        final VFS.Mount mount = VFS.getMount(this);
        return mount.getFileSystem().getCodeSigners(mount.getMountPoint(), this);
    }

    /**
     * Get the {@link Certificate}s for the virtual file.  Simply extracts the certificate entries from
     * the code signers array.
     *
     * @return the certificates for the virtual file, or {@code null} if not signed
     */
    public Certificate[] getCertificates() {
        // getCodeSigners() does the sec check
        final CodeSigner[] codeSigners = getCodeSigners();
        if (codeSigners == null) {
            return null;
        }
        final List<Certificate> certList = new ArrayList<Certificate>(codeSigners.length * 3);
        for (CodeSigner signer : codeSigners) {
            certList.addAll(signer.getSignerCertPath().getCertificates());
        }
        return certList.toArray(new Certificate[certList.size()]);
    }

    /**
     * Get a human-readable (but non-canonical) representation of this virtual file.
     *
     * @return the string
     */
    public String toString() {
        return '"' + getPathName() + '"';
    }

    /**
     * Determine whether the given object is equal to this one.  Returns true if the argument is a {@code VirtualFile}
     * from the same {@code VFS} instance with the same name.
     *
     * @param o the other object
     * @return {@code true} if they are equal
     */
    public boolean equals(Object o) {
        return o instanceof VirtualFile && equals((VirtualFile) o);
    }

    /**
     * Determine whether the given object is equal to this one.  Returns true if the argument is a {@code VirtualFile}
     * from the same {@code VFS} instance with the same name.
     *
     * @param o the other virtual file
     * @return {@code true} if they are equal
     */
    public boolean equals(VirtualFile o) {
        if (o == this) {
            return true;
        }
        if (o == null || hashCode != o.hashCode || !name.equals(o.name)) {
            return false;
        }
        final VirtualFile parent = this.parent;
        final VirtualFile oparent = o.parent;
        return parent != null && parent.equals(oparent) || oparent == null;
    }

    /**
     * Get a hashcode for this virtual file.
     *
     * @return the hash code
     */
    public int hashCode() {
        return hashCode;
    }
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

abstract class Minion_Database extends Minion_Task {

	protected function db_params($database)
	{
		$db = Kohana::$config->load("database.$database.connection");

		if ( ! isset($db['database']) )
		{
			if ( ! preg_match('/dbname=([^;]+)/', $db['dsn'], $matches))
				throw new Kohana_Exception("Error connecting to database, database missing");

			$db['database'] = $matches[1];
		}

		$db['type'] = Kohana::$config->load("database.$database.type");

		return $db;
	}
}