text:
require 'spec_helper'

describe Chef::Mixin::Securable do

  before(:each) do
    @securable = Object.new
    @securable.send(:extend, Chef::Mixin::Securable)
    @securable.send(:extend, Chef::Mixin::ParamsValidate)
  end

  it "should accept a group name or id for group" do
    lambda { @securable.group "root" }.should_not raise_error
    lambda { @securable.group 123 }.should_not raise_error
    lambda { @securable.group "+bad:group" }.should raise_error(ArgumentError)
  end

  it "should accept a user name or id for owner" do
    lambda { @securable.owner "root" }.should_not raise_error
    lambda { @securable.owner 123 }.should_not raise_error
    lambda { @securable.owner "+bad:owner" }.should raise_error(ArgumentError)
  end

  it "allows the owner to be specified as #user" do
    @securable.should respond_to(:user)
  end

  describe "unix-specific behavior" do
    before(:each) do
      platform_mock :unix do
        load File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "chef", "config.rb")
        load File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "chef", "mixin", "securable.rb")
        @securable = Object.new
        @securable.send(:extend, Chef::Mixin::Securable)
        @securable.send(:extend, Chef::Mixin::ParamsValidate)
      end
    end

    it "should accept group/owner names with spaces and backslashes" do
      lambda { @securable.group 'test\ group' }.should_not raise_error
      lambda { @securable.owner 'test\ group' }.should_not raise_error
    end

    it "should accept group/owner names that are a single character or digit" do
      lambda { @securable.group 'v' }.should_not raise_error
      lambda { @securable.group '1' }.should_not raise_error
      lambda { @securable.owner 'v' }.should_not raise_error
      lambda { @securable.owner '1' }.should_not raise_error
    end

    it "should not accept group/owner names starting with '-', '+', or '~'" do
      lambda { @securable.group '-test' }.should raise_error(ArgumentError)
      lambda { @securable.group '+test' }.should raise_error(ArgumentError)
      lambda { @securable.group '~test' }.should raise_error(ArgumentError)
      lambda { @securable.group 'te-st' }.should_not raise_error
      lambda { @securable.group 'te+st' }.should_not raise_error
      lambda { @securable.group 'te~st' }.should_not raise_error
      lambda { @securable.owner '-test' }.should raise_error(ArgumentError)
      lambda { @securable.owner '+test' }.should raise_error(ArgumentError)
      lambda { @securable.owner '~test' }.should raise_error(ArgumentError)
      lambda { @securable.owner 'te-st' }.should_not raise_error
      lambda { @securable.owner 'te+st' }.should_not raise_error
      lambda { @securable.owner 'te~st' }.should_not raise_error
    end

    it "should not accept group/owner names containing ':', ',' or non-space whitespace" do
      lambda { @securable.group ':test' }.should raise_error(ArgumentError)
      lambda { @securable.group 'te:st' }.should raise_error(ArgumentError)
      lambda { @securable.group ',test' }.should raise_error(ArgumentError)
      lambda { @securable.group 'te,st' }.should raise_error(ArgumentError)
      lambda { @securable.group "\ttest" }.should raise_error(ArgumentError)
      lambda { @securable.group "te\tst" }.should raise_error(ArgumentError)
      lambda { @securable.group "\rtest" }.should raise_error(ArgumentError)
      lambda { @securable.group "te\rst" }.should raise_error(ArgumentError)
      lambda { @securable.group "\ftest" }.should raise_error(ArgumentError)
      lambda { @securable.group "te\fst" }.should raise_error(ArgumentError)
      lambda { @securable.group "\0test" }.should raise_error(ArgumentError)
      lambda { @securable.group "te\0st" }.should raise_error(ArgumentError)
      lambda { @securable.owner ':test' }.should raise_error(ArgumentError)
      lambda { @securable.owner 'te:st' }.should raise_error(ArgumentError)
      lambda { @securable.owner ',test' }.should raise_error(ArgumentError)
      lambda { @securable.owner 'te,st' }.should raise_error(ArgumentError)
      lambda { @securable.owner "\ttest" }.should raise_error(ArgumentError)
      lambda { @securable.owner "te\tst" }.should raise_error(ArgumentError)
      lambda { @securable.owner "\rtest" }.should raise_error(ArgumentError)
      lambda { @securable.owner "te\rst" }.should raise_error(ArgumentError)
      lambda { @securable.owner "\ftest" }.should raise_error(ArgumentError)
      lambda { @securable.owner "te\fst" }.should raise_error(ArgumentError)
      lambda { @securable.owner "\0test" }.should raise_error(ArgumentError)
      lambda { @securable.owner "te\0st" }.should raise_error(ArgumentError)
    end

    it "should accept Active Directory-style domain names pulled in via LDAP (on unix hosts)" do
      lambda { @securable.owner "domain\@user" }.should_not raise_error
      lambda { @securable.owner "domain\\user" }.should_not raise_error
      lambda { @securable.group "domain\@group" }.should_not raise_error
      lambda { @securable.group "domain\\group" }.should_not raise_error
      lambda { @securable.group "domain\\group^name" }.should_not raise_error
    end

    it "should not accept group/owner names containing embedded carriage returns" do
      pending "XXX: params_validate needs to be extended to support multi-line regex"
      #lambda { @securable.group "\ntest" }.should raise_error(ArgumentError)
      #lambda { @securable.group "te\nst" }.should raise_error(ArgumentError)
      #lambda { @securable.owner "\ntest" }.should raise_error(ArgumentError)
      #lambda { @securable.owner "te\nst" }.should raise_error(ArgumentError)
    end

    it "should accept group/owner names in UTF-8" do
      lambda { @securable.group 'tëst' }.should_not raise_error
      lambda { @securable.group 'ë' }.should_not raise_error
      lambda { @securable.owner 'tëst' }.should_not raise_error
      lambda { @securable.owner 'ë' }.should_not raise_error
    end

    it "should accept a unix file mode in string form as an octal number" do
      lambda { @securable.mode "0" }.should_not raise_error
      lambda { @securable.mode "0000" }.should_not raise_error
      lambda { @securable.mode "0111" }.should_not raise_error
      lambda { @securable.mode "0444" }.should_not raise_error

      lambda { @securable.mode "111" }.should_not raise_error
      lambda { @securable.mode "444" }.should_not raise_error
      lambda { @securable.mode "7777" }.should_not raise_error
      lambda { @securable.mode "07777" }.should_not raise_error

      lambda { @securable.mode "-01" }.should raise_error(ArgumentError)
      lambda { @securable.mode "010000" }.should raise_error(ArgumentError)
      lambda { @securable.mode "-1" }.should raise_error(ArgumentError)
      lambda { @securable.mode "10000" }.should raise_error(ArgumentError)

      lambda { @securable.mode "07778" }.should raise_error(ArgumentError)
      lambda { @securable.mode "7778" }.should raise_error(ArgumentError)
      lambda { @securable.mode "4095" }.should raise_error(ArgumentError)

      lambda { @securable.mode "0foo1234" }.should raise_error(ArgumentError)
      lambda { @securable.mode "foo1234" }.should raise_error(ArgumentError)
    end

    it "should accept a unix file mode in numeric form as a ruby-interpreted integer" do
      lambda { @securable.mode 0 }.should_not raise_error
      lambda { @securable.mode 0000 }.should_not raise_error
      lambda { @securable.mode 444 }.should_not raise_error
      lambda { @securable.mode 0444 }.should_not raise_error
      lambda { @securable.mode 07777 }.should_not raise_error

      lambda { @securable.mode 292 }.should_not raise_error
      lambda { @securable.mode 4095 }.should_not raise_error

      lambda { @securable.mode 0111 }.should_not raise_error
      lambda { @securable.mode 73 }.should_not raise_error

      lambda { @securable.mode -01 }.should raise_error(ArgumentError)
      lambda { @securable.mode 010000 }.should raise_error(ArgumentError)
      lambda { @securable.mode -1 }.should raise_error(ArgumentError)
      lambda { @securable.mode 4096 }.should raise_error(ArgumentError)
    end
  end

  describe "windows-specific behavior" do
    before(:each) do
      platform_mock :windows do
        load File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "chef", "config.rb")
        load File.join(File.dirname(__FILE__), "..", "..", "..", "lib", "chef", "mixin", "securable.rb")
        SECURABLE_CLASS = Class.new do
          include Chef::Mixin::Securable
          include Chef::Mixin::ParamsValidate
        end
        @securable = SECURABLE_CLASS.new
      end
    end

    it "should not accept a group name or id for group with spaces and multiple backslashes" do
      lambda { @securable.group 'test\ \group' }.should raise_error(ArgumentError)
    end

    it "should accept a unix file mode in string form as an octal number" do
      lambda { @securable.mode "0" }.should_not raise_error
      lambda { @securable.mode "0000" }.should_not raise_error
      lambda { @securable.mode "0111" }.should_not raise_error
      lambda { @securable.mode "0444" }.should_not raise_error

      lambda { @securable.mode "111" }.should_not raise_error
      lambda { @securable.mode "444" }.should_not raise_error
      lambda { @securable.mode "7777" }.should raise_error(ArgumentError)
      lambda { @securable.mode "07777" }.should raise_error(ArgumentError)

      lambda { @securable.mode "-01" }.should raise_error(ArgumentError)
      lambda { @securable.mode "010000" }.should raise_error(ArgumentError)
      lambda { @securable.mode "-1" }.should raise_error(ArgumentError)
      lambda { @securable.mode "10000" }.should raise_error(ArgumentError)

      lambda { @securable.mode "07778" }.should raise_error(ArgumentError)
      lambda { @securable.mode "7778" }.should raise_error(ArgumentError)
      lambda { @securable.mode "4095" }.should raise_error(ArgumentError)

      lambda { @securable.mode "0foo1234" }.should raise_error(ArgumentError)
      lambda { @securable.mode "foo1234" }.should raise_error(ArgumentError)
    end

    it "should accept a unix file mode in numeric form as a ruby-interpreted integer" do
      lambda { @securable.mode 0 }.should_not raise_error
      lambda { @securable.mode 0000 }.should_not raise_error
      lambda { @securable.mode 444 }.should_not raise_error
      lambda { @securable.mode 0444 }.should_not raise_error
      lambda { @securable.mode 07777 }.should raise_error(ArgumentError)

      lambda { @securable.mode 292 }.should_not raise_error
      lambda { @securable.mode 4095 }.should raise_error(ArgumentError)

      lambda { @securable.mode 0111 }.should_not raise_error
      lambda { @securable.mode 73 }.should_not raise_error

      lambda { @securable.mode -01 }.should raise_error(ArgumentError)
      lambda { @securable.mode 010000 }.should raise_error(ArgumentError)
      lambda { @securable.mode -1 }.should raise_error(ArgumentError)
      lambda { @securable.mode 4096 }.should raise_error(ArgumentError)
    end

    it "should allow you to specify :full_control, :modify, :read_execute, :read, and :write rights" do
      lambda { @securable.rights :full_control, "The Dude" }.should_not raise_error
      lambda { @securable.rights :modify, "The Dude" }.should_not raise_error
      lambda { @securable.rights :read_execute, "The Dude" }.should_not raise_error
      lambda { @securable.rights :read, "The Dude" }.should_not raise_error
      lambda { @securable.rights :write, "The Dude" }.should_not raise_error
      lambda { @securable.rights :to_party, "The Dude" }.should raise_error(ArgumentError)
    end

    it "should allow you to specify :full_control, :modify, :read_execute, :read, and :write deny_rights" do
      lambda { @securable.deny_rights :full_control, "The Dude" }.should_not raise_error
      lambda { @securable.deny_rights :modify, "The Dude" }.should_not raise_error
      lambda { @securable.deny_rights :read_execute, "The Dude" }.should_not raise_error
      lambda { @securable.deny_rights :read, "The Dude" }.should_not raise_error
      lambda { @securable.deny_rights :write, "The Dude" }.should_not raise_error
      lambda { @securable.deny_rights :to_party, "The Dude" }.should raise_error(ArgumentError)
    end

    it "should accept a principal as a string or an array" do
      lambda { @securable.rights :read, "The Dude" }.should_not raise_error
      lambda { @securable.rights :read, ["The Dude","Donny"] }.should_not raise_error
      lambda { @securable.rights :read, 3 }.should raise_error(ArgumentError)
    end

    it "should allow you to specify whether the permissions applies_to_children with true/false/:containers_only/:objects_only" do
      lambda { @securable.rights :read, "The Dude", :applies_to_children => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => :containers_only }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => :objects_only }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => 'poop' }.should raise_error(ArgumentError)
    end

    it "should allow you to specify whether the permissions applies_to_self with true/false" do
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_self => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_self => 'poop' }.should raise_error(ArgumentError)
    end

    it "should allow you to specify whether the permissions applies one_level_deep with true/false" do
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => 'poop' }.should raise_error(ArgumentError)
    end

    it "should allow multiple rights and deny_rights declarations" do
      @securable.rights :read, "The Dude"
      @securable.deny_rights :full_control, "The Dude"
      @securable.rights :full_control, "The Dude"
      @securable.rights :write, "The Dude"
      @securable.deny_rights :read, "The Dude"
      @securable.rights.size.should == 3
      @securable.deny_rights.size.should == 2
    end

    it "should allow you to specify whether the permission applies_to_self only if you specified applies_to_children" do
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => false }.should raise_error(ArgumentError)
      lambda { @securable.rights :read, "The Dude", :applies_to_self => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_self => false }.should_not raise_error
    end

    it "should allow you to specify whether the permission applies one_level_deep only if you specified applies_to_children" do
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => true }.should raise_error(ArgumentError)
      lambda { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => false }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :one_level_deep => true }.should_not raise_error
      lambda { @securable.rights :read, "The Dude", :one_level_deep => false }.should_not raise_error
    end

    it "should allow you to specify whether the permissions inherit with true/false" do
      lambda { @securable.inherits true }.should_not raise_error
      lambda { @securable.inherits false }.should_not raise_error
      lambda { @securable.inherits "monkey" }.should raise_error(ArgumentError)
    end
  end
