GVKun编程网logo

com.facebook.FacebookAuthorizationException的实例源码(facebook源代码)

29

对于想了解com.facebook.FacebookAuthorizationException的实例源码的读者,本文将是一篇不可错过的文章,我们将详细介绍facebook源代码,并且为您提供关于an

对于想了解com.facebook.FacebookAuthorizationException的实例源码的读者,本文将是一篇不可错过的文章,我们将详细介绍facebook源代码,并且为您提供关于android – com.facebook.FacebookException:尝试使用未打开的Session、com.facebook.android.AsyncFacebookRunner的实例源码、com.facebook.buck.rules.Description的实例源码、com.facebook.buck.step.ExecutionContext的实例源码的有价值信息。

本文目录一览:

com.facebook.FacebookAuthorizationException的实例源码(facebook源代码)

com.facebook.FacebookAuthorizationException的实例源码(facebook源代码)

项目:android-oss    文件:LoginToutviewmodel.java   
private void registerFacebookCallback() {
  final PublishSubject<String> fbAccesstoken = this.facebookAccesstoken;
  final BehaviorSubject<FacebookException> fbAuthError = this.facebookAuthorizationError;

  this.callbackManager = CallbackManager.Factory.create();

  LoginManager.getInstance().registerCallback(this.callbackManager,new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(final @NonNull LoginResult result) {
      fbAccesstoken.onNext(result.getAccesstoken().getToken());
    }

    @Override
    public void onCancel() {
      // continue
    }

    @Override
    public void onError(final @NonNull FacebookException error) {
      if (error instanceof FacebookAuthorizationException) {
        fbAuthError.onNext(error);
      }
    }
  });
}
项目:ReactiveFB    文件:RequestAction.java   
protected void execute() {
    if (sessionManager.isLoggedIn()) {
        Accesstoken accesstoken = sessionManager.getAccesstoken();
        Bundle bundle = updateAppSecretProof();
        GraphRequest request = new GraphRequest(accesstoken,getGraPHPath(),bundle,HttpMethod.GET);
        request.setVersion(configuration.getGraphVersion());
        runRequest(request);
    } else {
        String reason = Errors.getError(Errors.ErrorMsg.LOGIN);
        Logger.logError(getClass(),reason,null);
        if (mSingleEmitter != null) {
            mSingleEmitter.onError(new FacebookAuthorizationException(reason));
        }
    }
}
项目:AndroidUtility    文件:FBLogin.java   
public void fbLogin(final FBLoginInterface fbLoginInterface,final Activity activity) {
    List<String> permissionNeeds = Arrays.asList("email");
    LoginManager.getInstance().logInWithReadPermissions(activity,permissionNeeds);
    LoginManager.getInstance().registerCallback(callbackManager,new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccesstoken(),new GraphRequest.GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object,GraphResponse response) {
                            Bundle facebookBundle = getFacebookData(object);
                            fbLoginInterface.doTaskAfterLogin(facebookBundle);
                        }
                    });

                    Bundle parameters = new Bundle();
                    parameters.putString("fields","id,first_name,last_name,email,gender,birthday,location"); // Parámetros que pedimos a facebook
                    request.setParameters(parameters);
                    request.executeAsync();
                }

                @Override
                public void onCancel() {

                }

                @Override
                public void onError(FacebookException error) {
                    if (error instanceof FacebookAuthorizationException) {
                        if (Accesstoken.getCurrentAccesstoken() != null) {
                            LoginManager.getInstance().logout();
                            fbLogin(fbLoginInterface,activity);
                        }
                    }
                }
            });
}
项目:QuizUpWinner    文件:Facebook.java   
private void onSessionCallback(Session paramSession,SessionState paramSessionState,Exception paramException,DialogListener paramDialogListener)
{
  Bundle localBundle = paramSession.getAuthorizationBundle();
  if (paramSessionState == SessionState.OPENED)
  {
    Session localSession2;
    synchronized (this.lock)
    {
      Session localSession1 = this.session;
      localSession2 = null;
      if (paramSession != localSession1)
      {
        localSession2 = this.session;
        this.session = paramSession;
        this.sessionInvalidated = false;
      }
    }
    if (localSession2 != null)
      localSession2.close();
    paramDialogListener.onComplete(localBundle);
    return;
  }
  if (paramException != null)
  {
    if ((paramException instanceof FacebookOperationCanceledException))
    {
      paramDialogListener.onCancel();
      return;
    }
    if (((paramException instanceof FacebookAuthorizationException)) && (localBundle != null) && (localBundle.containsKey("com.facebook.sdk.WebViewErrorCode")) && (localBundle.containsKey("com.facebook.sdk.FailingUrl")))
    {
      paramDialogListener.onError(new DialogError(paramException.getMessage(),localBundle.getInt("com.facebook.sdk.WebViewErrorCode"),localBundle.getString("com.facebook.sdk.FailingUrl")));
      return;
    }
    paramDialogListener.onFacebookError(new FacebookError(paramException.getMessage()));
  }
}

android – com.facebook.FacebookException:尝试使用未打开的Session

android – com.facebook.FacebookException:尝试使用未打开的Session

我整合了facebook分享,它在过去几天工作得很好,但是今天在问这个问题之前的2个小时我正面临着这个问题.

我正在使用此代码登录:

  Session.openActiveSession(this, true, new Session.StatusCallback() {

// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
  if (state.isOpened()) {

    // make request to the /me API
    Request.newMeRequest(session, new Request.GraphUserCallback() {

      // callback after Graph API response with user object
      @Override
      public void onCompleted(GraphUser user, Response response) {
        if (user != null) {

          Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
        }
      }
    }).executeAsync();
  }
}
});
publishFeedDialog();

问题是if()条件总是假的,我也使用session.isOpened()也返回false,我很困惑为什么会发生这种情况.

我已经在清单中声明了INTERNET,ACCESSNETWORKSTATE,权限

 <application>
 ..........
 ..........
 <Meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
 </application>

请帮忙…

编辑

这是我实现的代码,你可以看到onCreateOptionsMenu,onoptionsItemSelected,onActivityResult,publishFeedDialog

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_bar_share_menu, menu);
        MenuItem item = menu.findItem(R.id.menu_item_share1);


        return true;
    }
@Override

public boolean      onoptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_share1: // facebook item selected
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
//start Facebook Login


Session.openActiveSession(this, true, new Session.StatusCallback() {

// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
  if (state.isOpened()) {

    // make request to the /me API
    Request.newMeRequest(session, new Request.GraphUserCallback() {

      // callback after Graph API response with user object
      @Override
      public void onCompleted(GraphUser user, Response response) {
        if (user != null) {

          Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
        }
      }
    }).executeAsync();
  }
}
});
publishFeedDialog();

}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
        @Override
        public void one rror(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.e("Activity", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.i("Activity", "Success!");
        }
    });

}
@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(STATE_POSITION, pager.getCurrentItem());
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}

@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
}