end


text:
Build Management Tools
======================

# Overview #
The build management repository contains a collection of tools and
applications for creating an enterprise build and release infrastructure.
The central focus of this project is to utilize a relational database to
capture build information.  Tools and applications are provided to populate
the database with build content, as well as to view and manage the build
content and artifacts.

## Project Goals ##
The goal of this project is not to reinvent the type of scheduling
automation or code analysis tools already available, it is to provide
an infrastructure for capturing historical build information and tools
for performing enterprise-level tasks using that data.  To achieve that
objective, the build management database serves as the focal point for
the project.

* Create a scalable infrastructure for capturing and managing build
  information.
* Provide integration with 3rd party such as source control, bug tracking,
  continuous integration, and automated test frameworks.
* Provide visibility into historical build results and trends.

## Project Components ##
This project uses Maven to provide the structure and tools for building
and packaging project artifacts.  This is a multi-module project composed
of the following components:

* Core API
* Ant Tasks
* Service Patch Tool
* Build Management Web Application

Each of these components can be used independenly or as a complete suite
of tools.  For details on each project, please read the README files in
each project directory, or view the project documentation found on the
project website.

## Project Documentation ##

A copy of the latest project documentation is available on the [project
website].  Project documentation can also be generated locally using Maven:

    mvn package
    mvn install
    mvn site