private void publishFeedDialog() {

    Log.v("pos",""+pos);
    Bundle params = new Bundle();
    params.putString("name", ItemListApplication.names.get(pos).getItem());
    params.putString("caption", "Irrational beliefs");
    params.putString("description",ItemListApplication.names.get(pos).getDesc() );
    params.putString("link", "https://www.facebook.com/vivek.warde.3?ref=tn_tnmn");

    if(pos==0) params.putString("picture","http://i.imgur.com/lOIUcW2.jpg");
    else params.putString("picture",imageUrls[pos]);
    WebDialog FeedDialog = (
        new WebDialog.FeedDialogBuilder(this,
            Session.getActiveSession(),
            params))
        .setonCompleteListener(new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values,
                FacebookException error) {
                if (error == null) {
                    // When the story is posted, echo the success
                    // and the post Id.
                    final String postId = values.getString("post_id");
                    if (postId != null) {
                        Toast.makeText(ImagePagerActivity.this,
                            "Posted story, id: "+postId,
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(ImagePagerActivity.this, 
                            "Publish cancelled", 
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(ImagePagerActivity.this, 
                        "Publish cancelled", 
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(ImagePagerActivity.this, 
                        "Error posting story", 
                        Toast.LENGTH_SHORT).show();
                }
            }

        })
        .build();
    FeedDialog.show();
}

解决方法:

处理这个问题可能有很多原因.你应该检查一下:

我正在使用此代码通过Facebook登录:

class MyFragment extends Fragment {
   //... some code

   SessionStatusCallback statusCallback = new SessionStatusCallback();

   public void login() {
       Session session = Session.getActiveSession();
       if (!session.isOpened() && !session.isClosed()) {
           session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
       } else {
           Session.openActiveSession(getActivity(), this, true, statusCallback);
       }
   }

   private class SessionStatusCallback implements Session.StatusCallback {
       @Override
       public void call(Session session, SessionState state, Exception exception) {
           if (exception != null) {
               handleException(exception);
           }
           if (state.isOpened()) {
               afterLogin();
           } else if (state.isClosed()) {
               afterlogout();
           }
        }
    }

}

如果未打开会话,则应将其打开以供阅读(如果需要,则打开publish).

检查AndroidManifest文件中的元数据标记,是否有正确的应用程序ID?

经常发生错误不在Android应用程序内,但在Facebook应用程序设置.在facebook应用程序的设置页面中应该是正确的软件包名称,您应该为您的应用程序添加密钥哈希值(每种版本类型都不同,在大多数情况下是调试和发布).

要获取哈希键,您可以运行脚本

keytool -exportcert -alias YOUR_ALIAS -keystore PATH_TO_KEYSTORE_FILE | openssl sha1 -binary | openssl base64

或者你可以在代码中获取它:

PackageInfo info;
try {
    info = getPackageManager().getPackageInfo("YOUR_APP_PACKAGE", PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String keyhash = new String(Base64.encode(md.digest(), 0));
        //string something is what you should paste as key hash
        Log.e("hash key", keyhash);
    }
} catch (NameNotFoundException e1) {
    Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
    Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
    Log.e("exception", e.toString());
} 

在Facebook应用程序的设置页面中状态&审核标签,您应该公开app.或者,如果您仍然不想将其公开,则应为可以使用您的Android应用程序的所有用户添加角色(在“角色”选项卡中).

此外,如果它没有帮助,尝试调试方法
public void call(会话会话,SessionState状态,异常异常)
通常有正常的消息,为什么授权不成功

com.facebook.android.AsyncFacebookRunner的实例源码

com.facebook.android.AsyncFacebookRunner的实例源码

项目:facebook-android-sdk    文件:Tests.java   
public void onComplete(Bundle values) {
    final String postId = values.getString("post_id");
    if (postId != null) {
        Log.d("Facebook-Example","Dialog Success! post_id=" + postId);
        new AsyncFacebookRunner(authenticatedFacebook).request(postId,new TestPostRequestListener());
    } else {
        Tests.this.runOnUiThread(new Runnable() {
            public void run() {
                wallPostText.setText("Wall Post Failure");
                wallPostText.setTextColor(Color.RED);
            }
        });
    }
}
项目:Socialite    文件:FacebookConnector.java   
@Override
public void logout() {
    SessionEvents.onlogoutBegin(SessionListenerType.FACEBOOK_SESSION_LISTENER);
    AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
    asyncRunner.logout(activity.getApplicationContext(),new logoutRequestListener());
}
项目:kaorisan    文件:LoginActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginActivity = this;
    sqliteDatabaseAdapter.setContext(this);

    checkGooglePlayServices();

    mPlusClient = new PlusClient.Builder(this,this,this)
    .setVisibleActivities("http://schemas.google.com/AddActivity","http://schemas.google.com/BuyActivity").setScopes(Scopes.PLUS_LOGIN,Scopes.PLUS_PROFILE).build();

    btnLoginGoogle = (Button) findViewById(R.id.btn_login_google);
    initGoogleButton();

    genKeyHash();
    resource = getResources();

    DebugLog.logd("On create");

    // Create the Facebook Object using the app id.
    if (Utility.mFacebook == null) {
        Utility.mFacebook = new Facebook(APP_ID);
    }
    // Instantiate the asynrunner object for asynchronous api calls.
    if (Utility.mAsyncRunner == null) {
        Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);
    }

    SessionStore.restore(Utility.mFacebook,this);

    SessionEvents.addAuthListener(authenListener);
    SessionEvents.addlogoutListener(logoutListener);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    btnLoginFaceBook = (Button) findViewById(R.id.btn_login_facebook);
    initFacebookButton();

    SessionEvents.addAuthListener(mSessionListener);
    SessionEvents.addlogoutListener(mSessionListener);

    if (Utility.mFacebook.isSessionValid() && islogout == 0 && currentSocial == Social.FACEBOOK) {
        DebugLog.logd("On facebook Create");
        if (Utils.checkInternetConnect(this)) {
            requestGetUserData();
        }
    }

    if (currentSocial == Social.GOOGLE && islogout == 0) {
        DebugLog.logd("On Google Create");
        mPlusClient.connect();
    }
    checklogout();

}
项目:kaorisan    文件:LoginActivity.java   
private void checklogout() {

        if (islogout == 1 && NetworkUtil.NETWORK_STATE != NetworkUtil.TYPE_NOT_CONNECTED) {
            if (currentSocial == Social.FACEBOOK) {
                if (Utility.mFacebook.isSessionValid()) {
                    SessionEvents.onlogoutBegin();
                    AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

                    try {
                        if (showProcess != null) {
                            if (showProcess.isShowing()) {
                                showProcess.dismiss();
                            }
                            showProcess = null;
                        }

                        showProcess = new ProgressDialog(this);
                        showProcess.setCancelable(false);
                        showProcess.setTitle(getResources().getString(R.string.txt_logout));

                        showProcess.show();
                    } catch (Exception ex) {
                        DebugLog.logd("checklogout ??? Do not kNow what happen with show process," +
                                "maybe the facebook already hace show process");
                    }
                    asyncRunner.logout(this,new logoutRequestListener());
                }

                if(TaskActivity.taskActivity != null){
                    TaskActivity.taskActivity.finish();
                }
            } else if (currentSocial == Social.GOOGLE) {
                DebugLog.logd("On google logout");
                mPlusClient.disconnect();

            }

            if(CacheData.getInstant().getTokenKaorisan() != null){
                if(!CacheData.getInstant().getTokenKaorisan().isEmpty()){
                    DebugLog.logd("Delete token kaorisan in sqlite");
//                  UserDao.deleteUser(CacheData.getInstant().getTokenKaorisan());
                    UserDao.setCurrentUser("","0","","");
                }
            }
        }

        if(CacheData.getInstant().getCurrentUser() != null){
            if(CacheData.getInstant().getCurrentUser().getPushToken() != null && islogout == 1){
                if (GCMRegistrar.isRegisteredOnServer(TaskActivity.taskActivity)) {
                    ServerUtilities.unregister(TaskActivity.taskActivity,CacheData.getInstant().getCurrentUser().getPushToken());
                    Log.i(TAG,"Unregister server");
                } else {
                    // This callback results from the call to unregister made on
                    // ServerUtilities when the registration to the server Failed.
                    Log.i(TAG,"Ignoring unregister callback");
                }
            }
        }

        Utils.resetCacheData();
        islogout = 0;
    }
项目:IPRJapp    文件:Tutorial_1.java   
@SuppressWarnings("deprecation")
@Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);        

        if (savedInstanceState != null)

            TutoRes = savedInstanceState.getInt("TutoRes");
        facebook = new Facebook(APP_ID);
        AsyncFacebookRunner   mAsyncRunner = new AsyncFacebookRunner(facebook);
        //loginFacebook();

requestwindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tutorial_1);
//setLogin();



Session.openActiveSession(this,true,new Session.StatusCallback() {


    @Override
    public void call(final Session session,SessionState state,Exception exception) {
        if (session.isOpened()) {

            Request.newMeRequest(session,new Request.GraphUserCallback() {

                  @Override
                  public void onCompleted(GraphUser user,Response response) {

                      if (user != null) {

                        //welcome = (TextView) findViewById(R.id.welcome);                      
                        Userid = user.getId();
                        User_name= user.getFirstName();


                        }
                  }
                }).executeAsync();
            }
    }
  }); 



final Button  Button = (Button) findViewById(R.id.button1);

Button.setonClickListener(new View.OnClickListener() {

       @Override
      public void onClick(View v) {

        if(Userid != null && User_name != null){

             Intent intent = new Intent();
             intent.setClass(Tutorial_1.this,Tutorial_2.class);
             db.addUsuario(new Usuario(User_name,Userid));
            startActivity(intent);
             finish();


        }

        else {

            Toast.makeText(getApplicationContext(),"Aguarde o carregamento dos dados do perfil do Facebook",Toast.LENGTH_SHORT).show();

        }

       }

});
   }

com.facebook.buck.rules.Description的实例源码

com.facebook.buck.rules.Description的实例源码

项目:buck-cutom    文件:Parser.java   
/**
 * @param rules the raw rule objects to parse.
 */
@VisibleForTesting
synchronized void parseRawRulesInternal(Iterable<Map<String,Object>> rules)
    throws BuildTargetException,IOException {
  for (Map<String,Object> map : rules) {

    if (isMetaRule(map)) {
      parseMetaRule(map);
      continue;
    }

    BuildTarget target = parseBuildTargetFromrawRule(map);
    buildruleType buildruleType = parsebuildruleTypeFromrawRule(map);
    Description<?> description = repository.getDescription(buildruleType);
    if (description == null) {
      throw new HumanReadableException("Unrecognized rule %s while parsing %s.",buildruleType,repository.getAbsolutePathToBuildFile(target));
    }

    state.put(target,map);
  }
}
项目:buck-cutom    文件:ProjectBuildFileParser.java   
protected ProjectBuildFileParser(
    ProjectFilesystem projectFilesystem,Iterable<String> commonIncludes,String pythoninterpreter,ImmutableSet<Description<?>> descriptions,Console console,ImmutableMap<String,String> environment) {
  this.projectRoot = projectFilesystem.getRootPath();
  this.descriptions = Preconditions.checkNotNull(descriptions);
  this.ignorePaths = projectFilesystem.getIgnorePaths();
  this.commonIncludes = ImmutableList.copyOf(commonIncludes);
  this.pythoninterpreter = Preconditions.checkNotNull(pythoninterpreter);
  this.pathToBuckPy = Optional.absent();
  this.console = Preconditions.checkNotNull(console);
  this.environment = Preconditions.checkNotNull(environment);

  // Default to server mode unless explicitly unset internally.
  setServerMode(true);
}
项目:buck-cutom    文件:MissingSymbolsHandler.java   
public static MissingSymbolsHandler create(
    ProjectFilesystem projectFilesystem,BuckConfig config,BuckEventBus buckEventBus,String> environment) {
  SrcRootsFinder srcRootsFinder = new SrcRootsFinder(projectFilesystem);
  ProjectBuildFileParserFactory projectBuildFileParserFactory =
      new DefaultProjectBuildFileParserFactory(
          projectFilesystem,config.getpythoninterpreter(),descriptions);
  JavaSymbolFinder javaSymbolFinder = new JavaSymbolFinder(
      projectFilesystem,srcRootsFinder,projectBuildFileParserFactory,config,buckEventBus,console,environment);
  return new MissingSymbolsHandler(
      console,javaSymbolFinder);
}
项目:buck-cutom    文件:GenruleDescriptionTest.java   
@Test
public void testImplicitDepsAreAddedCorrectly() throws NoSuchBuildTargetException {
  Description<GenruleDescription.Arg> genruleDescription = new GenruleDescription();
  Map<String,?> instance = ImmutableMap.of(
      "srcs",ImmutableList.of(":baz","//biz:baz"),"out","AndroidManifest.xml","cmd","$(exe //bin:executable) $(location :arg)");
  ProjectFilesystem projectFilesystem = new AllExistingProjectFilesystem();
  buildruleFactoryParams params = new buildruleFactoryParams(
      instance,projectFilesystem,new BuildTargetParser(projectFilesystem),BuildTargetFactory.newInstance("//foo:bar"),new FakeRuleKeyBuilderFactory());
  TargetNode<GenruleDescription.Arg> targetNode = new TargetNode<>(genruleDescription,params);
  assertEquals(
      "SourcePaths and targets from cmd string should be extracted as extra deps.",ImmutableSet.of(
          "//foo:baz","//biz:baz","//bin:executable","//foo:arg"),FluentIterable.from(targetNode.getExTradeps())
          .transform(Functions.toStringFunction())
          .toSet());
}
项目:buck-cutom    文件:AuditOwnerCommandTest.java   
private static TargetNode<?> createTargetNode(
    BuildTarget buildTarget,ImmutableSet<Path> inputs) {
  Description<FakeDescription.FakeArg> description = new FakeDescription();
  buildruleFactoryParams params =
      NonCheckingbuildruleFactoryParams.createNonCheckingbuildruleFactoryParams(
          Maps.<String,Object>newHashMap(),new BuildTargetParser(new FakeProjectFilesystem()),buildTarget);
  return new TargetNode<>(
      description,params,inputs,ImmutableSet.<BuildTarget>of(),ImmutableSet.<BuildTargetPattern>of());
}
项目:buck    文件:JavaDepsFinder.java   
public DependencyInfo findDependencyInfoForgraph(final TargetGraph graph) {
  final DependencyInfo dependencyInfo = new DependencyInfo();

  // Walk the graph and for each Java rule we record the Java entities it provides.
  //
  // Currently,we traverse the entire target graph using a single thread. However,the work to
  // visit each node Could be done in parallel,so long as the updates to the above collections
  // were thread-safe.
  for (TargetNode<?,?> node : graph.getNodes()) {
    if (!RULES_TO_VISIT.contains(Description.getbuildruleType(node.getDescription()))) {
      continue;
    }

    if (!(node.getConstructorArg() instanceof JavaLibraryDescription.CoreArg)
        && !(node.getConstructorArg() instanceof PrebuiltJarDescriptionArg)) {
      throw new IllegalStateException("This rule is not supported by suggest: " + node);
    }

    Symbols symbols = getJavaFileFeatures(node);
    for (String providedEntity : symbols.provided) {
      dependencyInfo.symbolToProviders.put(providedEntity,node);
    }
  }

  return dependencyInfo;
}
项目:buck    文件:ProjectBuildFileParserFactory.java   
/**
 * Callers are responsible for managing the life-cycle of the created {@link
 * ProjectBuildFileParser}.
 */
public static ProjectBuildFileParser createBuildFileParser(
    Cell cell,TypeCoercerFactory typeCoercerFactory,BuckEventBus eventBus,ExecutableFinder executableFinder,Iterable<Description<?>> descriptions) {
  return createBuildFileParser(
      cell,typeCoercerFactory,eventBus,new ParserpythoninterpreterProvider(cell.getBuckConfig(),executableFinder),descriptions,/* enableProfiling */
      false);
}
项目:buck    文件:ProjectBuildFileParserFactory.java   
/**
 * Callers are responsible for managing the life-cycle of the created {@link
 * ProjectBuildFileParser}.
 */
public static ProjectBuildFileParser createBuildFileParser(
    Cell cell,ParserpythoninterpreterProvider pythoninterpreterProvider,pythoninterpreterProvider,/* enableProfiling */
      false);
}
项目:buck    文件:VersionedTargetGraph.java   
private HumanReadableException getUnexpectedVersionednodeError(TargetNode<?,?> node) {
  String msg =
      String.format(
          "Found versioned node %s from unversioned,top-level target:%s",node.getBuildTarget(),System.lineseparator());
  ArrayList<TargetNode<?,?>> trace = new ArrayList<>();
  for (TargetNode<?,?> n = node; n != null; n = getVersionedSubGraPHParent(n)) {
    trace.add(n);
  }
  msg +=
      trace
          .stream()
          .map(
              n ->
                  String.format(
                      "    %s (%s)",n,Description.getbuildruleType(n.getDescription())))
          .collect(Collectors.joining(" depended on by" + System.lineseparator()));
  return new HumanReadableException(msg);
}
项目:buck    文件:PythonDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  BuckConfig buckConfig = context.getBuckConfig();
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(buckConfig);
  PythonBuckConfig pyConfig = new PythonBuckConfig(buckConfig);
  ToolchainProvider toolchainProvider = context.getToolchainProvider();

  PythonBinaryDescription pythonBinaryDescription =
      new PythonBinaryDescription(toolchainProvider,pyConfig,cxxBuckConfig);

  return Arrays.asList(
      pythonBinaryDescription,new PrebuiltPythonLibraryDescription(),new PythonLibraryDescription(toolchainProvider),new PythonTestDescription(
          toolchainProvider,pythonBinaryDescription,cxxBuckConfig),new CxxPythonExtensionDescription(toolchainProvider,cxxBuckConfig));
}
项目:buck    文件:AppleTestDescription.java   
private AppleBundle getbuildruleForTestHostAppTarget(
    BuildTarget buildTarget,buildruleResolver resolver,BuildTarget testHostBuildTarget,AppleDebugFormat debugFormat,Iterable<Flavor> additionalFlavors,String testHostKeyName) {
  buildrule rule =
      resolver.requireRule(
          testHostBuildTarget.withAppendedFlavors(
              ImmutableSet.<Flavor>builder()
                  .addAll(additionalFlavors)
                  .add(debugFormat.getFlavor(),StripStyle.NON_GLOBAL_SYMBOLS.getFlavor())
                  .build()));

  if (!(rule instanceof AppleBundle)) {
    throw new HumanReadableException(
        "Apple test rule '%s' has %s '%s' not of type '%s'.",buildTarget,testHostKeyName,testHostBuildTarget,Description.getbuildruleType(AppleBundleDescription.class));
  }
  return (AppleBundle) rule;
}
项目:buck    文件:Applebuildrules.java   
@SuppressWarnings("unchecked")
public static <T> ImmutableSet<T> collectTransitivebuildrules(
    TargetGraph targetGraph,Optional<AppleDependenciesCache> cache,ImmutableSet<Class<? extends Description<?>>> descriptionClasses,Collection<TargetNode<?,?>> targetNodes) {
  return RichStream.from(targetNodes)
      .flatMap(
          targetNode ->
              getRecursiveTargetNodeDependenciesOfTypes(
                      targetGraph,cache,RecursiveDependenciesMode.copYING,targetNode,descriptionClasses)
                  .stream())
      .map(input -> (T) input.getConstructorArg())
      .toImmutableSet();
}
项目:buck    文件:ProjectGenerator.java   
@SuppressWarnings("unchecked")
private static Optional<TargetNode<CxxLibraryDescription.CommonArg,?>> getAppleNativeNodeOfType(
    TargetGraph targetGraph,TargetNode<?,?> targetNode,Set<Class<? extends Description<?>>> nodeTypes,Set<AppleBundleExtension> bundleExtensions) {
  Optional<TargetNode<CxxLibraryDescription.CommonArg,?>> nativeNode = Optional.empty();
  if (nodeTypes.contains(targetNode.getDescription().getClass())) {
    nativeNode = Optional.of((TargetNode<CxxLibraryDescription.CommonArg,?>) targetNode);
  } else if (targetNode.getDescription() instanceof AppleBundleDescription) {
    TargetNode<AppleBundleDescriptionArg,?> bundle =
        (TargetNode<AppleBundleDescriptionArg,?>) targetNode;
    Either<AppleBundleExtension,String> extension = bundle.getConstructorArg().getExtension();
    if (extension.isLeft() && bundleExtensions.contains(extension.getLeft())) {
      nativeNode =
          Optional.of(
              (TargetNode<CxxLibraryDescription.CommonArg,?>)
                  targetGraph.get(bundle.getConstructorArg().getBinary()));
    }
  }
  return nativeNode;
}
项目:buck    文件:JsBundleDescription.java   
ImmutableSortedSet<JsLibrary> collect(Collection<BuildTarget> deps) {
  ImmutableSortedSet.Builder<JsLibrary> jsLibraries = ImmutableSortedSet.naturalOrder();

  new AbstractBreadthFirstTraversal<BuildTarget>(deps) {
    @Override
    public Iterable<BuildTarget> visit(BuildTarget target) throws RuntimeException {
      final TargetNode<?,?> targetNode = targetGraph.get(target);
      final Description<?> description = targetNode.getDescription();

      if (description instanceof JsLibraryDescription) {
        final JsLibrary library = requireLibrary(target);
        jsLibraries.add(library);
        return getLibraryDependencies(library);
      } else if (description instanceof AndroidLibraryDescription
          || description instanceof AppleLibraryDescription) {
        return targetNode.getDeclaredDeps();
      }

      return ImmutableList.of();
    }
  }.start();

  return jsLibraries.build();
}
项目:buck    文件:TargetsCommand.java   
@SuppressWarnings("unchecked")
private Optional<ImmutableSet<Class<? extends Description<?>>>> getDescriptionClassFromParams(
    CommandRunnerParams params) {
  ImmutableSet<String> types = getTypes();
  ImmutableSet.Builder<Class<? extends Description<?>>> descriptionClassesBuilder =
      ImmutableSet.builder();
  for (String name : types) {
    try {
      KNownbuildruleTypes kNownbuildruleTypes =
          params.getKNownbuildruleTypesProvider().get(params.getCell());
      buildruleType type = kNownbuildruleTypes.getbuildruleType(name);
      Description<?> description = kNownbuildruleTypes.getDescription(type);
      descriptionClassesBuilder.add((Class<? extends Description<?>>) description.getClass());
    } catch (IllegalArgumentException e) {
      params.getBuckEventBus().post(ConsoleEvent.severe("Invalid build rule type: " + name));
      return Optional.empty();
    }
  }
  return Optional.of(descriptionClassesBuilder.build());
}
项目:buck    文件:SkylarkProjectBuildFileParser.java   
/**
 * Create a Skylark deFinition for the {@code ruleClass} rule.
 *
 * <p>This makes functions like @{code java_library} available in build files. All they do is
 * capture passed attribute values in a map and adds them to the {@code ruleRegistry}.
 *
 * @param ruleClass The name of the rule to to define.
 * @return Skylark function to handle the Buck rule.
 */