# System Requirements #

The following are required if building this project from source:

* Maven 3.0+
* JDK 1.6

Please refer to the documentation for each sub-module for the list of
requirements specific to that project.

## Pre-requisites ##

The following pre-requisites must be available in your local environment
if you wish to compile and package this project using Maven:

1. Install Oracle JDBC jar into the local Maven repository (*required*)

   Obtain a local copy of the JDBC jar (either from the installed
   database or by downloading directly from Oracle).

        mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.4 -Dpackaging=jar -Dfile=/path/to/file/ojdbc6.jar -DgeneratePom=true

2. Install the native `rpmbuild` command (*optional*)

   Some project artificates have been configured to be generate an RPM file,
   which makes it much easier to deploy on some Linux systems.  If you would
   like to generate RPMs for projects which support it, you will need to
   ensure that your system has the `rpmbuild` command available.  Here is an
   example of how to install that command on a RedHat system:

        yum install rpm-build

3. Customize your Maven `settings.xml` file:

    <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          http://maven.apache.org/xsd/settings-1.0.0.xsd">

      ...
      <pluginGroups>
        <pluginGroup>org.eclipse.jetty</pluginGroup>
      </pluginGroups>
    </settings>

# Installation #

Each module within this project produces a separate build artifact.  Each
artifact will have it's own unique installation requirements.  The following
table illustrates the type of artifact produced by each module.

| Project          | Output      |
| ---------------- | ----------- |
| mn-build-core    | jar         |
| mn-build-ant     | jar         |
| mn-build-patch   | jar, rpm    |
| mn-build-webapp  | war         |

## Downloading ##

Individual project components may be available for download from the
[project website].

## Compiling from Source ##

Run a Maven build

    mvn package

### Profiles ###

Maven profiles can be used to alter the behavior of the build process.
In this project, profiles are used to select the type of project
artifact to generate during the build.  For example, by default a
project may produce a `jar` file.  However, for ease of deployment,
the project may provide an `rpm` profile to produce an additional
RPM file which can be used to easily deploy the project binaries to
a Linux system.

A Maven profile can be selected during the build process by using
the following command-line syntax:

    mvn package -P <profile>

The following Maven profiles are supported:

#### rpm ####

If applicable, the `rpm` profile can be used to generate RPMs
as an artifact of the build.  To do this, ensure that you have
the rpmbuild executable available on your system (see the
system pre-requisites listed above for details on how to
install it).

#### installer ####

If applicable, the `installer` profile can be used to generate
an install package.  This provides a platform-independent
user interface for installing the project.

# References #

* The Build Management Tools [project website]

[project website]: http://buildmanagement.modeln.com

redpajama_set_name: RedPajamaGithub


text:
  Blog |
  Archive |
  Resume |
  Projects


text:
package com.izforge.izpack.compiler;

import static org.hamcrest.MatcherAssert.assertThat;

import java.util.jar.JarFile;
import java.util.zip.ZipFile;

import org.hamcrest.core.IsCollectionContaining;
import org.hamcrest.core.IsNot;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.izforge.izpack.compiler.container.TestCompilerContainer;
import com.izforge.izpack.core.container.AbstractContainer;
import com.izforge.izpack.matcher.ZipMatcher;
import com.izforge.izpack.test.Container;
import com.izforge.izpack.test.InstallFile;
import com.izforge.izpack.test.junit.PicoRunner;

/**
 * Test for an Izpack compilation
 */
@RunWith(PicoRunner.class)
@Container(TestCompilerContainer.class)
public class CompilerConfigSamplesTest
{
    private JarFile jar;
    private CompilerConfig compilerConfig;
    private AbstractContainer testContainer;

    public CompilerConfigSamplesTest(TestCompilerContainer container, CompilerConfig compilerConfig)
    {
        this.testContainer = container;
        this.compilerConfig = compilerConfig;
    }

    @Test
    @InstallFile("samples/izpack.xml")
    public void installerShouldContainInstallerClassResourcesAndImages() throws Exception
    {
        compilerConfig.executeCompiler();
        jar = testContainer.getComponent(JarFile.class);
        assertThat((ZipFile)jar, ZipMatcher.isZipContainingFiles(
                "com/izforge/izpack/panels/checkedhello/CheckedHelloPanel.class",
                "resources/vars",
                "com/izforge/izpack/img/JFrameIcon.png"));
    }

    @Test
    @InstallFile("samples/silverpeas/silverpeas.xml")
    public void installerShouldMergeProcessPanelCorrectly() throws Exception
    {
        compilerConfig.executeCompiler();
        jar = testContainer.getComponent(JarFile.class);
        assertThat((ZipFile)jar, ZipMatcher.isZipMatching(IsNot.not(IsCollectionContaining.hasItems(
                "com/izforge/izpack/panels/process/VariableCondition.class",
                "com/sora/panel/VimPanel.class",
                "resource/32/help-browser.png"))));
    }

    @Test
    @InstallFile("samples/silverpeas/silverpeas.xml")
    public void installerShouldConfigureSplashScreenCorrectly() throws Exception
    {
        compilerConfig.executeCompiler();
        jar = testContainer.getComponent(JarFile.class);
        assertThat((ZipFile)jar, ZipMatcher.isZipContainingFiles(
                "resources/Splash.image"));
    }

    @Test
    @InstallFile("samples/izpack-jdk11-min.xml")
    public void installerShouldContainInstallerJdk11() throws Exception
    {
        compilerConfig.executeCompiler();
        jar = testContainer.getComponent(JarFile.class);
        assertThat((ZipFile)jar, ZipMatcher.isZipContainingFiles(
                "com/izforge/izpack/panels/checkedhello/CheckedHelloPanel.class",
                "resources/vars",
                "com/izforge/izpack/img/JFrameIcon.png"));
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

            Open source Restful Api integrated testing tool

                Welcome to use HitchhikerAPI !{{inviter}} invite you to join {{project}} project.

                Click buttons below to join or reject (if accept, will auto generte a account for your and send you a mail about password):

                    Join

                    Reject

 kind send email to us if any problem support@hitchhiker-api.com

                website: http://www.hitchhiker-api.com/

                github: http://www.github.com/brookshi/hitchhiker/

This mail is auto generated, please don't reply.


text:
__all__ = ['prepare_django_object', 'import_django_models']

DEFAULT_RENAMINGS = {
    '_state': None,
    'id': None,
}

def get_field_meta(instance, name):
    if name in instance._meta.get_all_field_names():
        return instance._meta.get_field_by_name(name)[0]
    return None

def make_obj_pk(instance):
    return make_pk(instance._meta.object_name, instance.pk)

def make_pk(obj_name, obj_pk):
    return u'%s:%s' % (obj_name, obj_pk)

def prepare_django_object(instance, renamings=None):
    """
    Converts given Django model to a dictionary ready for Tokyo Cabinet.
    Does not save anything, only returns the dictionary.
    """
    orig_data = instance.__dict__
    data = {
        'django_model': instance._meta.object_name,
        'django_id': instance.pk,
    }
    renamings = dict(DEFAULT_RENAMINGS, **renamings or {})
    for key, value in orig_data.iteritems():
        if key.endswith('_id'):
            key = key[:-3]

        field_meta = get_field_meta(instance, key)

        # key conversion
        if key in renamings:
            key = renamings[key]
            if not key:
                continue

        # value conversion
        if field_meta and field_meta.rel:
            if value:
                data[key] = make_pk(field_meta.rel.to._meta.object_name, value)
        else:
            data[key] = '' if value is None else unicode(value)
    return data

def import_django_models(database, models, renamings=None, dry_run=False):
    """
    Converts and saves multiple Django models to Tokyo Cabinet.

    :param tyrant: an instance of pyrant.Tyrant (actually any dict-like object
        will do)
    :param models: a list of Django models to convert. The order does not matter
        because we do not follow foreign keys, we just save their values in the
        same format as document keys, so if the referenced item is ever going
        to be imported, its key will match the value of the reference field.
        I think I should get a nap.
    :param renamings: a dict of dicts, e.g. ``{Note: {'text': 'summary'}}`` which
        reads as "when importing Note objects, rename field `text` to `summary`".
        Setting new value to None (e.g. ``{Note: {'text': None}`}` removes this
        field from the results. By default we only remove `id` and `_state`.
    :param dry_run: convert data but don't save to Tokyo. Default is False.

    Usage::

        from pyrant import Tyrant
        from pyrant.utils.django import import_django_models

        # load your Django models
        from myapp.models import Category, Note

        database = Tyrant(host='127.0.0.1', port=1978)
        models = Category, Note
        renamings = {
            Category: {'name': 'title'},
            Note:  {'text': 'summary', 'some_legacy_field: None},
        }

        import_django_models(database, models, renamings, dry_run=True)

    """
    for model in models:
        print 'converting all %(count)d %(model)s objects...' % {
            'model': model._meta.object_name,
            'count': model.objects.count(),
        }
        model_renamings = renamings.get(model, None)
        for instance in model.objects.all():
            key = make_obj_pk(instance)
            prepared_dict = prepare_django_object(instance, model_renamings)
            if not dry_run:
                database[key] = prepared_dict


text:
namespace file_manager_private = extensions::api::file_manager_private;

namespace file_manager {
namespace util {
namespace {

// The struct is used for GetSelectedFileInfo().
struct GetSelectedFileInfoParams {
  GetSelectedFileInfoLocalPathOption local_path_option;
  GetSelectedFileInfoCallback callback;
  std::vector<base::FilePath> file_paths;
  std::vector<ui::SelectedFileInfo> selected_files;
};

// The callback type for GetFileNativeLocalPathFor{Opening,Saving}. It receives
// the resolved local path when successful, and receives empty path for failure.
typedef base::OnceCallback<void(const base::FilePath&)> LocalPathCallback;

// Gets a resolved local file path of a non native |path| for file opening.
void GetFileNativeLocalPathForOpening(Profile* profile,
                                      const base::FilePath& path,
                                      LocalPathCallback callback) {
  VolumeManager::Get(profile)->snapshot_manager()->CreateManagedSnapshot(
      path, std::move(callback));
}

// Gets a resolved local file path of a non native |path| for file saving.
void GetFileNativeLocalPathForSaving(Profile* profile,
                                     const base::FilePath& path,
                                     LocalPathCallback callback) {
  // TODO(kinaba): For now, there are no writable non-local volumes.
  NOTREACHED();
  std::move(callback).Run(base::FilePath());
}

// Forward declarations of helper functions for GetSelectedFileInfo().
void ContinueGetSelectedFileInfo(
    Profile* profile,
    std::unique_ptr<GetSelectedFileInfoParams> params,
    const base::FilePath& local_file_path);

void ContinueGetSelectedFileInfoWithDriveFsMetadata(
    Profile* profile,
    std::unique_ptr<GetSelectedFileInfoParams> params,
    drive::FileError error,
    drivefs::mojom::FileMetadataPtr metadata);

// Part of GetSelectedFileInfo().
void GetSelectedFileInfoInternal(
    Profile* profile,
    std::unique_ptr<GetSelectedFileInfoParams> params) {
  DCHECK(profile);

  for (size_t i = params->selected_files.size(); i < params->file_paths.size();
       ++i) {
    const base::FilePath& file_path = params->file_paths[i];

    if (file_manager::util::IsUnderNonNativeLocalPath(profile, file_path)) {
      // When the caller of the select file dialog wants local file paths, and
      // the selected path does not point to a native local path (e.g., Drive,
      // MTP, or provided file system), we should resolve the path.
      switch (params->local_path_option) {
        case NO_LOCAL_PATH_RESOLUTION: {
          // Pass empty local path.
          params->selected_files.emplace_back(file_path, base::FilePath());

          GURL external_file_url =
              ash::CreateExternalFileURLFromPath(profile, file_path);
          if (!external_file_url.is_empty()) {
            params->selected_files.back().url.emplace(
                std::move(external_file_url));
          }
          break;
        }
        case NEED_LOCAL_PATH_FOR_OPENING: {
          GetFileNativeLocalPathForOpening(
              profile, file_path,
              base::BindOnce(&ContinueGetSelectedFileInfo, profile,
                             std::move(params)));
          return;  // Remaining work is done in ContinueGetSelectedFileInfo.
        }
        case NEED_LOCAL_PATH_FOR_SAVING: {
          GetFileNativeLocalPathForSaving(
              profile, file_path,
              base::BindOnce(&ContinueGetSelectedFileInfo, profile,
                             std::move(params)));
          return;  // Remaining work is done in ContinueGetSelectedFileInfo.
        }
      }
    } else {
      // Hosted docs can only accessed by navigating to their URLs. Get the
      // metadata for the file from DriveFS and populate the |url| field in the
      // SelectedFileInfo.
      if (drive::util::HasHostedDocumentExtension(file_path)) {
        auto* integration_service =
            drive::util::GetIntegrationServiceByProfile(profile);
        base::FilePath drive_mount_relative_path;
        if (integration_service && integration_service->GetDriveFsInterface() &&
            integration_service->GetRelativeDrivePath(
                file_path, &drive_mount_relative_path)) {
          integration_service->GetDriveFsInterface()->GetMetadata(
              drive_mount_relative_path,
              base::BindOnce(&ContinueGetSelectedFileInfoWithDriveFsMetadata,
                             profile, std::move(params)));
          return;
        }
      }
      params->selected_files.emplace_back(file_path, file_path);
    }
  }

  // Populate the virtual path for any files on a external mount point. This
  // lets consumers that are capable of using a virtual path use this rather
  // than file_path, which can make certain operations more efficient.
  for (auto& file_info : params->selected_files) {
    auto* external_mount_points =
        storage::ExternalMountPoints::GetSystemInstance();
    base::FilePath virtual_path;
    if (external_mount_points->GetVirtualPath(file_info.file_path,
                                              &virtual_path)) {
      file_info.virtual_path.emplace(std::move(virtual_path));
    } else {
      LOG(ERROR) << "Failed to get external virtual path: "
                 << file_info.file_path;
    }
  }

  std::move(params->callback).Run(params->selected_files);
}

// Part of GetSelectedFileInfo().
void ContinueGetSelectedFileInfo(
    Profile* profile,
    std::unique_ptr<GetSelectedFileInfoParams> params,
    const base::FilePath& local_path) {
  if (local_path.empty()) {
    std::move(params->callback).Run(std::vector<ui::SelectedFileInfo>());
    return;
  }
  const int index = params->selected_files.size();
  const base::FilePath& file_path = params->file_paths[index];
  params->selected_files.emplace_back(file_path, local_path);
  GetSelectedFileInfoInternal(profile, std::move(params));
}

// Part of GetSelectedFileInfo().
void ContinueGetSelectedFileInfoWithDriveFsMetadata(
    Profile* profile,
    std::unique_ptr<GetSelectedFileInfoParams> params,
    drive::FileError error,
    drivefs::mojom::FileMetadataPtr metadata) {
  const int index = params->selected_files.size();
  const auto& path = params->file_paths[index];
  params->selected_files.emplace_back(path, path);
  if (metadata && drivefs::IsHosted(metadata->type) &&
      !metadata->alternate_url.empty()) {
    params->selected_files.back().url.emplace(
        std::move(metadata->alternate_url));
  }
  GetSelectedFileInfoInternal(profile, std::move(params));
}

std::string GetShareUrlFromAlternateUrl(const GURL& alternate_url) {
  // Set |share_url| to a modified version of |alternate_url| that opens the
  // sharing dialog for files and folders (add ?userstoinvite="" to the URL).
  GURL::Replacements replacements;
  std::string new_query =
      (alternate_url.has_query() ? alternate_url.query() + "&" : "") +
      "userstoinvite=%22%22";
  replacements.SetQueryStr(new_query);

  return alternate_url.ReplaceComponents(replacements).spec();
}

extensions::api::file_manager_private::VmType VmTypeToJs(
    guest_os::VmType vm_type) {
  switch (vm_type) {
    case guest_os::VmType::TERMINA:
      return extensions::api::file_manager_private::VM_TYPE_TERMINA;
    case guest_os::VmType::PLUGIN_VM:
      return extensions::api::file_manager_private::VM_TYPE_PLUGIN_VM;
    case guest_os::VmType::BOREALIS:
      return extensions::api::file_manager_private::VM_TYPE_BOREALIS;
    case guest_os::VmType::BRUSCHETTA:
      return extensions::api::file_manager_private::VM_TYPE_BRUSCHETTA;
    case guest_os::VmType::ARCVM:
      return extensions::api::file_manager_private::VM_TYPE_ARCVM;
    case guest_os::VmType::UNKNOWN:
    case guest_os::VmType::VmType_INT_MIN_SENTINEL_DO_NOT_USE_:
    case guest_os::VmType::VmType_INT_MAX_SENTINEL_DO_NOT_USE_:
      NOTREACHED();
      return extensions::api::file_manager_private::VM_TYPE_NONE;
  }
}

}  // namespace

// Creates an instance and starts the process.
void SingleEntryPropertiesGetterForDriveFs::Start(
    const storage::FileSystemURL& file_system_url,
    Profile* const profile,
    ResultCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  SingleEntryPropertiesGetterForDriveFs* instance =
      new SingleEntryPropertiesGetterForDriveFs(file_system_url, profile,
                                                std::move(callback));
  instance->StartProcess();

  // The instance will be destroyed by itself.
}

SingleEntryPropertiesGetterForDriveFs::SingleEntryPropertiesGetterForDriveFs(
    const storage::FileSystemURL& file_system_url,
    Profile* const profile,
    ResultCallback callback)
    : callback_(std::move(callback)),
      file_system_url_(file_system_url),
      running_profile_(profile),
      properties_(std::make_unique<
                  extensions::api::file_manager_private::EntryProperties>()) {
  DCHECK(callback_);
  DCHECK(profile);
}

SingleEntryPropertiesGetterForDriveFs::
    ~SingleEntryPropertiesGetterForDriveFs() = default;

void SingleEntryPropertiesGetterForDriveFs::StartProcess() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  drive::DriveIntegrationService* integration_service =
      drive::DriveIntegrationServiceFactory::FindForProfile(running_profile_);
  if (!integration_service || !integration_service->IsMounted()) {
    CompleteGetEntryProperties(drive::FILE_ERROR_SERVICE_UNAVAILABLE);
    return;
  }
  base::FilePath path;
  if (!integration_service->GetRelativeDrivePath(file_system_url_.path(),
                                                 &path)) {
    CompleteGetEntryProperties(drive::FILE_ERROR_INVALID_OPERATION);
    return;
  }

  auto* drivefs_interface = integration_service->GetDriveFsInterface();
  if (!drivefs_interface) {
    CompleteGetEntryProperties(drive::FILE_ERROR_SERVICE_UNAVAILABLE);
    return;
  }

  drivefs_interface->GetMetadata(
      path,
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(
          base::BindOnce(&SingleEntryPropertiesGetterForDriveFs::OnGetFileInfo,
                         weak_ptr_factory_.GetWeakPtr()),
          drive::FILE_ERROR_SERVICE_UNAVAILABLE, nullptr));
}

void SingleEntryPropertiesGetterForDriveFs::OnGetFileInfo(
    drive::FileError error,
    drivefs::mojom::FileMetadataPtr metadata) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!metadata) {
    CompleteGetEntryProperties(error);
    return;
  }

  if (base::FeatureList::IsEnabled(ash::features::kFilesInlineSyncStatus)) {
    drive::DriveIntegrationService* integration_service =
        drive::DriveIntegrationServiceFactory::FindForProfile(running_profile_);
    auto sync_status = (!integration_service)
                           ? drivefs::SyncStatus::kNotFound
                           : integration_service->GetSyncStatusForPath(
                                 file_system_url_.path());
    switch (sync_status) {
      case drivefs::SyncStatus::kInProgress:
        properties_->sync_status =
            file_manager_private::SYNC_STATUS_IN_PROGRESS;
        break;
      case drivefs::SyncStatus::kError:
        properties_->sync_status = file_manager_private::SYNC_STATUS_ERROR;
        break;
      default:
        properties_->sync_status = file_manager_private::SYNC_STATUS_NOT_FOUND;
        break;
    }
  } else {
    properties_->sync_status = file_manager_private::SYNC_STATUS_NOT_FOUND;
  }

  properties_->size = metadata->size;
  properties_->present = metadata->available_offline;
  properties_->dirty = metadata->dirty;
  properties_->hosted = drivefs::IsHosted(metadata->type);
  properties_->available_offline =
      metadata->available_offline || *properties_->hosted;
  properties_->available_when_metered =
      metadata->available_offline || *properties_->hosted;
  properties_->pinned = metadata->pinned;
  properties_->shared = metadata->shared;
  properties_->starred = metadata->starred;

  if (metadata->modification_time != base::Time()) {
    properties_->modification_time = metadata->modification_time.ToJsTime();
  }
  if (metadata->last_viewed_by_me_time != base::Time()) {
    properties_->modification_by_me_time =
        metadata->last_viewed_by_me_time.ToJsTime();
  }
  if (!metadata->content_mime_type.empty()) {
    properties_->content_mime_type = metadata->content_mime_type;
  }
  if (!metadata->custom_icon_url.empty()) {
    properties_->custom_icon_url = std::move(metadata->custom_icon_url);
  }
  if (!metadata->alternate_url.empty()) {
    properties_->alternate_url = std::move(metadata->alternate_url);
    properties_->share_url =
        GetShareUrlFromAlternateUrl(GURL(*properties_->alternate_url));
  }
  if (metadata->image_metadata) {
    properties_->image_height = metadata->image_metadata->height;
    properties_->image_width = metadata->image_metadata->width;
    properties_->image_rotation = metadata->image_metadata->rotation;
  }

  properties_->can_delete = metadata->capabilities->can_delete;
  properties_->can_rename = metadata->capabilities->can_rename;
  properties_->can_add_children = metadata->capabilities->can_add_children;

  // Only set the |can_copy| capability for hosted documents; for other files,
  // we must have read access, so |can_copy| is implicitly true.
  properties_->can_copy =
      !*properties_->hosted || metadata->capabilities->can_copy;
  properties_->can_share = metadata->capabilities->can_share;

  properties_->can_pin =
      metadata->can_pin == drivefs::mojom::FileMetadata::CanPinStatus::kOk;

  if (drivefs::IsAFile(metadata->type)) {
    properties_->thumbnail_url =
        base::StrCat({"drivefs:", file_system_url_.ToGURL().spec()});
    properties_->cropped_thumbnail_url = *properties_->thumbnail_url;
  }

  if (metadata->folder_feature) {
    properties_->is_machine_root = metadata->folder_feature->is_machine_root;
    properties_->is_external_media =
        metadata->folder_feature->is_external_media;
    properties_->is_arbitrary_sync_folder =
        metadata->folder_feature->is_arbitrary_sync_folder;
  }

  CompleteGetEntryProperties(drive::FILE_ERROR_OK);
}

void SingleEntryPropertiesGetterForDriveFs::CompleteGetEntryProperties(
    drive::FileError error) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(callback_);

  std::move(callback_).Run(std::move(properties_),
                           drive::FileErrorToBaseFileError(error));
  content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this);
}

void FillIconSet(file_manager_private::IconSet* output,
                 const ash::file_system_provider::IconSet& input) {
  DCHECK(output);
  using ash::file_system_provider::IconSet;
  if (input.HasIcon(IconSet::IconSize::SIZE_16x16)) {
    output->icon16x16_url = input.GetIcon(IconSet::IconSize::SIZE_16x16).spec();
  }
  if (input.HasIcon(IconSet::IconSize::SIZE_32x32)) {
    output->icon32x32_url = input.GetIcon(IconSet::IconSize::SIZE_32x32).spec();
  }
}

void VolumeToVolumeMetadata(
    Profile* profile,
    const Volume& volume,
    file_manager_private::VolumeMetadata* volume_metadata) {
  DCHECK(volume_metadata);

  volume_metadata->volume_id = volume.volume_id();

  // TODO(kinaba): fill appropriate information once multi-profile support is
  // implemented.
  volume_metadata->profile.display_name = profile->GetProfileUserName();
  volume_metadata->profile.is_current_profile = true;

  if (!volume.source_path().empty()) {
    volume_metadata->source_path = volume.source_path().AsUTF8Unsafe();
  }
  if (!volume.remote_mount_path().empty()) {
    volume_metadata->remote_mount_path = volume.remote_mount_path().value();
  }

  switch (volume.source()) {
    case SOURCE_FILE:
      volume_metadata->source = file_manager_private::SOURCE_FILE;
      break;
    case SOURCE_DEVICE:
      volume_metadata->source = file_manager_private::SOURCE_DEVICE;
      volume_metadata->is_read_only_removable_device =
          volume.is_read_only_removable_device();
      break;
    case SOURCE_NETWORK:
      volume_metadata->source =
          extensions::api::file_manager_private::SOURCE_NETWORK;
      break;
    case SOURCE_SYSTEM:
      volume_metadata->source =
          extensions::api::file_manager_private::SOURCE_SYSTEM;
      break;
  }

  volume_metadata->configurable = volume.configurable();
  volume_metadata->watchable = volume.watchable();

  if (volume.type() == VOLUME_TYPE_PROVIDED) {
    volume_metadata->provider_id = volume.provider_id().ToString();
    volume_metadata->file_system_id = volume.file_system_id();
  }

  FillIconSet(&volume_metadata->icon_set, volume.icon_set());

  volume_metadata->volume_label = volume.volume_label();
  volume_metadata->disk_file_system_type = volume.file_system_type();
  volume_metadata->drive_label = volume.drive_label();

  switch (volume.type()) {
    case VOLUME_TYPE_GOOGLE_DRIVE:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_DRIVE;
      break;
    case VOLUME_TYPE_DOWNLOADS_DIRECTORY:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_DOWNLOADS;
      break;
    case VOLUME_TYPE_REMOVABLE_DISK_PARTITION:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_REMOVABLE;
      break;
    case VOLUME_TYPE_MOUNTED_ARCHIVE_FILE:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_ARCHIVE;
      break;
    case VOLUME_TYPE_PROVIDED:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_PROVIDED;
      break;
    case VOLUME_TYPE_MTP:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_MTP;
      break;
    case VOLUME_TYPE_MEDIA_VIEW:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_MEDIA_VIEW;
      break;
    case VOLUME_TYPE_CROSTINI:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_CROSTINI;
      break;
    case VOLUME_TYPE_ANDROID_FILES:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_ANDROID_FILES;
      break;
    case VOLUME_TYPE_DOCUMENTS_PROVIDER:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_DOCUMENTS_PROVIDER;
      break;
    case VOLUME_TYPE_TESTING:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_TESTING;
      break;
    case VOLUME_TYPE_SMB:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_SMB;
      break;
    case VOLUME_TYPE_SYSTEM_INTERNAL:
      volume_metadata->volume_type =
          file_manager_private::VOLUME_TYPE_SYSTEM_INTERNAL;
      break;
    case VOLUME_TYPE_GUEST_OS:
      volume_metadata->volume_type = file_manager_private::VOLUME_TYPE_GUEST_OS;
      break;
    case NUM_VOLUME_TYPE:
      NOTREACHED();
      break;
  }

  // Fill device_type iff the volume is removable partition.
  if (volume.type() == VOLUME_TYPE_REMOVABLE_DISK_PARTITION) {
    switch (volume.device_type()) {
      case ash::DeviceType::kUnknown:
        volume_metadata->device_type =
            file_manager_private::DEVICE_TYPE_UNKNOWN;
        break;
      case ash::DeviceType::kUSB:
        volume_metadata->device_type = file_manager_private::DEVICE_TYPE_USB;
        break;
      case ash::DeviceType::kSD:
        volume_metadata->device_type = file_manager_private::DEVICE_TYPE_SD;
        break;
      case ash::DeviceType::kOpticalDisc:
      case ash::DeviceType::kDVD:
        volume_metadata->device_type =
            file_manager_private::DEVICE_TYPE_OPTICAL;
        break;
      case ash::DeviceType::kMobile:
        volume_metadata->device_type = file_manager_private::DEVICE_TYPE_MOBILE;
        break;
    }
    volume_metadata->device_path = volume.storage_device_path().AsUTF8Unsafe();
    volume_metadata->is_parent_device = volume.is_parent();
  } else {
    volume_metadata->device_type = file_manager_private::DEVICE_TYPE_NONE;
  }

  volume_metadata->is_read_only = volume.is_read_only();
  volume_metadata->has_media = volume.has_media();
  volume_metadata->hidden = volume.hidden();

  switch (volume.mount_condition()) {
    default:
      LOG(ERROR) << "Unexpected mount condition: " << volume.mount_condition();
      [[fallthrough]];
    case ash::MountError::kSuccess:
      volume_metadata->mount_condition = file_manager_private::MOUNT_ERROR_NONE;
      break;
    case ash::MountError::kUnknownFilesystem:
      volume_metadata->mount_condition =
          file_manager_private::MOUNT_ERROR_UNKNOWN_FILESYSTEM;
      break;
    case ash::MountError::kUnsupportedFilesystem:
      volume_metadata->mount_condition =
          file_manager_private::MOUNT_ERROR_UNSUPPORTED_FILESYSTEM;
      break;
  }

  // If the context is known, then pass it.
  switch (volume.mount_context()) {
    case MOUNT_CONTEXT_USER:
      volume_metadata->mount_context = file_manager_private::MOUNT_CONTEXT_USER;
      break;
    case MOUNT_CONTEXT_AUTO:
      volume_metadata->mount_context = file_manager_private::MOUNT_CONTEXT_AUTO;
      break;
    case MOUNT_CONTEXT_UNKNOWN:
      break;
  }

  if (volume.vm_type()) {
    volume_metadata->vm_type = VmTypeToJs(*volume.vm_type());
  }
}

base::FilePath GetLocalPathFromURL(content::RenderFrameHost* render_frame_host,
                                   Profile* profile,
                                   const GURL& url) {
  DCHECK(render_frame_host);
  DCHECK(profile);

  scoped_refptr<storage::FileSystemContext> file_system_context =
      util::GetFileSystemContextForRenderFrameHost(profile, render_frame_host);

  const storage::FileSystemURL filesystem_url(
      file_system_context->CrackURLInFirstPartyContext(url));
  base::FilePath path;
  if (!ash::FileSystemBackend::CanHandleURL(filesystem_url))
    return base::FilePath();
  return filesystem_url.path();
}

void GetSelectedFileInfo(content::RenderFrameHost* render_frame_host,
                         Profile* profile,
                         const std::vector<GURL>& file_urls,
                         GetSelectedFileInfoLocalPathOption local_path_option,
                         GetSelectedFileInfoCallback callback) {
  DCHECK(render_frame_host);
  DCHECK(profile);

  std::unique_ptr<GetSelectedFileInfoParams> params(
      new GetSelectedFileInfoParams);
  params->local_path_option = local_path_option;
  params->callback = std::move(callback);

  for (const GURL& url : file_urls) {
    base::FilePath path = GetLocalPathFromURL(render_frame_host, profile, url);
    if (!path.empty()) {
      DVLOG(1) << "Selected: file path: " << path;
      params->file_paths.push_back(std::move(path));
    }
  }

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&GetSelectedFileInfoInternal, profile, std::move(params)));
}

drive::EventLogger* GetLogger(Profile* profile) {
  if (!profile)
    return nullptr;
  drive::DriveIntegrationService* service =
      drive::DriveIntegrationServiceFactory::FindForProfile(profile);
  return service ? service->event_logger() : nullptr;
}

std::vector<extensions::api::file_manager_private::MountableGuest>
CreateMountableGuestList(Profile* profile) {
  auto* registry =
      guest_os::GuestOsService::GetForProfile(profile)->MountProviderRegistry();
  std::vector<file_manager_private::MountableGuest> guests;
  for (const auto id : registry->List()) {
    file_manager_private::MountableGuest guest;
    auto* provider = registry->Get(id);
    guest.id = id;
    guest.display_name = provider->DisplayName();
    guest.vm_type = VmTypeToJs(provider->vm_type());
    guests.push_back(std::move(guest));
  }
  return guests;
}

}  // namespace util
}  // namespace file_manager


text:
/**
 * Configuration and specification of workers in CDAP.
 */
package co.cask.cdap.api.worker;


text:
/*
 * DEBUG: section 16    Cache Manager API
 *
 */

#include "squid.h"
#include "base/TextException.h"
#include "IoStats.h"
#include "ipc/Messages.h"
#include "ipc/TypedMsgHdr.h"
#include "mgr/IoAction.h"
#include "SquidMath.h"
#include "Store.h"
#include "tools.h"

void GetIoStats(Mgr::IoActionData& stats);
void DumpIoStats(Mgr::IoActionData& stats, StoreEntry* sentry);

Mgr::IoActionData::IoActionData()
{
    memset(this, 0, sizeof(*this));
}

Mgr::IoActionData&
Mgr::IoActionData::operator += (const IoActionData& stats)
{
    http_reads += stats.http_reads;
    for (int i = 0; i < IoStats::histSize; ++i)
        http_read_hist[i] += stats.http_read_hist[i];
    ftp_reads += stats.ftp_reads;
    for (int i = 0; i < IoStats::histSize; ++i)
        ftp_read_hist[i] += stats.ftp_read_hist[i];
    gopher_reads += stats.gopher_reads;
    for (int i = 0; i < IoStats::histSize; ++i)
        gopher_read_hist[i] += stats.gopher_read_hist[i];

    return *this;
}

Mgr::IoAction::Pointer
Mgr::IoAction::Create(const CommandPointer &cmd)
{
    return new IoAction(cmd);
}

Mgr::IoAction::IoAction(const CommandPointer &cmd):
        Action(cmd), data()
{
    debugs(16, 5, HERE);
}

void
Mgr::IoAction::add(const Action& action)
{
    debugs(16, 5, HERE);
    data += dynamic_cast<const IoAction&>(action).data;
}

void
Mgr::IoAction::collect()
{
    GetIoStats(data);
}

void
Mgr::IoAction::dump(StoreEntry* entry)
{
    debugs(16, 5, HERE);
    Must(entry != NULL);
    DumpIoStats(data, entry);
}

void
Mgr::IoAction::pack(Ipc::TypedMsgHdr& msg) const
{
    msg.setType(Ipc::mtCacheMgrResponse);
    msg.putPod(data);
}

void
Mgr::IoAction::unpack(const Ipc::TypedMsgHdr& msg)
{
    msg.checkType(Ipc::mtCacheMgrResponse);
    msg.getPod(data);
}