private BuiltinFunction newRuleDeFinition(Description<?> ruleClass) {
  String name = Description.getbuildruleType(ruleClass).getName();
  return new BuiltinFunction(
      name,FunctionSignature.kwargs,BuiltinFunction.USE_AST_ENV,/*isRule=*/ true) {

    @SuppressWarnings({"unused"})
    public Runtime.nonetype invoke(
        Map<String,Object> kwargs,FuncallExpression ast,Environment env) throws EvalException {
      ImmutableMap.Builder<String,Object> builder =
          ImmutableMap.<String,Object>builder()
              .put("buck.base_path",env.lookup(Runtime.PKG_NAME))
              .put("buck.type",name);
      ImmutableMap<String,ParamInfo> allParamInfo =
          CoercedTypeCache.INSTANCE.getAllParamInfo(
              typeCoercerFactory,ruleClass.getConstructorArgType());
      populateAttributes(kwargs,builder,allParamInfo);
      throwOnMissingrequiredAttribute(kwargs,allParamInfo,getName(),ast);
      ParseContext parseContext = getParseContext(env,ast);
      parseContext.recordRule(builder.build());
      return Runtime.NONE;
    }
  };
}
项目:buck-cutom    文件:DefaultProjectBuildFileParserFactory.java   
public DefaultProjectBuildFileParserFactory(
    ProjectFilesystem projectFilesystem,ImmutableSet<Description<?>> descriptions) {
  this.projectFilesystem = Preconditions.checkNotNull(projectFilesystem);
  this.pythoninterpreter = Preconditions.checkNotNull(pythoninterpreter);
  this.descriptions = Preconditions.checkNotNull(descriptions);
}
项目:buck    文件:JavaDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig config = context.getBuckConfig();
  JavaBuckConfig javaConfig = config.getView(JavaBuckConfig.class);

  return Arrays.asList(
      new JarGenruleDescription(toolchainProvider,context.getSandBoxExecutionStrategy()),new JavaBinaryDescription(toolchainProvider,javaConfig),new JavaAnnotationProcessorDescription(),new JavaLibraryDescription(toolchainProvider,new JavaTestDescription(toolchainProvider,new KeystoreDescription());
}
项目:buck    文件:ScalaDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig config = context.getBuckConfig();
  ScalaBuckConfig scalaConfig = new ScalaBuckConfig(config);
  JavaBuckConfig javaConfig = config.getView(JavaBuckConfig.class);

  return Arrays.asList(
      new ScalaLibraryDescription(toolchainProvider,scalaConfig,new ScalaTestDescription(toolchainProvider,javaConfig));
}
项目:buck    文件:GroovyDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig config = context.getBuckConfig();
  GroovyBuckConfig groovyBuckConfig = new GroovyBuckConfig(config);
  JavaBuckConfig javaConfig = config.getView(JavaBuckConfig.class);

  return Arrays.asList(
      new GroovyLibraryDescription(toolchainProvider,groovyBuckConfig,new GroovyTestDescription(toolchainProvider,javaConfig));
}
项目:buck    文件:KotlinDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig config = context.getBuckConfig();
  KotlinBuckConfig kotlinBuckConfig = new KotlinBuckConfig(config);
  JavaBuckConfig javaConfig = config.getView(JavaBuckConfig.class);

  return Arrays.asList(
      new KotlinLibraryDescription(toolchainProvider,kotlinBuckConfig,new KotlinTestDescription(toolchainProvider,javaConfig));
}
项目:buck    文件:PrebuiltCxxLibraryDescription.java   
private PrebuiltCxxLibraryPaths getPaths(
    BuildTarget target,AbstractPrebuiltCxxLibraryDescriptionArg args,Optional<String> versionSubDir) {
  if (args.isNewApiUsed() && args.isOldApiUsed()) {
    throw new HumanReadableException("%s: cannot use both old and new APIs",target);
  }
  if (args.isOldApiUsed()) {
    if (!cxxBuckConfig.isDeprecatedPrebuiltCxxLibraryApiEnabled()) {
      throw new HumanReadableException(
          "%s(%s) uses the deprecated API,but `cxx.enable_deprecated_prebuilt_cxx_library_api` "
              + "isn't set.  Please see the `prebuilt_cxx_library` documentation for details and "
              + "examples on how to port to the new API.",Description.getbuildruleType(this).toString(),target);
    }
    return DeprecatedPrebuiltCxxLibraryPaths.builder()
        .setTarget(target)
        .setVersionSubdir(versionSubDir)
        .setIncludeDirs(args.getIncludeDirs().orElse(ImmutableList.of()))
        .setLibDir(args.getLibDir())
        .setLibName(args.getLibName())
        .build();
  }
  return NewPrebuiltCxxLibraryPaths.builder()
      .setTarget(target)
      .setHeaderDirs(args.getHeaderDirs())
      .setPlatformHeaderDirs(args.getPlatformHeaderDirs())
      .setVersionedHeaderDirs(args.getVersionedHeaderDirs())
      .setSharedLib(args.getSharedLib())
      .setPlatformSharedLib(args.getPlatformSharedLib())
      .setVersionedSharedLib(args.getVersionedSharedLib())
      .setStaticLib(args.getStaticLib())
      .setPlatformStaticLib(args.getPlatformStaticLib())
      .setVersionedStaticLib(args.getVersionedStaticLib())
      .setStaticPicLib(args.getStaticPicLib())
      .setPlatformStaticPicLib(args.getPlatformStaticPicLib())
      .setVersionedStaticPicLib(args.getVersionedStaticPicLib())
      .build();
}
项目:buck    文件:PerBuildState.java   
private ProjectBuildFileParser createBuildFileParser(
    Cell cell,Iterable<Description<?>> descriptions) {
  return ProjectBuildFileParserFactory.createBuildFileParser(
      cell,this.parser.getTypeCoercerFactory(),parserpythoninterpreterProvider,enableProfiling);
}
项目:buck    文件:AbstractTargetNodePredicateSpec.java   
@Override
public ImmutableMap<BuildTarget,Optional<TargetNode<?,?>>> filter(
    Iterable<TargetNode<?,?>> nodes) {
  ImmutableMap.Builder<BuildTarget,?>>> resultBuilder =
      ImmutableMap.builder();

  for (TargetNode<?,?> node : nodes) {
    if (!onlyTests() || Description.getbuildruleType(node.getDescription()).isTestRule()) {
      resultBuilder.put(node.getBuildTarget(),Optional.of(node));
    }
  }

  return resultBuilder.build();
}
项目:buck    文件:SwiftDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig config = context.getBuckConfig();
  SwiftBuckConfig swiftBuckConfig = new SwiftBuckConfig(config);
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(config);

  return Collections.singleton(
      new SwiftLibraryDescription(toolchainProvider,cxxBuckConfig,swiftBuckConfig));
}
项目:buck    文件:TargetGraphVersionTransformations.java   
public static <A,B extends Description<A>> Iterable<BuildTarget> getDeps(
    TypeCoercerFactory typeCoercerFactory,TargetNode<A,B> node) {
  return Iterables.concat(
      node.getDeclaredDeps(),node.getExTradeps(),getVersionedDeps(typeCoercerFactory,node).keySet());
}
项目:buck    文件:PythonDslProjectBuildFileParser.java   
private synchronized Path getPathToBuckPy(ImmutableSet<Description<?>> descriptions)
    throws IOException {
  if (buckPythonProgram == null) {
    buckPythonProgram =
        BuckPythonProgram.newInstance(
            typeCoercerFactory,!options.getEnableProfiling());
  }
  return buckPythonProgram.getExecutablePath();
}
项目:buck    文件:GoDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  GoBuckConfig goBuckConfig = new GoBuckConfig(context.getBuckConfig());
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(context.getBuckConfig());
  ToolchainProvider toolchainProvider = context.getToolchainProvider();

  return Arrays.asList(
      new GoBinaryDescription(goBuckConfig,toolchainProvider),new GoLibraryDescription(goBuckConfig,new CgoLibraryDescription(goBuckConfig,new GoTestDescription(goBuckConfig,toolchainProvider));
}
项目:buck    文件:DDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  BuckConfig buckConfig = context.getBuckConfig();
  DBuckConfig dBuckConfig = new DBuckConfig(buckConfig);
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(buckConfig);

  return Arrays.asList(
      new DBinaryDescription(toolchainProvider,dBuckConfig,new DLibraryDescription(toolchainProvider,new DTestDescription(toolchainProvider,cxxBuckConfig));
}
项目:buck    文件:LuaDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(context.getBuckConfig());

  return Arrays.asList(
      new CxxLuaExtensionDescription(toolchainProvider,new LuaBinaryDescription(toolchainProvider,new LuaLibraryDescription());
}
项目:buck    文件:AppleLibraryDescription.java   
@Override
public ImmutableSortedSet<Flavor> addImplicitFlavors(
    ImmutableSortedSet<Flavor> argDefaultFlavors) {
  // Use defaults.apple_library if present,but fall back to defaults.cxx_library otherwise.
  return cxxLibraryImplicitFlavors.addImplicitFlavorsForRuleTypes(
      argDefaultFlavors,Description.getbuildruleType(this),Description.getbuildruleType(CxxLibraryDescription.class));
}
项目:buck    文件:Applebuildrules.java   
public static ImmutableSet<TargetNode<?,?>> getRecursiveTargetNodeDependenciesOfTypes(
    final TargetGraph targetGraph,final Optional<AppleDependenciesCache> cache,final RecursiveDependenciesMode mode,final TargetNode<?,final Optional<ImmutableSet<Class<? extends Description<?>>>> descriptionClasses) {
  LOG.verbose(
      "Getting recursive dependencies of node %s,mode %s,including only types %s\n",mode,descriptionClasses);
  Predicate<TargetNode<?,?>> isDependencyNode =
      descriptionClasses
          .map(
              classes ->
                  (Predicate<TargetNode<?,?>>)
                      node -> classes.contains(node.getDescription().getClass()))
          .orElse(x -> true);

  ImmutableSet<TargetNode<?,?>> result =
      getRecursiveTargetNodeDependenciesOfTypes(
          targetGraph,isDependencyNode);

  LOG.verbose(
      "Got recursive dependencies of node %s mode %s types %s: %s\n",descriptionClasses,result);

  return result;
}
项目:buck    文件:Applebuildrules.java   
public static ImmutableSet<TargetNode<?,?>> getRecursiveTargetNodeDependenciesOfTypes(
    TargetGraph targetGraph,RecursiveDependenciesMode mode,?> input,ImmutableSet<Class<? extends Description<?>>> descriptionClasses) {
  return getRecursiveTargetNodeDependenciesOfTypes(
      targetGraph,input,Optional.of(descriptionClasses));
}
项目:buck    文件:XCodeProjectCommandHelper.java   
private static boolean canGenerateImplicitWorkspaceForDescription(Description<?> description) {
  // We weren't given a workspace target,but we may have been given something that Could
  // still turn into a workspace (for example,a library or an actual app rule). If that's the
  // case we still want to generate a workspace.
  return description instanceof AppleBinaryDescription
      || description instanceof AppleBundleDescription
      || description instanceof AppleLibraryDescription;
}
项目:buck    文件:ProjectGenerator.java   
/** List of frameworks and libraries that goes into the "Link Binary With Libraries" phase. */
private Iterable<FrameworkPath> collectRecursiveFrameworkDependencies(
    TargetNode<?,?> targetNode) {
  return FluentIterable.from(
          Applebuildrules.getRecursiveTargetNodeDependenciesOfTypes(
              targetGraph,Optional.of(dependenciesCache),Applebuildrules.RecursiveDependenciesMode.LINKING,ImmutableSet.<Class<? extends Description<?>>>builder()
                  .addAll(Applebuildrules.XCODE_TARGET_DESCRIPTION_CLASSES)
                  .add(PrebuiltAppleFrameworkDescription.class)
                  .build()))
      .transformAndConcat(
          input -> {
            // Libraries and bundles which has system frameworks and libraries.
            Optional<TargetNode<CxxLibraryDescription.CommonArg,?>> library =
                getLibraryNode(targetGraph,input);
            if (library.isPresent()
                && !AppleLibraryDescription.isNotStaticallyLinkedLibraryNode(library.get())) {
              return Iterables.concat(
                  library.get().getConstructorArg().getFrameworks(),library.get().getConstructorArg().getLibraries());
            }

            Optional<TargetNode<PrebuiltAppleFrameworkDescriptionArg,?>> prebuilt =
                input.castArg(PrebuiltAppleFrameworkDescriptionArg.class);
            if (prebuilt.isPresent()) {
              return Iterables.concat(
                  prebuilt.get().getConstructorArg().getFrameworks(),prebuilt.get().getConstructorArg().getLibraries(),ImmutableList.of(
                      FrameworkPath.ofSourcePath(
                          prebuilt.get().getConstructorArg().getFramework())));
            }

            return ImmutableList.of();
          });
}
项目:buck    文件:AppleBinaryDescription.java   
@Override
public ImmutableSortedSet<Flavor> addImplicitFlavors(
    ImmutableSortedSet<Flavor> argDefaultFlavors) {
  // Use defaults.apple_binary if present,but fall back to defaults.cxx_binary otherwise.
  return cxxBinaryImplicitFlavors.addImplicitFlavorsForRuleTypes(
      argDefaultFlavors,Description.getbuildruleType(CxxBinaryDescription.class));
}
项目:buck    文件:RustDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  RustBuckConfig rustBuckConfig = new RustBuckConfig(context.getBuckConfig());

  return Arrays.asList(
      new RustBinaryDescription(toolchainProvider,rustBuckConfig),new RustLibraryDescription(toolchainProvider,new RustTestDescription(toolchainProvider,new PrebuiltRustLibraryDescription());
}
项目:buck    文件:JsDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  ToolchainProvider toolchainProvider = context.getToolchainProvider();
  return Arrays.asList(
      new JsLibraryDescription(),new JsBundleGenruleDescription(toolchainProvider,new JsBundleDescription(toolchainProvider));
}
项目:buck    文件:JsLibraryDescription.java   
JsLibrary verifyIsJsLibraryRule(buildrule rule) {
  if (!(rule instanceof JsLibrary)) {
    BuildTarget target = rule.getBuildTarget();
    throw new HumanReadableException(
        "js_library target '%s' can only depend on other js_library targets,but one of its "
            + "dependencies,'%s',is of type %s.",baseTarget,target,Description.getbuildruleType(targetGraph.get(target).getDescription()).getName());
  }

  return (JsLibrary) rule;
}
项目:buck    文件:HalideDescriptionsprovider.java   
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
  BuckConfig buckConfig = context.getBuckConfig();
  CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(buckConfig);
  HalideBuckConfig halideBuckConfig = new HalideBuckConfig(buckConfig);

  return Collections.singleton(
      new HalideLibraryDescription(
          context.getToolchainProvider(),halideBuckConfig));
}

com.facebook.buck.step.ExecutionContext的实例源码

com.facebook.buck.step.ExecutionContext的实例源码

项目:buck-cutom    文件:DxStepTest.java   
@Test
public void testdxcommandOptimizeNoJumbo() {
  // Context with --verbose 2.
  ExecutionContext context = createExecutionContext(2);
  Function<Path,Path> pathAbsolutifier = context.getProjectFilesystem().getAbsolutifier();

  DxStep dx = new DxStep(SAMPLE_OUTPUT_PATH,SAMPLE_FILES_TO_DEX);

  String expected = String.format("%s --output %s %s",EXPECTED_DX_PREFIX,SAMPLE_OUTPUT_PATH,Joiner.on(' ').join(Iterables.transform(SAMPLE_FILES_TO_DEX,pathAbsolutifier)));
  MoreAsserts.assertShellCommands(
      "Neither --no-optimize nor --force-jumbo should be present.",ImmutableList.of(expected),ImmutableList.<Step>of(dx),context);
  verifyAll();
}
项目:buck-cutom    文件:SymlinkFilesIntoDirectoryStep.java   
@Override
public int execute(ExecutionContext context) {
  // Note that because these paths are resolved to absolute paths,the symlinks will be absolute
  // paths,as well.
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  Path outDir = projectFilesystem.resolve(this.outDir);
  Path srcDir = projectFilesystem.resolve(this.srcDir);

  for (Path entry : entries) {
    Path link = outDir.resolve(entry);
    Path target = srcDir.resolve(entry);
    try {
      Files.createDirectories(link.getParent());
      Files.createSymbolicLink(link,target);
    } catch (IOException e) {
      context.logError(e,"Failed to create symlink from %s to %s.",link,target);
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:TouchStepTest.java   
@Test
public void testGetShellCommand() {
  Path someFile = Paths.get("a/file.txt");
  TouchStep touchStep = new TouchStep(someFile);

  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem() {
    @Override
    public Path resolve(Path relativePath) {
      return Paths.get("/abs/path").resolve(relativePath);
    }
  };
  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();
  assertEquals(
      ImmutableList.of("touch","/abs/path/a/file.txt"),touchStep.getShellCommandInternal(executionContext));
}
项目:buck-cutom    文件:DxStep.java   
private int executeInProcess(ExecutionContext context) {
  ImmutableList<String> argv = getShellCommandInternal(context);

  // The first arguments should be ".../dx --dex".  Strip them off
  // because we bypass the dispatcher and go straight to the dexer.
  Preconditions.checkState(argv.get(0).endsWith("/dx"));
  Preconditions.checkState(argv.get(1).equals("--dex"));
  ImmutableList<String> args = argv.subList(2,argv.size());

  try {
    return new com.android.dx.command.dexer.Main().run(
        args.toArray(new String[args.size()]),context.getStdOut(),context.getStdErr()
    );
  } catch (IOException e) {
    e.printstacktrace(context.getStdErr());
    return 1;
  }
}
项目:buck-cutom    文件:Genrule.java   
public AbstractGenruleStep createGenruleStep() {
  // The user's command (this.cmd) should be run from the directory that contains only the
  // symlinked files. This ensures that the user can reference only the files that were declared
  // as srcs. Without this,a genrule is not guaranteed to be hermetic.
  File workingDirectory = new File(absolutePathToSrcDirectory.toString());

  return new AbstractGenruleStep(
      getType(),getBuildTarget(),new CommandString(cmd,bash,cmdExe),getDeps(),workingDirectory) {
    @Override
    protected void addEnvironmentvariables(
        ExecutionContext context,ImmutableMap.Builder<String,String> environmentvariablesBuilder) {
      Genrule.this.addEnvironmentvariables(context,environmentvariablesBuilder);
    }
  };
}
项目:buck-cutom    文件:TestCommandTest.java   
@Test
public void testIsTestRunrequiredForTestInDebugMode()
    throws IOException,ExecutionException,InterruptedException {
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  expect(executionContext.isDebugEnabled()).andReturn(true);

  replay(executionContext);

  assertTrue(
      "In debug mode,test should always run regardless of any cached results since " +
          "the user is expecting to hook up a debugger.",TestCommand.isTestRunrequiredForTest(
          createMock(TestRule.class),createMock(CachingBuildEngine.class),executionContext,createMock(TestRuleKeyFileHelper.class),true,false));

  verify(executionContext);
}
项目:buck-cutom    文件:PrebuiltJar.java   
@Override
public int execute(ExecutionContext context) {
  // Todo(simons): Because binaryJar Could be a generated file,it may not be bit-for-bit
  // identical when generated across machines. Therefore,we should calculate its ABI based on
  // the contents of its .class files rather than just hashing its contents.
  String fileSha1;
  try {
    fileSha1 = context.getProjectFilesystem().computeSha1(binaryJar.resolve());
  } catch (IOException e) {
    context.logError(e,"Failed to calculate ABI for %s.",binaryJar);
    return 1;
  }

  Sha1HashCode abiKey = new Sha1HashCode(fileSha1);
  buildableContext.addMetadata(AbiRule.ABI_KEY_ON_disK_MetaDATA,abiKey.getHash());

  return 0;
}
项目:buck-cutom    文件:ExopackageInstaller.java   
public ExopackageInstaller(
    ExecutionContext context,AdbHelper adbHelper,InstallableApk apkRule) {
  this.adbHelper = Preconditions.checkNotNull(adbHelper);
  this.projectFilesystem = context.getProjectFilesystem();
  this.eventBus = context.getBuckEventBus();
  this.apkRule = Preconditions.checkNotNull(apkRule);
  this.packageName = AdbHelper.tryToExtractPackageNameFromManifest(apkRule,context);
  this.daTaroot = "/data/local/tmp/exopackage/" + packageName;

  Preconditions.checkArgument(AdbHelper.PACKAGE_NAME_PATTERN.matcher(packageName).matches());

  Optional<InstallableApk.ExopackageInfo> exopackageInfo = apkRule.getExopackageInfo();
  Preconditions.checkArgument(exopackageInfo.isPresent());
  this.exopackageInfo = exopackageInfo.get();
}
项目:buck-cutom    文件:JavacInMemoryStepIntegrationTest.java   
@Test
public void testGetDescription() throws IOException {
  JavacInMemoryStep javac = createJavac(/* withSyntaxError */ false);
  ExecutionContext executionContext = createExecutionContext();
  String pathToOutputDir = new File(tmp.getRoot(),"out").getAbsolutePath();
  String pathToAbiFile = new File(tmp.getRoot(),"abi").getAbsolutePath();
  assertEquals(
      String.format("javac -source %s -target %s -g " +
          "-processorpath %s " +
          "-processor %s " +
          "-A%s=%s " +
          "-d %s " +
          "-classpath '' " +
          "@" + pathToSrcslist.toString(),JavaCompilerEnvironment.TARGETED_JAVA_VERSION,AbiWritingAnnotationProcessingDataDecorator.ABI_PROCESSOR_CLAsspATH,AbiWriterProtocol.ABI_ANNOTATION_PROCESSOR_CLASS_NAME,AbiWriterProtocol.ParaM_ABI_OUTPUT_FILE,pathToAbiFile,pathToOutputDir),javac.getDescription(executionContext));
}
项目:buck-cutom    文件:JavacInMemoryStepTest.java   
@Test
public void testJavacCommand() {
  ExecutionContext context = TestExecutionContext.newInstance();

  JavacInMemoryStep firstOrder = createTestStep(BuildDependencies.FirsT_ORDER_ONLY);
  JavacInMemoryStep warn = createTestStep(BuildDependencies.WARN_ON_TRANSITIVE);
  JavacInMemoryStep transitive = createTestStep(BuildDependencies.TRANSITIVE);

  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath foo.jar @%s",TARGETED_JAVA_VERSION,PATH_TO_SRCS_LIST),firstOrder.getDescription(context));
  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath foo.jar @%s",warn.getDescription(context));
  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath bar.jar%sfoo.jar @%s",File.pathSeparator,transitive.getDescription(context));
}
项目:buck-cutom    文件:SymlinkTreeStep.java   
@Override
public int execute(ExecutionContext context) {
  for (ImmutableMap.Entry<Path,Path> ent : links.entrySet()) {
    Path target = context.getProjectFilesystem().resolve(ent.getValue());
    Path link = context.getProjectFilesystem().resolve(root.resolve(ent.getKey()));
    try {
      context.getProjectFilesystem().mkdirs(link.getParent());
      context.getProjectFilesystem().createSymLink(target,true /* force */);
    } catch (IOException e) {
      String msg = String.format("Failed creating linking \"%s\" -> \"%s\"",target);
      context.logError(e,msg);
      e.printstacktrace(context.getStdErr());
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:RmStep.java   
public ImmutableList<String> getShellCommand(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  args.add("rm");

  if (shouldRecurse) {
    args.add("-r");
  }

  if (shouldForceDeletion) {
    args.add("-f");
  }

  Path absolutePath = context.getProjectFilesystem().resolve(toDelete);
  args.add(absolutePath.toString());

  return args.build();
}
项目:buck-cutom    文件:RmStep.java   
@Override
public int execute(ExecutionContext context) {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  if (shouldRecurse) {
    // Delete a folder recursively
    try {
      projectFilesystem.rmdir(toDelete);
    } catch (IOException e) {
      if (shouldForceDeletion) {
        return 0;
      }
      e.printstacktrace(context.getStdErr());
      return 1;
    }
  } else {
    // Delete a single file
    File file = projectFilesystem.resolve(toDelete).toFile();
    if (!file.delete() && !shouldForceDeletion) {
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:UnzipStepTest.java   
@Test
public void testGetShellCommand() {
  Path zipFile = Paths.get("the/zipfile.zip");
  Path outputDirectory = Paths.get("an/output/dir");
  UnzipStep unzipStep = new UnzipStep(zipFile,outputDirectory);

  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem() {
    @Override
    public Path resolve(Path relativePath) {
      return Paths.get("/abs/path").resolve(relativePath);
    }
  };
  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();
  assertEquals(
      "unzip /abs/path/the/zipfile.zip -d /abs/path/an/output/dir",unzipStep.getDescription(executionContext));
}
项目:buck-cutom    文件:ProGuardobfuscateStepTest.java   
@Test
public void testSdkConfigArgs() {
  ExecutionContext context = createMock(ExecutionContext.class);
  AndroidplatformTarget target = createMock(AndroidplatformTarget.class);
  expect(context.getProjectDirectoryRoot()).andStubReturn(Paths.get("root"));
  expect(context.getAndroidplatformTarget()).andStubReturn(target);
  expect(target.getProguardConfig()).andStubReturn(Paths.get("sdk-default.pro"));
  expect(target.getoptimizedProguardConfig()).andStubReturn(Paths.get("sdk-optimized.pro"));
  expect(target.getbootclasspathEntries()).andStubReturn(ImmutableList.<Path>of());
  replayAll();

  checkSdkConfig(context,ProGuardobfuscateStep.SdkProguardType.DEFAULT,"sdk-default.pro");
  checkSdkConfig(context,ProGuardobfuscateStep.SdkProguardType.OPTIMIZED,"sdk-optimized.pro");
  checkSdkConfig(context,ProGuardobfuscateStep.SdkProguardType.NONE,null);

  verifyAll();
}
项目:buck-cutom    文件:copyStep.java   
@Override
public String getDescription(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  args.add("cp");
  switch (copySourceMode) {
    case FILE:
      args.add(source.toString());
      break;
    case DIRECTORY_AND_CONTENTS:
      args.add("-R");
      args.add(source.toString());
      break;
    case DIRECTORY_CONTENTS_ONLY:
      args.add("-R");
      // BSD and GNU cp have different behaviors with -R:
      // http://jondavidjohn.com/blog/2012/09/linux-vs-osx-the-cp-command
      //
      // To work around this,we use "sourceDir/*" as the source to
      // copy in this mode.
      args.add(source.resolve("*").toString());
      break;
  }
  args.add(destination.toString());
  return Joiner.on(" ").join(args.build());
}
项目:buck-cutom    文件:Genrule.java   
protected void addEnvironmentvariables(ExecutionContext context,String> environmentvariablesBuilder) {
  environmentvariablesBuilder.put("SRCS",Joiner.on(' ').join(srcsToAbsolutePaths.values()));
  environmentvariablesBuilder.put("OUT",getAbsoluteOutputFilePath());

  final Set<String> depFiles = Sets.newHashSet();
  final Set<buildrule> processedbuildrules = Sets.newHashSet();
  for (buildrule dep : getDeps()) {
    transformNames(processedbuildrules,depFiles,dep);
  }

  environmentvariablesBuilder.put(
      "GEN_DIR",relativetoAbsolutePathFunction.apply(BuckConstant.GEN_PATH).toString());
  environmentvariablesBuilder.put("DEPS",Joiner.on(' ').skipNulls().join(depFiles));
  environmentvariablesBuilder.put("SRCDIR",absolutePathToSrcDirectory.toString());
  environmentvariablesBuilder.put("TMP",absolutePathToTmpDirectory.toString());

  Optional<AndroidplatformTarget> optionalAndroid = context.getAndroidplatformTargetoptional();
  if (optionalAndroid.isPresent()) {
    AndroidplatformTarget android = optionalAndroid.get();

    environmentvariablesBuilder.put("DX",android.getDxExecutable().toString());
    environmentvariablesBuilder.put("ZIPALIGN",android.getZipalignExecutable().toString());
  }
}
项目:buck-cutom    文件:MoreAsserts.java   
/**
 * Invokes the {@link Step#getDescription(ExecutionContext)} method on each of the observed steps
 * to create a list of strings and compares it to the expected value.
 */
public static void assertSteps(
    String userMessage,List<String> expectedStepDescriptions,List<Step> observedSteps,final ExecutionContext executionContext) {
  ImmutableList<String> commands = FluentIterable
      .from(observedSteps)
      .transform(new Function<Step,String>() {
        @Override
        public String apply(Step step) {
          return step.getDescription(executionContext);
        }
      })
      .toList();
  assertListEquals(
      userMessage,expectedStepDescriptions,commands);
}
项目:buck-cutom    文件:SmartDexingStep.java   
@Override
public String getDescription(ExecutionContext context) {
  StringBuilder b = new StringBuilder();
  b.append(getShortName());
  b.append(' ');

  Multimap<Path,Path> outputToInputs = outputToInputssupplier.get();
  for (Path output : outputToInputs.keySet()) {
    b.append("-out ");
    b.append(output.toString());
    b.append("-in ");
    Joiner.on(':').appendTo(b,Iterables.transform(outputToInputs.get(output),Functions.toStringFunction()));
  }

  return b.toString();
}
项目:buck-cutom    文件:PythonTest.java   
private Step getRunTestStep() {
  return new ShellStep() {

    @Override
    protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
      ProjectFilesystem fs = context.getProjectFilesystem();
      return ImmutableList.of(
          fs.resolve(binary.resolve()).toString(),"-o",fs.resolve(getPathToTestOutputResult()).toString());
    }

    @Override
    public String getShortName() {
      return "pyunit";
    }

  };
}
项目:buck-cutom    文件:GenerateManifestStepTest.java   
@Test
public void testManifestGeneration() throws IOException {
  String expectedOutputPath = testDataPath("AndroidManifest.expected.xml").toString();
  SourcePath libraryManifestA = testDataPath("AndroidManifestA.xml");
  SourcePath libraryManifestB = testDataPath("AndroidManifestB.xml");
  SourcePath libraryManifestC = testDataPath("AndroidManifestC.xml");
  ImmutableSet.Builder<SourcePath> libraryManifestFiles = ImmutableSet.builder();
  libraryManifestFiles.add(libraryManifestA);
  libraryManifestFiles.add(libraryManifestB);
  libraryManifestFiles.add(libraryManifestC);

  ExecutionContext context = TestExecutionContext.newInstance();

  GenerateManifestStep manifestCommand = new GenerateManifestStep(
      skeletonPath,libraryManifestFiles.build(),manifestPath);
  int result = manifestCommand.execute(context);

  assertEquals(0,result);

  String expected = Files.toString(new File(expectedOutputPath),Charsets.UTF_8);
  String output = Files.toString(manifestPath.toFile(),Charsets.UTF_8);

  assertEquals(expected,output);
}
项目:buck-cutom    文件:ShTestTest.java   
@Test
public void testHasTestResultFiles() {
  ShTest shTest = new ShTest(
      new FakebuildruleParamsBuilder(
          BuildTarget.builder("//test/com/example","my_sh_test").build())
          .build(),new TestSourcePath("run_test.sh"),/* labels */ ImmutableSet.<Label>of());

  ProjectFilesystem filesystem = createMock(ProjectFilesystem.class);
  EasyMock.expect(filesystem.isFile(shTest.getPathToTestOutputResult())).andReturn(true);
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  EasyMock.expect(executionContext.getProjectFilesystem()).andReturn(filesystem);

  replayAll();

  assertTrue("hasTestResultFiles() should return true if result.json exists.",shTest.hasTestResultFiles(executionContext));
}
项目:buck-cutom    文件:ExternalJavacTest.java   
@Test
public void testJavacCommand() {
  ExecutionContext context = TestExecutionContext.newInstance();

  ExternalJavacStep firstOrder = createTestStep(BuildDependencies.FirsT_ORDER_ONLY);
  ExternalJavacStep warn = createTestStep(BuildDependencies.WARN_ON_TRANSITIVE);
  ExternalJavacStep transitive = createTestStep(BuildDependencies.TRANSITIVE);

  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath foo.jar @" + PATH_TO_SRCS_LIST,firstOrder.getDescription(context));
  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath foo.jar @" + PATH_TO_SRCS_LIST,warn.getDescription(context));
  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath bar.jar" + File.pathSeparator +
      "foo.jar @" + PATH_TO_SRCS_LIST,transitive.getDescription(context));
}
项目:buck-cutom    文件:GenProGuardConfigStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  AndroidplatformTarget androidplatformTarget = context.getAndroidplatformTarget();

  args.add(androidplatformTarget.getAaptExecutable().toString());
  args.add("package");

  // Specify where the ProGuard config should be written.
  args.add("-G").add(proguardConfigurationPath.toString());

  // Add all of the res/ directories.
  for (Path res : resDirectories) {
    args.add("-S").add(res.toString());
  }

  // Add the remaining flags.
  args.add("-M").add(androidManifestPath.toString());
  args.add("--auto-add-overlay");
  args.add("-I").add(androidplatformTarget.getAndroidJar().toString());

  return args.build();
}
项目:buck-cutom    文件:ApkBuilderStep.java   
private PrivateKeyAndCertificate createKeystoreProperties(ExecutionContext context)
    throws CertificateException,IOException,KeyStoreException,NoSuchAlgorithmException,UnrecoverableKeyException {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  KeystoreProperties keystoreProperties = KeystoreProperties.createFromPropertiesFile(
      pathToKeystore,pathToKeystorePropertiesFile,projectFilesystem);
  KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
  InputStream inputStream = projectFilesystem.getInputStreamForRelativePath(pathToKeystore);
  char[] keystorePassword = keystoreProperties.getStorepass().tochararray();
  keystore.load(inputStream,keystorePassword);

  String alias = keystoreProperties.getAlias();
  char[] keyPassword = keystoreProperties.getKeypass().tochararray();
  Key key = keystore.getKey(alias,keyPassword);
  Certificate certificate = keystore.getCertificate(alias);

  return new PrivateKeyAndCertificate((PrivateKey) key,(X509Certificate) certificate);
}
项目:buck-cutom    文件:SplitZipStep.java   
/**
 * Construct a {@link Set} of internal class names that must go into the primary dex.
 * <p/>
 * @return ImmutableSet of class internal names.
 */
private ImmutableSet<String> getrequiredPrimaryDexClassNames(
    ExecutionContext context,ProguardTranslatorFactory translatorFactory,supplier<ImmutableList<ClassNode>> classessupplier)
    throws IOException {
  ImmutableSet.Builder<String> builder = ImmutableSet.builder();

  Optional<Path> primaryDexClassesFile = dexSplitMode.getPrimaryDexClassesFile()
      .transform(SourcePaths.TO_PATH);
  if (primaryDexClassesFile.isPresent()) {
    Iterable<String> classes = FluentIterable
        .from(context.getProjectFilesystem().readLines(primaryDexClassesFile.get()))
        .transform(STRING_TRIM)
        .filter(IS_NEITHER_EMPTY_nor_COMMENT);
    builder.addAll(classes);
  }

  // If there is a scenario file but overflow is not allowed,then the scenario dependencies
  // are required,and therefore get added here.
  if (!dexSplitMode.isPrimaryDexScenarioOverflowAllowed() && primaryDexScenarioFile.isPresent()) {
    addScenarioClasses(context,translatorFactory,classessupplier,builder);
  }

  return ImmutableSet.copyOf(builder.build());
}
项目:buck-cutom    文件:ShellStep.java   
/**
 * This method is idempotent.
 * @return the shell command arguments
 */
public final ImmutableList<String> getShellCommand(ExecutionContext context) {
  if (shellCommandArgs == null) {
    shellCommandArgs = getShellCommandInternal(context);
  }
  return shellCommandArgs;
}
项目:onos    文件:OsgiWrapper.java   
@Override
public StepExecutionResult execute(ExecutionContext executionContext)
        throws IOException,InterruptedException {
    stderr = executionContext.getStdErr();
    boolean success = execute();
    stderr = System.err;
    return success ? StepExecutionResult.SUCCESS : StepExecutionResult.ERROR;
}
项目:buck-cutom    文件:AppleResourceTest.java   
/**
 * Tests an apple_resource rule with a directory resource.
 */
@Test
public void testAppleResourceRuleWithDirectoryResource() throws IOException {
  AppleResourceDescription.Arg args = new AppleResourceDescription.Arg();
  args.dirs = ImmutableSortedSet.of(Paths.get("MyLibrary.bundle"));
  args.files = ImmutableSortedSet.of();
  args.variants = Optional.absent();

  AppleResource appleResource = new AppleResource(
      new FakebuildruleParamsBuilder(
          BuildTarget.builder("//path/to/app","MyApp").build()).build(),new FakeDirectoryTraverser(),args);

  FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();

  List<Step> steps = appleResource.getBuildSteps(
      FakeBuildContext.NOOP_CONTEXT,new FakeBuildableContext());

  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();

  MoreAsserts.assertSteps("copy the resources to the expected location",ImmutableList.of(
          "cp -R MyLibrary.bundle buck-out/bin/path/to/app/MyApp.app"),steps,executionContext);
}
项目:buck-cutom    文件:UnzipStep.java   
@Override
public int execute(ExecutionContext context) throws InterruptedException {
  ProjectFilesystem filesystem = context.getProjectFilesystem();
  Path zip = filesystem.getPathForRelativeExistingPath(zipFile).toAbsolutePath();
  Path out = filesystem.getPathForRelativeExistingPath(destinationDirectory).toAbsolutePath();

  try {
    Unzip.extractZipFile(zip,out,true);
  } catch (IOException e) {
    LOG.warn(e,"Unable to unpack zip: %s",zipFile);
    return 1;
  }
  return 0;
}
项目:buck-cutom    文件:UnzipStep.java   
@Override
public String getDescription(ExecutionContext context) {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  return String.format(
      "unzip %s -d %s",MorePaths.pathWithUnixSeparators(projectFilesystem.resolve(zipFile)),MorePaths.pathWithUnixSeparators(projectFilesystem.resolve(destinationDirectory)));
}
项目:buck-cutom    文件:ZipalignStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();

  AndroidplatformTarget androidplatformTarget = context.getAndroidplatformTarget();
  args.add(androidplatformTarget.getZipalignExecutable().toString());
  args.add("-f").add("4");
  args.add(inputFile.toString());
  args.add(outputFile.toString());
  return args.build();
}
项目:buck-cutom    文件:CompilerStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> cmdBuilder = ImmutableList.builder();

  cmdBuilder.add(compiler);

  if (context.isDebugEnabled()) {
    cmdBuilder.add("-g");
  }

  if (!shouldLink) {
    cmdBuilder.add("-c");
  }

  if (shouldAddProjectRoottoIncludePaths) {
    cmdBuilder.add("-I");
    cmdBuilder.add(context.getProjectDirectoryRoot().toString());
  }

  for (Path includePath : includePaths) {
    cmdBuilder.add("-I");
    cmdBuilder.add(includePath.toString());
  }

  cmdBuilder.addAll(commandLineArgs);

  for (Path src : srcs) {
    cmdBuilder.add(src.toString());
  }
  cmdBuilder.add("-o").add(outputFile.toString());

  return cmdBuilder.build();
}
项目:buck-cutom    文件:TestCommandTest.java   
@Test
public void testIsTestRunrequiredForTestBuiltFromCacheIfHasTestResultFiles()
    throws IOException,InterruptedException {
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  expect(executionContext.isDebugEnabled()).andReturn(false);

  FakeTestRule testRule = new FakeTestRule(
      JavaTestDescription.TYPE,ImmutableSet.of(new Label("windows")),BuildTargetFactory.newInstance("//:lulz"),ImmutableSortedSet.<buildrule>of(),ImmutableSet.<BuildTargetPattern>of());

  CachingBuildEngine cachingBuildEngine = createMock(CachingBuildEngine.class);
  expect(cachingBuildEngine.getbuildruleResult(BuildTargetFactory.newInstance("//:lulz")))
      .andReturn(new buildruleSuccess(testRule,buildruleSuccess.Type.FETCHED_FROM_CACHE));
  replay(executionContext,cachingBuildEngine);

  assertTrue(
      "A cache hit updates the build artifact but not the test results. " +
          "Therefore,the test should be re-run to ensure the test results are up to date.",TestCommand.isTestRunrequiredForTest(
          testRule,cachingBuildEngine,/* results cache enabled */ true,/* running with test selectors */ false));

  verify(executionContext,cachingBuildEngine);
}
项目:buck-cutom    文件:AndroidBinaryTest.java   
private void createAndroidBinaryRuleAndTestcopyNativeLibraryCommand(
    ImmutableSet<TargetcpuType> cpuFilters,String sourceDir,String destinationDir,ImmutableList<String> expectedCommandDescriptions) {

  class FakeProjectFilesystem extends ProjectFilesystem {

    public FakeProjectFilesystem() {
      super(new File("."));
    }

    @Override
    public Path resolve(Path path) {
      return path;
    }
  }

  // Invoke copyNativeLibrary to populate the steps.
  ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
  AndroidBinary.copyNativeLibrary(
      Paths.get(sourceDir),Paths.get(destinationDir),cpuFilters,stepsBuilder);
  ImmutableList<Step> steps = stepsBuilder.build();

  assertEquals(steps.size(),expectedCommandDescriptions.size());
  ExecutionContext context = createMock(ExecutionContext.class);
  expect(context.getProjectFilesystem()).andReturn(new FakeProjectFilesystem()).anyTimes();
  replay(context);

  for (int i = 0; i < steps.size(); ++i) {
    String description = steps.get(i).getDescription(context);
    assertEquals(expectedCommandDescriptions.get(i),description);
  }

  verify(context);
}
项目:buck-cutom    文件:FakeTestRule.java   
@Override
public Callable<TestResults> interpretTestResults(
    ExecutionContext executionContext,boolean isUsingTestSelectors,boolean isDryRun) {
  throw new UnsupportedOperationException("interpretTestResults() not supported in fake");
}
项目:buck-cutom    文件:SymlinkFileStepTest.java   
@Test
public void testReplaceMalformedSymlink() throws IOException,InterruptedException {
  assumeTrue(Platform.detect() != Platform.WINDOWS);

  // Run `ln -s /path/that/does/not/exist dummy` in /tmp.
  ProcessBuilder builder = new ProcessBuilder();
  builder.command("ln","-s","/path/that/does/not/exist","my_symlink");
  File tmp = tmpDir.getRoot();
  builder.directory(tmp);
  Process process = builder.start();
  process.waitFor();

  // Verify that the symlink points to a non-existent file.
  Path symlink = Paths.get(tmp.getAbsolutePath(),"my_symlink");
  assertFalse("exists() should reflect the existence of what the symlink points to",symlink.toFile().exists());
  assertTrue("even though exists() is false,isSymbolicLink should be true",java.nio.file.Files.isSymbolicLink(symlink));

  // Create an ExecutionContext to return the ProjectFilesystem.
  ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot());
  ExecutionContext executionContext = TestExecutionContext.newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();

  tmpDir.newFile("dummy");
  SymlinkFileStep symlinkStep = new SymlinkFileStep(
      /* source */ Paths.get("dummy"),/* target */ Paths.get("my_symlink"),/* useAbsolutePaths*/ true);
  int exitCode = symlinkStep.execute(executionContext);
  assertEquals(0,exitCode);
  assertTrue(java.nio.file.Files.isSymbolicLink(symlink));
  assertTrue(symlink.toFile().exists());
}
项目:buck-cutom    文件:DxStepTest.java   
@Test
public void testUseCustomDxOption() {
  // Context with --verbose 2.
  ExecutionContext context = createExecutionContext(2);
  Function<Path,SAMPLE_FILES_TO_DEX,EnumSet.of(Option.USE_CUSTOM_DX_IF_AVAILABLE),new supplier<String>() {
        @Override
        public String get() {
          return "/home/mbolin/dx";
        }
      });

  String expected = String.format("%s --output %s %s",EXPECTED_DX_PREFIX.replace("/usr/bin/dx","/home/mbolin/dx"),pathAbsolutifier)));
  MoreAsserts.assertShellCommands(
      "/home/mbolin/dx should be used instead of /usr/bin/dx.",context);
  verifyAll();
}
项目:buck-cutom    文件:ExternalJavacStep.java   
@Override
public String getDescription(ExecutionContext context) {
  StringBuilder builder = new StringBuilder(pathToJavac.toString());
  builder.append(" ");
  Joiner.on(" ").appendTo(builder,getoptions(context,getClasspathEntries()));
  builder.append(" ");

  if (pathToSrcslist.isPresent()) {
    builder.append("@").append(pathToSrcslist.get());
  } else {
    Joiner.on(" ").appendTo(builder,javaSourceFilePaths);
  }

  return builder.toString();
}
项目:buck-cutom    文件:JavacInMemoryStepIntegrationTest.java   
@Test
public void testClassesFile() throws IOException,InterruptedException {
  JavacInMemoryStep javac = createJavac(/* withSyntaxError */ false);
  ExecutionContext executionContext = createExecutionContext();
  int exitCode = javac.execute(executionContext);
  assertEquals("javac should exit with code 0.",exitCode,0);

  File srcslistFile = pathToSrcslist.toFile();
  assertTrue(srcslistFile.exists());
  assertTrue(srcslistFile.isFile());
  assertEquals("Example.java",Files.toString(srcslistFile,Charsets.UTF_8).trim());
}

关于com.facebook.FacebookAuthorizationException的实例源码facebook源代码的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于android – com.facebook.FacebookException:尝试使用未打开的Session、com.facebook.android.AsyncFacebookRunner的实例源码、com.facebook.buck.rules.Description的实例源码、com.facebook.buck.step.ExecutionContext的实例源码等相关内容,可以在本站寻找。

本文标签: