repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java
// Path: module-qualifier-inverse/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinActivityModule.java // @Module // @ActivityScope // public class NapkinActivityModule extends AbstractNapkinActivityModule { // // public NapkinActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Override // @Provides // @ActivityScope // public AppCompatActivity provideActivity() { // return activity; // } // // @Override // @Provides // @ActivityScope // @ContextActivity // public Context provideContext() { // return activity; // } // }
import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.module.NapkinActivityModule; import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.qualifier.ActivityString; import dagger.Module; import dagger.Provides;
package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @Module @ActivityScope
// Path: module-qualifier-inverse/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinActivityModule.java // @Module // @ActivityScope // public class NapkinActivityModule extends AbstractNapkinActivityModule { // // public NapkinActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Override // @Provides // @ActivityScope // public AppCompatActivity provideActivity() { // return activity; // } // // @Override // @Provides // @ActivityScope // @ContextActivity // public Context provideContext() { // return activity; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java import android.support.v7.app.AppCompatActivity; import com.github.aleksandermielczarek.napkin.module.NapkinActivityModule; import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.qualifier.ActivityString; import dagger.Module; import dagger.Provides; package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @Module @ActivityScope
public class ActivityModule extends NapkinActivityModule {
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java
// Path: module/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinFragmentModule.java // @Module // @FragmentScope // public class NapkinFragmentModule extends AbstractNapkinFragmentModule { // // public NapkinFragmentModule(Fragment fragment) { // super(fragment); // } // // @Override // @Provides // @FragmentScope // public Fragment provideFragment() { // return fragment; // } // // }
import android.support.v4.app.Fragment; import com.github.aleksandermielczarek.napkin.module.NapkinFragmentModule; import com.github.aleksandermielczarek.napkin.scope.FragmentScope; import com.github.aleksandermielczarek.napkinexample.qualifier.FragmentString; import dagger.Module; import dagger.Provides;
package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @Module @FragmentScope
// Path: module/src/main/java/com/github/aleksandermielczarek/napkin/module/NapkinFragmentModule.java // @Module // @FragmentScope // public class NapkinFragmentModule extends AbstractNapkinFragmentModule { // // public NapkinFragmentModule(Fragment fragment) { // super(fragment); // } // // @Override // @Provides // @FragmentScope // public Fragment provideFragment() { // return fragment; // } // // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java import android.support.v4.app.Fragment; import com.github.aleksandermielczarek.napkin.module.NapkinFragmentModule; import com.github.aleksandermielczarek.napkin.scope.FragmentScope; import com.github.aleksandermielczarek.napkinexample.qualifier.FragmentString; import dagger.Module; import dagger.Provides; package com.github.aleksandermielczarek.napkinexample.module; /** * Created by Aleksander Mielczarek on 18.11.2016. */ @Module @FragmentScope
public class FragmentModule extends NapkinFragmentModule {
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/NapkinApplication.java
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java // @Module // @AppScope // public class AppModule extends NapkinAppModule { // // public AppModule(Application application) { // super(application); // } // // @Provides // @AppString // String provideNapkinString() { // return "Hello Napkin in App!"; // } // // }
import android.app.Application; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.component.DaggerAppComponent; import com.github.aleksandermielczarek.napkinexample.module.AppModule;
package com.github.aleksandermielczarek.napkinexample; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class NapkinApplication extends Application implements ComponentProvider<AppComponent> { private AppComponent appComponent; @Override public void onCreate() { super.onCreate(); appComponent = DaggerAppComponent.builder()
// Path: napkin/src/main/java/com/github/aleksandermielczarek/napkin/ComponentProvider.java // public interface ComponentProvider<T> { // // T provideComponent(); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/AppComponent.java // @Component(modules = AppModule.class) // @AppScope // public interface AppComponent { // // ActivityComponent with(ActivityModule activityModule); // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/AppModule.java // @Module // @AppScope // public class AppModule extends NapkinAppModule { // // public AppModule(Application application) { // super(application); // } // // @Provides // @AppString // String provideNapkinString() { // return "Hello Napkin in App!"; // } // // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/NapkinApplication.java import android.app.Application; import com.github.aleksandermielczarek.napkin.ComponentProvider; import com.github.aleksandermielczarek.napkinexample.component.AppComponent; import com.github.aleksandermielczarek.napkinexample.component.DaggerAppComponent; import com.github.aleksandermielczarek.napkinexample.module.AppModule; package com.github.aleksandermielczarek.napkinexample; /** * Created by Aleksander Mielczarek on 13.05.2016. */ public class NapkinApplication extends Application implements ComponentProvider<AppComponent> { private AppComponent appComponent; @Override public void onCreate() { super.onCreate(); appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java // public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { // // @Inject // protected MainViewModel mainViewModel; // // private ActivityComponent activityComponent; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityComponent = Napkin.<AppComponent>provideAppComponent(this) // .with(new ActivityModule(this)); // // activityComponent.inject(this); // ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); // binding.setViewModel(mainViewModel); // } // // @Override // public ActivityComponent provideComponent() { // return activityComponent; // } // }
import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.MainActivity; import dagger.Subcomponent;
package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @ActivityScope @Subcomponent(modules = ActivityModule.class) public interface ActivityComponent {
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java // public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { // // @Inject // protected MainViewModel mainViewModel; // // private ActivityComponent activityComponent; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityComponent = Napkin.<AppComponent>provideAppComponent(this) // .with(new ActivityModule(this)); // // activityComponent.inject(this); // ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); // binding.setViewModel(mainViewModel); // } // // @Override // public ActivityComponent provideComponent() { // return activityComponent; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.MainActivity; import dagger.Subcomponent; package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @ActivityScope @Subcomponent(modules = ActivityModule.class) public interface ActivityComponent {
FragmentComponent with(FragmentModule fragmentModule);
AleksanderMielczarek/Napkin
app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java // public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { // // @Inject // protected MainViewModel mainViewModel; // // private ActivityComponent activityComponent; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityComponent = Napkin.<AppComponent>provideAppComponent(this) // .with(new ActivityModule(this)); // // activityComponent.inject(this); // ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); // binding.setViewModel(mainViewModel); // } // // @Override // public ActivityComponent provideComponent() { // return activityComponent; // } // }
import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.MainActivity; import dagger.Subcomponent;
package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @ActivityScope @Subcomponent(modules = ActivityModule.class) public interface ActivityComponent { FragmentComponent with(FragmentModule fragmentModule);
// Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/ActivityModule.java // @Module // @ActivityScope // public class ActivityModule extends NapkinActivityModule { // // public ActivityModule(AppCompatActivity activity) { // super(activity); // } // // @Provides // @ActivityString // String provideNapkinString() { // return "Hello Napkin in Activity!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/module/FragmentModule.java // @Module // @FragmentScope // public class FragmentModule extends NapkinFragmentModule { // // public FragmentModule(Fragment fragment) { // super(fragment); // } // // @Provides // @FragmentString // String provideNapkinString() { // return "Hello Napkin in Fragment!"; // } // } // // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/ui/MainActivity.java // public class MainActivity extends AppCompatActivity implements ComponentProvider<ActivityComponent> { // // @Inject // protected MainViewModel mainViewModel; // // private ActivityComponent activityComponent; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // activityComponent = Napkin.<AppComponent>provideAppComponent(this) // .with(new ActivityModule(this)); // // activityComponent.inject(this); // ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); // binding.setViewModel(mainViewModel); // } // // @Override // public ActivityComponent provideComponent() { // return activityComponent; // } // } // Path: app/src/main/java/com/github/aleksandermielczarek/napkinexample/component/ActivityComponent.java import com.github.aleksandermielczarek.napkin.scope.ActivityScope; import com.github.aleksandermielczarek.napkinexample.module.ActivityModule; import com.github.aleksandermielczarek.napkinexample.module.FragmentModule; import com.github.aleksandermielczarek.napkinexample.ui.MainActivity; import dagger.Subcomponent; package com.github.aleksandermielczarek.napkinexample.component; /** * Created by Aleksander Mielczarek on 13.05.2016. */ @ActivityScope @Subcomponent(modules = ActivityModule.class) public interface ActivityComponent { FragmentComponent with(FragmentModule fragmentModule);
void inject(MainActivity mainActivity);
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // }
import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService;
package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService; package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired
private ApplicationService appService;
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // }
import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService;
package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired private ApplicationService appService; /** * Set component error handler with the one from UI. * This is required because when an exception is thrown when calling Navigator#navigateTo it won't be handled by UI' error handler */ public void setErrorHandler(Layout page) { page.setErrorHandler(page.getUI().getErrorHandler()); } public void setLayoutStyle(AbstractOrderedLayout page) { // Center align layout page.setWidth("100%"); page.setMargin(new MarginInfo(false, true)); }
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService; package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired private ApplicationService appService; /** * Set component error handler with the one from UI. * This is required because when an exception is thrown when calling Navigator#navigateTo it won't be handled by UI' error handler */ public void setErrorHandler(Layout page) { page.setErrorHandler(page.getUI().getErrorHandler()); } public void setLayoutStyle(AbstractOrderedLayout page) { // Center align layout page.setWidth("100%"); page.setMargin(new MarginInfo(false, true)); }
public Application getApp(int appId) {
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // }
import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService;
package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired private ApplicationService appService; /** * Set component error handler with the one from UI. * This is required because when an exception is thrown when calling Navigator#navigateTo it won't be handled by UI' error handler */ public void setErrorHandler(Layout page) { page.setErrorHandler(page.getUI().getErrorHandler()); } public void setLayoutStyle(AbstractOrderedLayout page) { // Center align layout page.setWidth("100%"); page.setMargin(new MarginInfo(false, true)); } public Application getApp(int appId) { Optional<Application> app = appService.findById(appId); if(!app.isPresent()) {
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/ApplicationNotFoundException.java // public class ApplicationNotFoundException extends RuntimeException { // // public ApplicationNotFoundException(int appId) { // super(String.format("Application with id %s has not been found", appId)); // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/service/ApplicationService.java // @Service // public class ApplicationService { // // private static final Logger LOGGER = LoggerFactory.getLogger(LogsService.class); // // private List<Application> applications = Collections.emptyList(); // // public List<Application> findAll() { // LOGGER.debug("Get all applications"); // return this.applications; // } // // public Optional<Application> findById(int appId) { // LOGGER.debug("Get application with id {}", appId); // return this.applications.stream().filter(app -> app.getId() == appId).findFirst(); // } // // public void setApplications(List<Application> apps) { // LOGGER.debug("Adding {} applications", apps.size()); // this.applications = Collections.unmodifiableList(apps); // } // // public void setUp(Application app, boolean up) { // if(app.isUp() != up) { // LOGGER.info("Changing Application#up to {} for application with id {}", up, app.getId()); // app.setUp(up); // } // } // // public void setActuatorVersion(Application app, ActuatorVersion actuatorVersion) { // if(app.getActuatorVersion() == null) { // LOGGER.info("Changing Application#actuatorVersion to {} for application with id {}", actuatorVersion, app.getId()); // app.setActuatorVersion(actuatorVersion); // } // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/util/PageHelper.java import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Layout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.exception.ApplicationNotFoundException; import re.vianneyfaiv.persephone.service.ApplicationService; package re.vianneyfaiv.persephone.ui.util; @Component public class PageHelper { @Autowired private ApplicationService appService; /** * Set component error handler with the one from UI. * This is required because when an exception is thrown when calling Navigator#navigateTo it won't be handled by UI' error handler */ public void setErrorHandler(Layout page) { page.setErrorHandler(page.getUI().getErrorHandler()); } public void setLayoutStyle(AbstractOrderedLayout page) { // Center align layout page.setWidth("100%"); page.setMargin(new MarginInfo(false, true)); } public Application getApp(int appId) { Optional<Application> app = appService.findById(appId); if(!app.isPresent()) {
throw new ApplicationNotFoundException(appId);
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/component/grid/TraceGridRow.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/trace/Trace.java // public class Trace { // // private long timestamp; // private TraceInfo info; // // public long getTimestamp() { // return timestamp; // } // // public TraceInfo getInfo() { // return info; // } // // @Override // public String toString() { // return "Trace [timestamp=" + timestamp + ", info=" + info + "]"; // } // }
import java.time.Duration; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.trace.Trace;
package re.vianneyfaiv.persephone.ui.component.grid; public class TraceGridRow { private Date timestamp; private HttpMethod method; private String path; private Optional<Duration> timeTaken; private Optional<HttpStatus> responseHttp; private Map<String, List<String>> requestHeaders; private Map<String, List<String>> responseHeaders;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/trace/Trace.java // public class Trace { // // private long timestamp; // private TraceInfo info; // // public long getTimestamp() { // return timestamp; // } // // public TraceInfo getInfo() { // return info; // } // // @Override // public String toString() { // return "Trace [timestamp=" + timestamp + ", info=" + info + "]"; // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/component/grid/TraceGridRow.java import java.time.Duration; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.trace.Trace; package re.vianneyfaiv.persephone.ui.component.grid; public class TraceGridRow { private Date timestamp; private HttpMethod method; private String path; private Optional<Duration> timeTaken; private Optional<HttpStatus> responseHttp; private Map<String, List<String>> requestHeaders; private Map<String, List<String>> responseHeaders;
public TraceGridRow(Trace trace) {
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/config/RestErrorHandler.java
// Path: src/main/java/re/vianneyfaiv/persephone/exception/HttpRedirectErrorException.java // public class HttpRedirectErrorException extends HttpStatusCodeException { // // private static final long serialVersionUID = 6338405670035326036L; // // public HttpRedirectErrorException(HttpStatus statusCode) { // super(statusCode); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText) { // super(statusCode, statusText); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText, byte[] responseBody, Charset responseCharset) { // super(statusCode, statusText, responseBody, responseCharset); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) { // super(statusCode, statusText, responseHeaders, responseBody, responseCharset); // } // // }
import java.io.IOException; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import re.vianneyfaiv.persephone.exception.HttpRedirectErrorException;
package re.vianneyfaiv.persephone.config; /** * Handle HTTP 3xx as errors */ @Configuration public class RestErrorHandler extends DefaultResponseErrorHandler { @Override protected boolean hasError(HttpStatus statusCode) { return statusCode.series() == HttpStatus.Series.REDIRECTION || super.hasError(statusCode); } @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); // handle 3xx switch (statusCode.series()) { case REDIRECTION:
// Path: src/main/java/re/vianneyfaiv/persephone/exception/HttpRedirectErrorException.java // public class HttpRedirectErrorException extends HttpStatusCodeException { // // private static final long serialVersionUID = 6338405670035326036L; // // public HttpRedirectErrorException(HttpStatus statusCode) { // super(statusCode); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText) { // super(statusCode, statusText); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText, byte[] responseBody, Charset responseCharset) { // super(statusCode, statusText, responseBody, responseCharset); // } // // public HttpRedirectErrorException(HttpStatus statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody, Charset responseCharset) { // super(statusCode, statusText, responseHeaders, responseBody, responseCharset); // } // // } // Path: src/main/java/re/vianneyfaiv/persephone/config/RestErrorHandler.java import java.io.IOException; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import re.vianneyfaiv.persephone.exception.HttpRedirectErrorException; package re.vianneyfaiv.persephone.config; /** * Handle HTTP 3xx as errors */ @Configuration public class RestErrorHandler extends DefaultResponseErrorHandler { @Override protected boolean hasError(HttpStatus statusCode) { return statusCode.series() == HttpStatus.Series.REDIRECTION || super.hasError(statusCode); } @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); // handle 3xx switch (statusCode.series()) { case REDIRECTION:
throw new HttpRedirectErrorException(statusCode, response.getStatusText(),
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/env/ActuatorVersion.java // public enum ActuatorVersion { // // V1(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE), // V2("application/vnd.spring-boot.actuator.v2+json"); // // private static final Logger LOGGER = LoggerFactory.getLogger(ActuatorVersion.class); // // private String mediaType; // // private ActuatorVersion(String mediaType) { // this.mediaType = mediaType; // } // // public static ActuatorVersion parse(MediaType contentType) { // // String simpleType = contentType.getType() + "/" + contentType.getSubtype(); // // if(V1.mediaType.equals(simpleType)) { // return V1; // } // // if(V2.mediaType.equals(simpleType)) { // return V2; // } // // LOGGER.warn("Version not found in header {}, so we assume it's V1", contentType); // // // By default, consider it's Actuator from spring boot 1.x // return V1; // } // // }
import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.env.ActuatorVersion;
package re.vianneyfaiv.persephone.domain.app; public class Application { private int id; private String name; private String environment; private String url; private boolean up; // set when application is clicked private Endpoints endpoints; private AuthScheme authScheme; private String actuatorUsername; private String actuatorPassword;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/env/ActuatorVersion.java // public enum ActuatorVersion { // // V1(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE), // V2("application/vnd.spring-boot.actuator.v2+json"); // // private static final Logger LOGGER = LoggerFactory.getLogger(ActuatorVersion.class); // // private String mediaType; // // private ActuatorVersion(String mediaType) { // this.mediaType = mediaType; // } // // public static ActuatorVersion parse(MediaType contentType) { // // String simpleType = contentType.getType() + "/" + contentType.getSubtype(); // // if(V1.mediaType.equals(simpleType)) { // return V1; // } // // if(V2.mediaType.equals(simpleType)) { // return V2; // } // // LOGGER.warn("Version not found in header {}, so we assume it's V1", contentType); // // // By default, consider it's Actuator from spring boot 1.x // return V1; // } // // } // Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.env.ActuatorVersion; package re.vianneyfaiv.persephone.domain.app; public class Application { private int id; private String name; private String environment; private String url; private boolean up; // set when application is clicked private Endpoints endpoints; private AuthScheme authScheme; private String actuatorUsername; private String actuatorPassword;
private ActuatorVersion actuatorVersion; // set when application is clicked
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/component/PageHeader.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/ui/PersephoneViews.java // public class PersephoneViews { // /** // * {@link ApplicationsPage} // */ // public static final String APPLICATIONS = ""; // // /** // * {@link PropertiesPage} // */ // public static final String PROPERTIES = "properties"; // // /** // * {@link LogsPage} // */ // public static final String LOGS = "logs"; // // /** // * {@link EndpointsPage} // */ // public static final String ENDPOINTS = "endpoints"; // // /** // * {@link LoggersPage} // */ // public static final String LOGGERS = "loggers"; // // // /** // * {@link MetricsPage} // */ // public static final String METRICS = "metrics"; // // /** // * {@link TracePage} // */ // public static final String TRACE = "trace"; // }
import com.vaadin.icons.VaadinIcons; import com.vaadin.shared.ui.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.ui.PersephoneViews;
package re.vianneyfaiv.persephone.ui.component; /** * Page header based on current application. * * Contains a title and a button bar */ public class PageHeader extends VerticalLayout { /** * @param components components that will be added horizontally before the back button */ public PageHeader(Application app, String subtitle, Component... components) { this.addComponent(getTitle(app, subtitle)); this.addComponent(getButtons(components)); this.setMargin(false); } private HorizontalLayout getTitle(Application app, String subtitle) { Label title = new Label(String.format("<h2>%s (%s): %s</h2>", app.getName(), app.getEnvironment(), subtitle), ContentMode.HTML); return new HorizontalLayout(title); } private HorizontalLayout getButtons(Component... components) { Button backButton = new Button("Go Back", VaadinIcons.BACKSPACE_A); backButton.setId("back-btn");
// Path: src/main/java/re/vianneyfaiv/persephone/domain/app/Application.java // public class Application { // // private int id; // private String name; // private String environment; // private String url; // private boolean up; // set when application is clicked // private Endpoints endpoints; // private AuthScheme authScheme; // private String actuatorUsername; // private String actuatorPassword; // private ActuatorVersion actuatorVersion; // set when application is clicked // // /** // * Application without HTTP Auth // */ // public Application(int id, String name, String environment, String url) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.NONE; // } // // /** // * Application with HTTP Auth Basic enabled // */ // public Application(int id, String name, String environment, String url, String username, String password) { // this.id = id; // this.name = name; // this.environment = environment; // this.url = url; // this.endpoints = new Endpoints(url); // this.authScheme = AuthScheme.BASIC; // this.actuatorUsername = username; // this.actuatorPassword = password; // } // // public boolean isAuthValid() { // if(AuthScheme.BASIC == authScheme) { // return !StringUtils.isEmpty(actuatorUsername) && !StringUtils.isEmpty(actuatorPassword); // } // // return true; // } // // public int getId() { // return this.id; // } // // public String getName() { // return this.name; // } // // public String getEnvironment() { // return this.environment; // } // // public String getUrl() { // return this.url; // } // // public void setUp(boolean up) { // this.up = up; // } // // public boolean isUp() { // return this.up; // } // // public Endpoints endpoints() { // return this.endpoints; // } // // public AuthScheme getAuthScheme() { // return authScheme; // } // // public String getActuatorUsername() { // return actuatorUsername; // } // // public String getActuatorPassword() { // return actuatorPassword; // } // // public ActuatorVersion getActuatorVersion() { // return actuatorVersion; // } // // public void setActuatorVersion(ActuatorVersion actuatorVersion) { // this.actuatorVersion = actuatorVersion; // } // // @Override // public String toString() { // return "Application [id=" + id + ", name=" + name + ", environment=" + environment + ", url=" + url + ", up=" // + up + ", authScheme=" + authScheme + "]"; // } // } // // Path: src/main/java/re/vianneyfaiv/persephone/ui/PersephoneViews.java // public class PersephoneViews { // /** // * {@link ApplicationsPage} // */ // public static final String APPLICATIONS = ""; // // /** // * {@link PropertiesPage} // */ // public static final String PROPERTIES = "properties"; // // /** // * {@link LogsPage} // */ // public static final String LOGS = "logs"; // // /** // * {@link EndpointsPage} // */ // public static final String ENDPOINTS = "endpoints"; // // /** // * {@link LoggersPage} // */ // public static final String LOGGERS = "loggers"; // // // /** // * {@link MetricsPage} // */ // public static final String METRICS = "metrics"; // // /** // * {@link TracePage} // */ // public static final String TRACE = "trace"; // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/component/PageHeader.java import com.vaadin.icons.VaadinIcons; import com.vaadin.shared.ui.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.app.Application; import re.vianneyfaiv.persephone.ui.PersephoneViews; package re.vianneyfaiv.persephone.ui.component; /** * Page header based on current application. * * Contains a title and a button bar */ public class PageHeader extends VerticalLayout { /** * @param components components that will be added horizontally before the back button */ public PageHeader(Application app, String subtitle, Component... components) { this.addComponent(getTitle(app, subtitle)); this.addComponent(getButtons(components)); this.setMargin(false); } private HorizontalLayout getTitle(Application app, String subtitle) { Label title = new Label(String.format("<h2>%s (%s): %s</h2>", app.getName(), app.getEnvironment(), subtitle), ContentMode.HTML); return new HorizontalLayout(title); } private HorizontalLayout getButtons(Component... components) { Button backButton = new Button("Go Back", VaadinIcons.BACKSPACE_A); backButton.setId("back-btn");
backButton.addClickListener(e -> getUI().getNavigator().navigateTo(PersephoneViews.APPLICATIONS));
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/domain/env/Environment.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/env/v2/EnvironmentResponse.java // public class EnvironmentResponse { // // private List<String> activeProfiles; // private List<PropertySource> propertySources; // // public List<String> getActiveProfiles() { // return activeProfiles; // } // // public List<PropertySource> getPropertySources() { // return propertySources; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.env.v2.EnvironmentResponse;
package re.vianneyfaiv.persephone.domain.env; /** * Mapper for /env endpoint */ public class Environment { private List<PropertyItem> properties; private Map<String, List<String>> propertiesMap;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/env/v2/EnvironmentResponse.java // public class EnvironmentResponse { // // private List<String> activeProfiles; // private List<PropertySource> propertySources; // // public List<String> getActiveProfiles() { // return activeProfiles; // } // // public List<PropertySource> getPropertySources() { // return propertySources; // } // } // Path: src/main/java/re/vianneyfaiv/persephone/domain/env/Environment.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.util.StringUtils; import re.vianneyfaiv.persephone.domain.env.v2.EnvironmentResponse; package re.vianneyfaiv.persephone.domain.env; /** * Mapper for /env endpoint */ public class Environment { private List<PropertyItem> properties; private Map<String, List<String>> propertiesMap;
public Environment(EnvironmentResponse env, ActuatorVersion actuatorVersion) {
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/component/grid/LoggerGridRow.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/logger/Logger.java // public class Logger { // // private String configuredLevel; // private String effectiveLevel; // // public Logger() { // } // // public Logger(String configuredLevel, String effectiveLevel) { // this.configuredLevel = configuredLevel; // this.effectiveLevel = effectiveLevel; // } // // public String getConfiguredLevel() { // return configuredLevel; // } // // public String getEffectiveLevel() { // return effectiveLevel; // } // // @Override // public String toString() { // return "Logger [configuredLevel=" + configuredLevel + ", effectiveLevel=" + effectiveLevel + "]"; // } // }
import java.util.Map; import re.vianneyfaiv.persephone.domain.logger.Logger;
package re.vianneyfaiv.persephone.ui.component.grid; public class LoggerGridRow { private String name; private String level;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/logger/Logger.java // public class Logger { // // private String configuredLevel; // private String effectiveLevel; // // public Logger() { // } // // public Logger(String configuredLevel, String effectiveLevel) { // this.configuredLevel = configuredLevel; // this.effectiveLevel = effectiveLevel; // } // // public String getConfiguredLevel() { // return configuredLevel; // } // // public String getEffectiveLevel() { // return effectiveLevel; // } // // @Override // public String toString() { // return "Logger [configuredLevel=" + configuredLevel + ", effectiveLevel=" + effectiveLevel + "]"; // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/component/grid/LoggerGridRow.java import java.util.Map; import re.vianneyfaiv.persephone.domain.logger.Logger; package re.vianneyfaiv.persephone.ui.component.grid; public class LoggerGridRow { private String name; private String level;
public LoggerGridRow(Map.Entry<String, Logger> logger) {
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/component/grid/MetricsCacheGridRow.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/metrics/MetricsCache.java // public class MetricsCache { // // private String name; // private long size; // private double missRatio; // private double hitRatio; // // public MetricsCache(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public long getSize() { // return size; // } // // public double getMissRatio() { // return missRatio; // } // // public double getHitRatio() { // return hitRatio; // } // // public void setSize(long size) { // this.size = size; // } // // public void setMissRatio(double missRatio) { // this.missRatio = missRatio; // } // // public void setHitRatio(double hitRatio) { // this.hitRatio = hitRatio; // } // // @Override // public String toString() { // return "MetricsCache [name=" + name + ", size=" + size + ", missRatio=" + missRatio + ", hitRatio=" + hitRatio // + "]"; // } // }
import java.text.DecimalFormat; import re.vianneyfaiv.persephone.domain.metrics.MetricsCache;
package re.vianneyfaiv.persephone.ui.component.grid; public class MetricsCacheGridRow { private String name; private long size; private String hit; private String miss;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/metrics/MetricsCache.java // public class MetricsCache { // // private String name; // private long size; // private double missRatio; // private double hitRatio; // // public MetricsCache(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public long getSize() { // return size; // } // // public double getMissRatio() { // return missRatio; // } // // public double getHitRatio() { // return hitRatio; // } // // public void setSize(long size) { // this.size = size; // } // // public void setMissRatio(double missRatio) { // this.missRatio = missRatio; // } // // public void setHitRatio(double hitRatio) { // this.hitRatio = hitRatio; // } // // @Override // public String toString() { // return "MetricsCache [name=" + name + ", size=" + size + ", missRatio=" + missRatio + ", hitRatio=" + hitRatio // + "]"; // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/component/grid/MetricsCacheGridRow.java import java.text.DecimalFormat; import re.vianneyfaiv.persephone.domain.metrics.MetricsCache; package re.vianneyfaiv.persephone.ui.component.grid; public class MetricsCacheGridRow { private String name; private long size; private String hit; private String miss;
public MetricsCacheGridRow(MetricsCache metric) {
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/PersephoneUI.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/session/UserData.java // public class UserData { // // /** // * GET /logs page: current range retrieved by user // */ // private LogsRange currentRange; // // /** // * GET /logs page: auto scroll to the bottom (enabled by default) // */ // private boolean tailAutoScrollEnabled = true; // // public LogsRange getCurrentRange() { // return currentRange; // } // // public void setCurrentRange(LogsRange currentRange) { // this.currentRange = currentRange; // } // // public void toggleTailAutoScroll() { // if(tailAutoScrollEnabled) { // tailAutoScrollEnabled = false; // } else { // tailAutoScrollEnabled = true; // } // } // // public boolean isTailAutoScrollEnabled() { // return tailAutoScrollEnabled; // } // // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/UIErrorHandler.java // public class UIErrorHandler implements ErrorHandler { // // private static final long serialVersionUID = 7441835079387513134L; // // private static final Logger LOGGER = LoggerFactory.getLogger(UIErrorHandler.class); // // @Override // public void error(com.vaadin.server.ErrorEvent event) { // // // Loop through the exception stack // for (Throwable t = event.getThrowable(); t != null; t = t.getCause()) { // // // Try to get a persephone exception // boolean exceptionHandled = handlePersephoneExceptions(t); // // // If no persephone exception has been found => try from Exception#getCause // if(!exceptionHandled) { // exceptionHandled = handlePersephoneExceptions(t.getCause()); // } // // if(exceptionHandled) { // return; // } else if(t instanceof RuntimeException) { // displayErrorNotif("Unhandled runtime exception.", t); // return; // } else { // LOGGER.error("Persephone Error Handler: {} ; Message: {}", t.getClass(), t.getMessage()); // } // } // } // // private boolean handlePersephoneExceptions(Throwable t) { // boolean handled = false; // // // Technical runtime exceptions // if(t instanceof ApplicationRuntimeException) { // ApplicationRuntimeException e = (ApplicationRuntimeException) t; // displayErrorNotif("Unable to reach " + e.getApplication().getUrl(), e); // handled = true; // } // else if(t instanceof ApplicationNotFoundException) { // ApplicationNotFoundException e = (ApplicationNotFoundException) t; // displayErrorNotif(e.getMessage(), e); // handled = true; // } // // Expected exceptions (not handled) // else if(t instanceof ApplicationException) { // ApplicationException e = (ApplicationException) t; // displayErrorNotif("Unhandled error. Application " + e.getApplication().getName(), e); // handled = true; // } // // return handled; // } // // private void displayErrorNotif(String msg, Throwable t) { // LOGGER.error(String.format("Error handler: %s", msg), t); // // if(!StringUtils.isEmpty(t.getMessage())) { // new Notification( // msg, // t.getMessage(), // Notification.Type.ERROR_MESSAGE, // false) // .show(Page.getCurrent()); // } // } // }
import org.springframework.beans.factory.annotation.Value; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewDisplay; import com.vaadin.server.CustomizedSystemMessages; import com.vaadin.server.ExternalResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.BorderStyle; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.annotation.SpringViewDisplay; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.session.UserData; import re.vianneyfaiv.persephone.exception.UIErrorHandler;
package re.vianneyfaiv.persephone.ui; /** * Vaadin UI initializer */ @Title("Persephone") @Theme("persephone") @SpringUI @SpringViewDisplay public class PersephoneUI extends UI implements ViewDisplay { private Panel springViewDisplay; @Value("${info.persephone.version}") private String persephoneVersion;
// Path: src/main/java/re/vianneyfaiv/persephone/domain/session/UserData.java // public class UserData { // // /** // * GET /logs page: current range retrieved by user // */ // private LogsRange currentRange; // // /** // * GET /logs page: auto scroll to the bottom (enabled by default) // */ // private boolean tailAutoScrollEnabled = true; // // public LogsRange getCurrentRange() { // return currentRange; // } // // public void setCurrentRange(LogsRange currentRange) { // this.currentRange = currentRange; // } // // public void toggleTailAutoScroll() { // if(tailAutoScrollEnabled) { // tailAutoScrollEnabled = false; // } else { // tailAutoScrollEnabled = true; // } // } // // public boolean isTailAutoScrollEnabled() { // return tailAutoScrollEnabled; // } // // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/UIErrorHandler.java // public class UIErrorHandler implements ErrorHandler { // // private static final long serialVersionUID = 7441835079387513134L; // // private static final Logger LOGGER = LoggerFactory.getLogger(UIErrorHandler.class); // // @Override // public void error(com.vaadin.server.ErrorEvent event) { // // // Loop through the exception stack // for (Throwable t = event.getThrowable(); t != null; t = t.getCause()) { // // // Try to get a persephone exception // boolean exceptionHandled = handlePersephoneExceptions(t); // // // If no persephone exception has been found => try from Exception#getCause // if(!exceptionHandled) { // exceptionHandled = handlePersephoneExceptions(t.getCause()); // } // // if(exceptionHandled) { // return; // } else if(t instanceof RuntimeException) { // displayErrorNotif("Unhandled runtime exception.", t); // return; // } else { // LOGGER.error("Persephone Error Handler: {} ; Message: {}", t.getClass(), t.getMessage()); // } // } // } // // private boolean handlePersephoneExceptions(Throwable t) { // boolean handled = false; // // // Technical runtime exceptions // if(t instanceof ApplicationRuntimeException) { // ApplicationRuntimeException e = (ApplicationRuntimeException) t; // displayErrorNotif("Unable to reach " + e.getApplication().getUrl(), e); // handled = true; // } // else if(t instanceof ApplicationNotFoundException) { // ApplicationNotFoundException e = (ApplicationNotFoundException) t; // displayErrorNotif(e.getMessage(), e); // handled = true; // } // // Expected exceptions (not handled) // else if(t instanceof ApplicationException) { // ApplicationException e = (ApplicationException) t; // displayErrorNotif("Unhandled error. Application " + e.getApplication().getName(), e); // handled = true; // } // // return handled; // } // // private void displayErrorNotif(String msg, Throwable t) { // LOGGER.error(String.format("Error handler: %s", msg), t); // // if(!StringUtils.isEmpty(t.getMessage())) { // new Notification( // msg, // t.getMessage(), // Notification.Type.ERROR_MESSAGE, // false) // .show(Page.getCurrent()); // } // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/PersephoneUI.java import org.springframework.beans.factory.annotation.Value; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewDisplay; import com.vaadin.server.CustomizedSystemMessages; import com.vaadin.server.ExternalResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.BorderStyle; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.annotation.SpringViewDisplay; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.session.UserData; import re.vianneyfaiv.persephone.exception.UIErrorHandler; package re.vianneyfaiv.persephone.ui; /** * Vaadin UI initializer */ @Title("Persephone") @Theme("persephone") @SpringUI @SpringViewDisplay public class PersephoneUI extends UI implements ViewDisplay { private Panel springViewDisplay; @Value("${info.persephone.version}") private String persephoneVersion;
private UserData userData = new UserData();
vianneyfaivre/Persephone
src/main/java/re/vianneyfaiv/persephone/ui/PersephoneUI.java
// Path: src/main/java/re/vianneyfaiv/persephone/domain/session/UserData.java // public class UserData { // // /** // * GET /logs page: current range retrieved by user // */ // private LogsRange currentRange; // // /** // * GET /logs page: auto scroll to the bottom (enabled by default) // */ // private boolean tailAutoScrollEnabled = true; // // public LogsRange getCurrentRange() { // return currentRange; // } // // public void setCurrentRange(LogsRange currentRange) { // this.currentRange = currentRange; // } // // public void toggleTailAutoScroll() { // if(tailAutoScrollEnabled) { // tailAutoScrollEnabled = false; // } else { // tailAutoScrollEnabled = true; // } // } // // public boolean isTailAutoScrollEnabled() { // return tailAutoScrollEnabled; // } // // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/UIErrorHandler.java // public class UIErrorHandler implements ErrorHandler { // // private static final long serialVersionUID = 7441835079387513134L; // // private static final Logger LOGGER = LoggerFactory.getLogger(UIErrorHandler.class); // // @Override // public void error(com.vaadin.server.ErrorEvent event) { // // // Loop through the exception stack // for (Throwable t = event.getThrowable(); t != null; t = t.getCause()) { // // // Try to get a persephone exception // boolean exceptionHandled = handlePersephoneExceptions(t); // // // If no persephone exception has been found => try from Exception#getCause // if(!exceptionHandled) { // exceptionHandled = handlePersephoneExceptions(t.getCause()); // } // // if(exceptionHandled) { // return; // } else if(t instanceof RuntimeException) { // displayErrorNotif("Unhandled runtime exception.", t); // return; // } else { // LOGGER.error("Persephone Error Handler: {} ; Message: {}", t.getClass(), t.getMessage()); // } // } // } // // private boolean handlePersephoneExceptions(Throwable t) { // boolean handled = false; // // // Technical runtime exceptions // if(t instanceof ApplicationRuntimeException) { // ApplicationRuntimeException e = (ApplicationRuntimeException) t; // displayErrorNotif("Unable to reach " + e.getApplication().getUrl(), e); // handled = true; // } // else if(t instanceof ApplicationNotFoundException) { // ApplicationNotFoundException e = (ApplicationNotFoundException) t; // displayErrorNotif(e.getMessage(), e); // handled = true; // } // // Expected exceptions (not handled) // else if(t instanceof ApplicationException) { // ApplicationException e = (ApplicationException) t; // displayErrorNotif("Unhandled error. Application " + e.getApplication().getName(), e); // handled = true; // } // // return handled; // } // // private void displayErrorNotif(String msg, Throwable t) { // LOGGER.error(String.format("Error handler: %s", msg), t); // // if(!StringUtils.isEmpty(t.getMessage())) { // new Notification( // msg, // t.getMessage(), // Notification.Type.ERROR_MESSAGE, // false) // .show(Page.getCurrent()); // } // } // }
import org.springframework.beans.factory.annotation.Value; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewDisplay; import com.vaadin.server.CustomizedSystemMessages; import com.vaadin.server.ExternalResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.BorderStyle; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.annotation.SpringViewDisplay; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.session.UserData; import re.vianneyfaiv.persephone.exception.UIErrorHandler;
package re.vianneyfaiv.persephone.ui; /** * Vaadin UI initializer */ @Title("Persephone") @Theme("persephone") @SpringUI @SpringViewDisplay public class PersephoneUI extends UI implements ViewDisplay { private Panel springViewDisplay; @Value("${info.persephone.version}") private String persephoneVersion; private UserData userData = new UserData(); @Override protected void init(VaadinRequest request) { // Root layout final VerticalLayout root = new VerticalLayout(); root.setSizeFull(); root.setSpacing(false); root.setMargin(false); setContent(root); // Main panel springViewDisplay = new Panel(); springViewDisplay.setSizeFull(); root.addComponent(springViewDisplay); root.setExpandRatio(springViewDisplay, 1); // Footer Layout footer = getFooter(); root.addComponent(footer); root.setExpandRatio(footer, 0); // Error handler
// Path: src/main/java/re/vianneyfaiv/persephone/domain/session/UserData.java // public class UserData { // // /** // * GET /logs page: current range retrieved by user // */ // private LogsRange currentRange; // // /** // * GET /logs page: auto scroll to the bottom (enabled by default) // */ // private boolean tailAutoScrollEnabled = true; // // public LogsRange getCurrentRange() { // return currentRange; // } // // public void setCurrentRange(LogsRange currentRange) { // this.currentRange = currentRange; // } // // public void toggleTailAutoScroll() { // if(tailAutoScrollEnabled) { // tailAutoScrollEnabled = false; // } else { // tailAutoScrollEnabled = true; // } // } // // public boolean isTailAutoScrollEnabled() { // return tailAutoScrollEnabled; // } // // } // // Path: src/main/java/re/vianneyfaiv/persephone/exception/UIErrorHandler.java // public class UIErrorHandler implements ErrorHandler { // // private static final long serialVersionUID = 7441835079387513134L; // // private static final Logger LOGGER = LoggerFactory.getLogger(UIErrorHandler.class); // // @Override // public void error(com.vaadin.server.ErrorEvent event) { // // // Loop through the exception stack // for (Throwable t = event.getThrowable(); t != null; t = t.getCause()) { // // // Try to get a persephone exception // boolean exceptionHandled = handlePersephoneExceptions(t); // // // If no persephone exception has been found => try from Exception#getCause // if(!exceptionHandled) { // exceptionHandled = handlePersephoneExceptions(t.getCause()); // } // // if(exceptionHandled) { // return; // } else if(t instanceof RuntimeException) { // displayErrorNotif("Unhandled runtime exception.", t); // return; // } else { // LOGGER.error("Persephone Error Handler: {} ; Message: {}", t.getClass(), t.getMessage()); // } // } // } // // private boolean handlePersephoneExceptions(Throwable t) { // boolean handled = false; // // // Technical runtime exceptions // if(t instanceof ApplicationRuntimeException) { // ApplicationRuntimeException e = (ApplicationRuntimeException) t; // displayErrorNotif("Unable to reach " + e.getApplication().getUrl(), e); // handled = true; // } // else if(t instanceof ApplicationNotFoundException) { // ApplicationNotFoundException e = (ApplicationNotFoundException) t; // displayErrorNotif(e.getMessage(), e); // handled = true; // } // // Expected exceptions (not handled) // else if(t instanceof ApplicationException) { // ApplicationException e = (ApplicationException) t; // displayErrorNotif("Unhandled error. Application " + e.getApplication().getName(), e); // handled = true; // } // // return handled; // } // // private void displayErrorNotif(String msg, Throwable t) { // LOGGER.error(String.format("Error handler: %s", msg), t); // // if(!StringUtils.isEmpty(t.getMessage())) { // new Notification( // msg, // t.getMessage(), // Notification.Type.ERROR_MESSAGE, // false) // .show(Page.getCurrent()); // } // } // } // Path: src/main/java/re/vianneyfaiv/persephone/ui/PersephoneUI.java import org.springframework.beans.factory.annotation.Value; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewDisplay; import com.vaadin.server.CustomizedSystemMessages; import com.vaadin.server.ExternalResource; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.BorderStyle; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.annotation.SpringViewDisplay; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.Panel; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import re.vianneyfaiv.persephone.domain.session.UserData; import re.vianneyfaiv.persephone.exception.UIErrorHandler; package re.vianneyfaiv.persephone.ui; /** * Vaadin UI initializer */ @Title("Persephone") @Theme("persephone") @SpringUI @SpringViewDisplay public class PersephoneUI extends UI implements ViewDisplay { private Panel springViewDisplay; @Value("${info.persephone.version}") private String persephoneVersion; private UserData userData = new UserData(); @Override protected void init(VaadinRequest request) { // Root layout final VerticalLayout root = new VerticalLayout(); root.setSizeFull(); root.setSpacing(false); root.setMargin(false); setContent(root); // Main panel springViewDisplay = new Panel(); springViewDisplay.setSizeFull(); root.addComponent(springViewDisplay); root.setExpandRatio(springViewDisplay, 1); // Footer Layout footer = getFooter(); root.addComponent(footer); root.setExpandRatio(footer, 0); // Error handler
UI.getCurrent().setErrorHandler(new UIErrorHandler());
thevash/vash
src/vash/operation/ColorNode.java
// Path: src/vash/ImageParameters.java // public class ImageParameters { // final private int w; // final private int h; // final private float[] X; // final private float[] Y; // private final LinkedList<Plane> cache; // private long _puts = 0; // private long _gets = 0; // private final static long MAX_CACHE_SIZE = 64 * 1024 * 1024; // private final static boolean DEBUG = false; // // /** // * Initialize a new set of image parameters for the given width and height. // */ // public ImageParameters(int w, int h) { // this.w = w; // this.h = h; // this.cache = new LinkedList<Plane>(); // this.X = new float[w]; // this.Y = new float[h]; // // int i, j; // float gX, gY; // float delta_x = 2.0f / w; // float delta_y = 2.0f / h; // for(j = 0, gY = 1.0f - (delta_y / 2.0f); j < h; j++, gY -= delta_y) // Y[j] = gY; // for(i = 0, gX = -1.0f + (delta_x / 2.0f); i < w; i++, gX += delta_x) // X[i] = gX; // } // // public int getW() { // return w; // } // // public int getH() { // return h; // } // // // /** // * Returns an array of width length filled such that each index offset is // * the logical X value for that index. We use this as a faster way to map // * [0,width) offsets into the [-1.0, 1.0] logical range used by our // * computations. // */ // public float[] getXValues() { // return X; // } // // // /** // * Returns an array of height length filled such that each index offset is // * the logical Y value for that index. We use this as a faster way to map // * [0,height) offsets into the [1.0, -1.0] logical range used by our // * computations. // */ // public float[] getYValues() { // return Y; // } // // // /** // * Returns a new, or cached, plane of values. The plane values will not be // * initialized to any specific value. // */ // public Plane getPlane() { // _gets += 1; // if(DEBUG) { // long tmp = ((_gets - _puts) + cache.size()) * (w * h * 4); // System.out.format("GetPlane: %d gets, %d puts, %d out, %d cached: %d%n", // _gets, _puts, _gets - _puts, cache.size(), tmp); // } // if(cache.size() > 0) { // return cache.removeFirst(); // } // return new Plane(this.w, this.h); // } // // /** // * Give back a plane taken with getPlane. This allows us to re-use planes, // * rather than re-allocating new, massive arrays constantly. // */ // public void putPlane(Plane p) { // _puts += 1; // long outstanding = ((_gets - _puts) + cache.size()) * (w * h * 4); // if(outstanding < MAX_CACHE_SIZE) { // cache.addFirst(p); // } // } // // /** // * Returns a new plane of values who's coordinates are mirrored around // * y=x. This is useful in some nodes that use slope, in order to avoid // * singularities around vertical lines. // * @return a one-off plane; must be returned with putYXPlane // */ // public Plane getYXPlane() { // return new Plane(this.h, this.w); // } // // /** // * Give back a plane taken with getYXPlane. // * @param p the plane allocated with getYXPlane // */ // public void putYXPlane(Plane p) { // } // }
import vash.ImageParameters;
/* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash.operation; /** * A top-level nodes in the computation tree. Where most nodes deal * exclusively with Planes of data, the actual result of a computation is an * image. Thus, the toplevel node in a tree must be a ColorNode. This class * extends OperationNode with an extra "compute" method that returns a byte[], * instead of a Plane. */ abstract public class ColorNode extends OperationNode { protected ColorNode() {super(0, 3);}
// Path: src/vash/ImageParameters.java // public class ImageParameters { // final private int w; // final private int h; // final private float[] X; // final private float[] Y; // private final LinkedList<Plane> cache; // private long _puts = 0; // private long _gets = 0; // private final static long MAX_CACHE_SIZE = 64 * 1024 * 1024; // private final static boolean DEBUG = false; // // /** // * Initialize a new set of image parameters for the given width and height. // */ // public ImageParameters(int w, int h) { // this.w = w; // this.h = h; // this.cache = new LinkedList<Plane>(); // this.X = new float[w]; // this.Y = new float[h]; // // int i, j; // float gX, gY; // float delta_x = 2.0f / w; // float delta_y = 2.0f / h; // for(j = 0, gY = 1.0f - (delta_y / 2.0f); j < h; j++, gY -= delta_y) // Y[j] = gY; // for(i = 0, gX = -1.0f + (delta_x / 2.0f); i < w; i++, gX += delta_x) // X[i] = gX; // } // // public int getW() { // return w; // } // // public int getH() { // return h; // } // // // /** // * Returns an array of width length filled such that each index offset is // * the logical X value for that index. We use this as a faster way to map // * [0,width) offsets into the [-1.0, 1.0] logical range used by our // * computations. // */ // public float[] getXValues() { // return X; // } // // // /** // * Returns an array of height length filled such that each index offset is // * the logical Y value for that index. We use this as a faster way to map // * [0,height) offsets into the [1.0, -1.0] logical range used by our // * computations. // */ // public float[] getYValues() { // return Y; // } // // // /** // * Returns a new, or cached, plane of values. The plane values will not be // * initialized to any specific value. // */ // public Plane getPlane() { // _gets += 1; // if(DEBUG) { // long tmp = ((_gets - _puts) + cache.size()) * (w * h * 4); // System.out.format("GetPlane: %d gets, %d puts, %d out, %d cached: %d%n", // _gets, _puts, _gets - _puts, cache.size(), tmp); // } // if(cache.size() > 0) { // return cache.removeFirst(); // } // return new Plane(this.w, this.h); // } // // /** // * Give back a plane taken with getPlane. This allows us to re-use planes, // * rather than re-allocating new, massive arrays constantly. // */ // public void putPlane(Plane p) { // _puts += 1; // long outstanding = ((_gets - _puts) + cache.size()) * (w * h * 4); // if(outstanding < MAX_CACHE_SIZE) { // cache.addFirst(p); // } // } // // /** // * Returns a new plane of values who's coordinates are mirrored around // * y=x. This is useful in some nodes that use slope, in order to avoid // * singularities around vertical lines. // * @return a one-off plane; must be returned with putYXPlane // */ // public Plane getYXPlane() { // return new Plane(this.h, this.w); // } // // /** // * Give back a plane taken with getYXPlane. // * @param p the plane allocated with getYXPlane // */ // public void putYXPlane(Plane p) { // } // } // Path: src/vash/operation/ColorNode.java import vash.ImageParameters; /* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash.operation; /** * A top-level nodes in the computation tree. Where most nodes deal * exclusively with Planes of data, the actual result of a computation is an * image. Thus, the toplevel node in a tree must be a ColorNode. This class * extends OperationNode with an extra "compute" method that returns a byte[], * instead of a Plane. */ abstract public class ColorNode extends OperationNode { protected ColorNode() {super(0, 3);}
abstract public byte[] compute(ImageParameters ip, boolean this_method_is_different);
thevash/vash
src/vash/operation/OperationNode.java
// Path: src/vash/ImageParameters.java // public class ImageParameters { // final private int w; // final private int h; // final private float[] X; // final private float[] Y; // private final LinkedList<Plane> cache; // private long _puts = 0; // private long _gets = 0; // private final static long MAX_CACHE_SIZE = 64 * 1024 * 1024; // private final static boolean DEBUG = false; // // /** // * Initialize a new set of image parameters for the given width and height. // */ // public ImageParameters(int w, int h) { // this.w = w; // this.h = h; // this.cache = new LinkedList<Plane>(); // this.X = new float[w]; // this.Y = new float[h]; // // int i, j; // float gX, gY; // float delta_x = 2.0f / w; // float delta_y = 2.0f / h; // for(j = 0, gY = 1.0f - (delta_y / 2.0f); j < h; j++, gY -= delta_y) // Y[j] = gY; // for(i = 0, gX = -1.0f + (delta_x / 2.0f); i < w; i++, gX += delta_x) // X[i] = gX; // } // // public int getW() { // return w; // } // // public int getH() { // return h; // } // // // /** // * Returns an array of width length filled such that each index offset is // * the logical X value for that index. We use this as a faster way to map // * [0,width) offsets into the [-1.0, 1.0] logical range used by our // * computations. // */ // public float[] getXValues() { // return X; // } // // // /** // * Returns an array of height length filled such that each index offset is // * the logical Y value for that index. We use this as a faster way to map // * [0,height) offsets into the [1.0, -1.0] logical range used by our // * computations. // */ // public float[] getYValues() { // return Y; // } // // // /** // * Returns a new, or cached, plane of values. The plane values will not be // * initialized to any specific value. // */ // public Plane getPlane() { // _gets += 1; // if(DEBUG) { // long tmp = ((_gets - _puts) + cache.size()) * (w * h * 4); // System.out.format("GetPlane: %d gets, %d puts, %d out, %d cached: %d%n", // _gets, _puts, _gets - _puts, cache.size(), tmp); // } // if(cache.size() > 0) { // return cache.removeFirst(); // } // return new Plane(this.w, this.h); // } // // /** // * Give back a plane taken with getPlane. This allows us to re-use planes, // * rather than re-allocating new, massive arrays constantly. // */ // public void putPlane(Plane p) { // _puts += 1; // long outstanding = ((_gets - _puts) + cache.size()) * (w * h * 4); // if(outstanding < MAX_CACHE_SIZE) { // cache.addFirst(p); // } // } // // /** // * Returns a new plane of values who's coordinates are mirrored around // * y=x. This is useful in some nodes that use slope, in order to avoid // * singularities around vertical lines. // * @return a one-off plane; must be returned with putYXPlane // */ // public Plane getYXPlane() { // return new Plane(this.h, this.w); // } // // /** // * Give back a plane taken with getYXPlane. // * @param p the plane allocated with getYXPlane // */ // public void putYXPlane(Plane p) { // } // }
import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import vash.ImageParameters; import vash.Plane; import vash.value.Value;
* A utility function used by many nodes when computing values. */ protected static float clampf(float in, float lower, float upper) { return Math.min(Math.max(in, lower), upper); } /** * A utility function used by many nodes when computing values. * @param x0 * @param y0 * @param x1 * @param y1 * @return */ protected static float distance(float x0, float y0, float x1, float y1) { float xp = x1 - x0; float yp = y1 - y0; return (float)Math.sqrt(xp * xp + yp * yp); } /** * Create and return a completely independent copy of this node. */ @Override abstract public OperationNode clone(); /** * The main computation routine. * @param ip */
// Path: src/vash/ImageParameters.java // public class ImageParameters { // final private int w; // final private int h; // final private float[] X; // final private float[] Y; // private final LinkedList<Plane> cache; // private long _puts = 0; // private long _gets = 0; // private final static long MAX_CACHE_SIZE = 64 * 1024 * 1024; // private final static boolean DEBUG = false; // // /** // * Initialize a new set of image parameters for the given width and height. // */ // public ImageParameters(int w, int h) { // this.w = w; // this.h = h; // this.cache = new LinkedList<Plane>(); // this.X = new float[w]; // this.Y = new float[h]; // // int i, j; // float gX, gY; // float delta_x = 2.0f / w; // float delta_y = 2.0f / h; // for(j = 0, gY = 1.0f - (delta_y / 2.0f); j < h; j++, gY -= delta_y) // Y[j] = gY; // for(i = 0, gX = -1.0f + (delta_x / 2.0f); i < w; i++, gX += delta_x) // X[i] = gX; // } // // public int getW() { // return w; // } // // public int getH() { // return h; // } // // // /** // * Returns an array of width length filled such that each index offset is // * the logical X value for that index. We use this as a faster way to map // * [0,width) offsets into the [-1.0, 1.0] logical range used by our // * computations. // */ // public float[] getXValues() { // return X; // } // // // /** // * Returns an array of height length filled such that each index offset is // * the logical Y value for that index. We use this as a faster way to map // * [0,height) offsets into the [1.0, -1.0] logical range used by our // * computations. // */ // public float[] getYValues() { // return Y; // } // // // /** // * Returns a new, or cached, plane of values. The plane values will not be // * initialized to any specific value. // */ // public Plane getPlane() { // _gets += 1; // if(DEBUG) { // long tmp = ((_gets - _puts) + cache.size()) * (w * h * 4); // System.out.format("GetPlane: %d gets, %d puts, %d out, %d cached: %d%n", // _gets, _puts, _gets - _puts, cache.size(), tmp); // } // if(cache.size() > 0) { // return cache.removeFirst(); // } // return new Plane(this.w, this.h); // } // // /** // * Give back a plane taken with getPlane. This allows us to re-use planes, // * rather than re-allocating new, massive arrays constantly. // */ // public void putPlane(Plane p) { // _puts += 1; // long outstanding = ((_gets - _puts) + cache.size()) * (w * h * 4); // if(outstanding < MAX_CACHE_SIZE) { // cache.addFirst(p); // } // } // // /** // * Returns a new plane of values who's coordinates are mirrored around // * y=x. This is useful in some nodes that use slope, in order to avoid // * singularities around vertical lines. // * @return a one-off plane; must be returned with putYXPlane // */ // public Plane getYXPlane() { // return new Plane(this.h, this.w); // } // // /** // * Give back a plane taken with getYXPlane. // * @param p the plane allocated with getYXPlane // */ // public void putYXPlane(Plane p) { // } // } // Path: src/vash/operation/OperationNode.java import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import vash.ImageParameters; import vash.Plane; import vash.value.Value; * A utility function used by many nodes when computing values. */ protected static float clampf(float in, float lower, float upper) { return Math.min(Math.max(in, lower), upper); } /** * A utility function used by many nodes when computing values. * @param x0 * @param y0 * @param x1 * @param y1 * @return */ protected static float distance(float x0, float y0, float x1, float y1) { float xp = x1 - x0; float yp = y1 - y0; return (float)Math.sqrt(xp * xp + yp * yp); } /** * Create and return a completely independent copy of this node. */ @Override abstract public OperationNode clone(); /** * The main computation routine. * @param ip */
abstract public Plane compute(ImageParameters ip);
thevash/vash
src/vash/TreeParameters.java
// Path: src/vash/operation/OpParams.java // public class OpParams { // public final double ratio; // public final double channels; // // /** // * Instantiate a new operation parameters with a default channels count of 3. // * @param ratio // */ // public OpParams(double ratio) { // this.ratio = ratio; // this.channels = 3.0; // } // // /** // * Instantiate a new operation parameters. // * @param ratio // * @param channels // */ // public OpParams(double ratio, double channels) { // this.ratio = ratio; // this.channels = channels; // } // } // // Path: src/vash/operation/Operation.java // public enum Operation { // // colors // RGB, // // arithmetic // ABSOLUTE, // ADD, // DIVIDE, // EXPONENTIATE, // INVERT, // MODULUS, // MULTIPLY, // // trig // SINC, // SINE, // SPIRAL, // SQUIRCLE, // // LEAF // CONST, // ELLIPSE, // FLOWER, // GRADIENT_LINEAR, // GRADIENT_RADIAL, // POLAR_THETA, // ; // }
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import vash.operation.OpParams; import vash.operation.Operation;
/* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash; /** * Encapsulate all inputs to tree construction, parameterized by the seed and algorithm. */ public class TreeParameters { // tree layout seed private final Seed seed; // tree layout algorithm parameters private final short minDepth; private final short maxDepth;
// Path: src/vash/operation/OpParams.java // public class OpParams { // public final double ratio; // public final double channels; // // /** // * Instantiate a new operation parameters with a default channels count of 3. // * @param ratio // */ // public OpParams(double ratio) { // this.ratio = ratio; // this.channels = 3.0; // } // // /** // * Instantiate a new operation parameters. // * @param ratio // * @param channels // */ // public OpParams(double ratio, double channels) { // this.ratio = ratio; // this.channels = channels; // } // } // // Path: src/vash/operation/Operation.java // public enum Operation { // // colors // RGB, // // arithmetic // ABSOLUTE, // ADD, // DIVIDE, // EXPONENTIATE, // INVERT, // MODULUS, // MULTIPLY, // // trig // SINC, // SINE, // SPIRAL, // SQUIRCLE, // // LEAF // CONST, // ELLIPSE, // FLOWER, // GRADIENT_LINEAR, // GRADIENT_RADIAL, // POLAR_THETA, // ; // } // Path: src/vash/TreeParameters.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import vash.operation.OpParams; import vash.operation.Operation; /* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash; /** * Encapsulate all inputs to tree construction, parameterized by the seed and algorithm. */ public class TreeParameters { // tree layout seed private final Seed seed; // tree layout algorithm parameters private final short minDepth; private final short maxDepth;
private final HashMap<Operation, OpParams> ops;
thevash/vash
src/vash/TreeParameters.java
// Path: src/vash/operation/OpParams.java // public class OpParams { // public final double ratio; // public final double channels; // // /** // * Instantiate a new operation parameters with a default channels count of 3. // * @param ratio // */ // public OpParams(double ratio) { // this.ratio = ratio; // this.channels = 3.0; // } // // /** // * Instantiate a new operation parameters. // * @param ratio // * @param channels // */ // public OpParams(double ratio, double channels) { // this.ratio = ratio; // this.channels = channels; // } // } // // Path: src/vash/operation/Operation.java // public enum Operation { // // colors // RGB, // // arithmetic // ABSOLUTE, // ADD, // DIVIDE, // EXPONENTIATE, // INVERT, // MODULUS, // MULTIPLY, // // trig // SINC, // SINE, // SPIRAL, // SQUIRCLE, // // LEAF // CONST, // ELLIPSE, // FLOWER, // GRADIENT_LINEAR, // GRADIENT_RADIAL, // POLAR_THETA, // ; // }
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import vash.operation.OpParams; import vash.operation.Operation;
/* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash; /** * Encapsulate all inputs to tree construction, parameterized by the seed and algorithm. */ public class TreeParameters { // tree layout seed private final Seed seed; // tree layout algorithm parameters private final short minDepth; private final short maxDepth;
// Path: src/vash/operation/OpParams.java // public class OpParams { // public final double ratio; // public final double channels; // // /** // * Instantiate a new operation parameters with a default channels count of 3. // * @param ratio // */ // public OpParams(double ratio) { // this.ratio = ratio; // this.channels = 3.0; // } // // /** // * Instantiate a new operation parameters. // * @param ratio // * @param channels // */ // public OpParams(double ratio, double channels) { // this.ratio = ratio; // this.channels = channels; // } // } // // Path: src/vash/operation/Operation.java // public enum Operation { // // colors // RGB, // // arithmetic // ABSOLUTE, // ADD, // DIVIDE, // EXPONENTIATE, // INVERT, // MODULUS, // MULTIPLY, // // trig // SINC, // SINE, // SPIRAL, // SQUIRCLE, // // LEAF // CONST, // ELLIPSE, // FLOWER, // GRADIENT_LINEAR, // GRADIENT_RADIAL, // POLAR_THETA, // ; // } // Path: src/vash/TreeParameters.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import vash.operation.OpParams; import vash.operation.Operation; /* * Copyright 2011, Zettabyte Storage LLC * * This file is part of Vash. * * Vash is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vash is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vash. If not, see <http://www.gnu.org/licenses/>. */ package vash; /** * Encapsulate all inputs to tree construction, parameterized by the seed and algorithm. */ public class TreeParameters { // tree layout seed private final Seed seed; // tree layout algorithm parameters private final short minDepth; private final short maxDepth;
private final HashMap<Operation, OpParams> ops;
jmxtrans/jmxtrans-agent
src/main/java/org/jmxtrans/agent/google/MetricWriter.java
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // }
import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import org.jmxtrans.agent.util.StringUtils2; import org.jmxtrans.agent.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.InputStreamReader;
/* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent.google; /** * @author <a href="mailto:[email protected]">Evgeny Minkevich</a> * @author <a href="mailto:[email protected]">Mitch Simpson</a> */ public class MetricWriter { private static final String[] SET_VALUES = new String[]{"projectid", "serviceaccount", "serviceaccountkey", "applicationcredentials", "separator", "nameprefix", "hostname"}; private static final Set<String> RESERVED_KEYWORDS = new HashSet<String>(Arrays.asList(SET_VALUES));
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // } // Path: src/main/java/org/jmxtrans/agent/google/MetricWriter.java import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import org.jmxtrans.agent.util.StringUtils2; import org.jmxtrans.agent.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent.google; /** * @author <a href="mailto:[email protected]">Evgeny Minkevich</a> * @author <a href="mailto:[email protected]">Mitch Simpson</a> */ public class MetricWriter { private static final String[] SET_VALUES = new String[]{"projectid", "serviceaccount", "serviceaccountkey", "applicationcredentials", "separator", "nameprefix", "hostname"}; private static final Set<String> RESERVED_KEYWORDS = new HashSet<String>(Arrays.asList(SET_VALUES));
private final Logger logger = Logger.getLogger(this.getClass().getName());
jmxtrans/jmxtrans-agent
src/test/java/org/jmxtrans/agent/RollingFileOutputWriterTest.java
// Path: src/main/java/org/jmxtrans/agent/util/io/Resource.java // public interface Resource { // /** // * Return an {@link InputStream}. // * <p>It is expected that each call creates a <i>fresh</i> stream. // * @return the input stream for the underlying resource (must not be {@code null}) // * @throws IoRuntimeException if the stream could not be opened // */ // @Nonnull // InputStream getInputStream(); // // /** // * Return whether this resource actually exists in physical form. // * <p>This method performs a definitive existence check, whereas the // * existence of a {@code Resource} handle only guarantees a // * valid descriptor handle. // */ // boolean exists(); // // /** // * Return a URL handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as URL, // * i.e. if the resource is not available as descriptor // */ // @Nonnull // URL getURL(); // // /** // * Return a URI handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as URI, // * i.e. if the resource is not available as descriptor // */ // @Nonnull // URI getURI(); // // /** // * Return a File handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as absolute // * file path, i.e. if the resource is not available in a file system // */ // @Nonnull // File getFile(); // // /** // * Determine the last-modified timestamp for this resource. // * @throws IoRuntimeException if the resource cannot be resolved // * (in the file system or as some other known physical resource type) // */ // long lastModified(); // // /** // * Return a description for this resource, // * to be used for error output when working with the resource. // * <p>Implementations are also encouraged to return this value // * from their {@code toString} method. // * @see Object#toString() // */ // String getDescription(); // }
import org.jmxtrans.agent.util.io.ClasspathResource; import org.jmxtrans.agent.util.io.Resource; import org.junit.Test; import java.io.*; import java.nio.charset.Charset; import java.nio.file.*; import java.util.List; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.isEmptyString; import static org.junit.Assert.assertThat;
package org.jmxtrans.agent; public class RollingFileOutputWriterTest { @Test public void testWriteQueryResultMulti() throws IOException { Path defaultLog =Paths.get("jmxtrans-agent.data"); Files.deleteIfExists(defaultLog);
// Path: src/main/java/org/jmxtrans/agent/util/io/Resource.java // public interface Resource { // /** // * Return an {@link InputStream}. // * <p>It is expected that each call creates a <i>fresh</i> stream. // * @return the input stream for the underlying resource (must not be {@code null}) // * @throws IoRuntimeException if the stream could not be opened // */ // @Nonnull // InputStream getInputStream(); // // /** // * Return whether this resource actually exists in physical form. // * <p>This method performs a definitive existence check, whereas the // * existence of a {@code Resource} handle only guarantees a // * valid descriptor handle. // */ // boolean exists(); // // /** // * Return a URL handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as URL, // * i.e. if the resource is not available as descriptor // */ // @Nonnull // URL getURL(); // // /** // * Return a URI handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as URI, // * i.e. if the resource is not available as descriptor // */ // @Nonnull // URI getURI(); // // /** // * Return a File handle for this resource. // * @throws IoRuntimeException if the resource cannot be resolved as absolute // * file path, i.e. if the resource is not available in a file system // */ // @Nonnull // File getFile(); // // /** // * Determine the last-modified timestamp for this resource. // * @throws IoRuntimeException if the resource cannot be resolved // * (in the file system or as some other known physical resource type) // */ // long lastModified(); // // /** // * Return a description for this resource, // * to be used for error output when working with the resource. // * <p>Implementations are also encouraged to return this value // * from their {@code toString} method. // * @see Object#toString() // */ // String getDescription(); // } // Path: src/test/java/org/jmxtrans/agent/RollingFileOutputWriterTest.java import org.jmxtrans.agent.util.io.ClasspathResource; import org.jmxtrans.agent.util.io.Resource; import org.junit.Test; import java.io.*; import java.nio.charset.Charset; import java.nio.file.*; import java.util.List; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.isEmptyString; import static org.junit.Assert.assertThat; package org.jmxtrans.agent; public class RollingFileOutputWriterTest { @Test public void testWriteQueryResultMulti() throws IOException { Path defaultLog =Paths.get("jmxtrans-agent.data"); Files.deleteIfExists(defaultLog);
Resource resource = new ClasspathResource("classpath:jmxtrans-config-rolling-multi-test.xml");
jmxtrans/jmxtrans-agent
src/test/java/org/jmxtrans/agent/GraphiteMetricMessageBuilderTest.java
// Path: src/main/java/org/jmxtrans/agent/graphite/GraphiteMetricMessageBuilder.java // public class GraphiteMetricMessageBuilder { // // private static final String DEFAULT_METRIC_PATH_PREFIX_FORMAT = "servers.%s."; // private final String metricPathPrefix; // // /** // * @param configuredMetricPathPrefix // * Prefix to add to the metric keys. May be null, in which case servers.your_hostname will be used. // */ // public GraphiteMetricMessageBuilder(@Nullable String configuredMetricPathPrefix) { // this.metricPathPrefix = buildMetricPathPrefix(configuredMetricPathPrefix); // } // // /** // * Builds a metric string to send to a Graphite instance. // * // * @return The metric string without trailing newline // */ // public String buildMessage(String metricName, Object value, long timestamp) { // if (value instanceof Boolean) { // return metricPathPrefix + metricName + " " + ((Boolean)value ? 1 : 0) + " " + timestamp; // } // return metricPathPrefix + metricName + " " + value + " " + timestamp; // } // // /** // * {@link java.net.InetAddress#getLocalHost()} may not be known at JVM startup when the process is launched as a Linux service. // */ // private static String buildMetricPathPrefix(String configuredMetricPathPrefix) { // if (configuredMetricPathPrefix != null) { // return configuredMetricPathPrefix; // } // String hostname; // try { // hostname = InetAddress.getLocalHost().getHostName().replaceAll("\\.", "_"); // } catch (UnknownHostException e) { // hostname = "#unknown#"; // } // return String.format(DEFAULT_METRIC_PATH_PREFIX_FORMAT, hostname); // } // // public String getPrefix() { // return metricPathPrefix; // } // // }
import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.jmxtrans.agent.graphite.GraphiteMetricMessageBuilder; import org.junit.Test;
/* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent; /** * @author Kristoffer Erlandsson */ public class GraphiteMetricMessageBuilderTest { @Test public void configuredPrefix() throws Exception {
// Path: src/main/java/org/jmxtrans/agent/graphite/GraphiteMetricMessageBuilder.java // public class GraphiteMetricMessageBuilder { // // private static final String DEFAULT_METRIC_PATH_PREFIX_FORMAT = "servers.%s."; // private final String metricPathPrefix; // // /** // * @param configuredMetricPathPrefix // * Prefix to add to the metric keys. May be null, in which case servers.your_hostname will be used. // */ // public GraphiteMetricMessageBuilder(@Nullable String configuredMetricPathPrefix) { // this.metricPathPrefix = buildMetricPathPrefix(configuredMetricPathPrefix); // } // // /** // * Builds a metric string to send to a Graphite instance. // * // * @return The metric string without trailing newline // */ // public String buildMessage(String metricName, Object value, long timestamp) { // if (value instanceof Boolean) { // return metricPathPrefix + metricName + " " + ((Boolean)value ? 1 : 0) + " " + timestamp; // } // return metricPathPrefix + metricName + " " + value + " " + timestamp; // } // // /** // * {@link java.net.InetAddress#getLocalHost()} may not be known at JVM startup when the process is launched as a Linux service. // */ // private static String buildMetricPathPrefix(String configuredMetricPathPrefix) { // if (configuredMetricPathPrefix != null) { // return configuredMetricPathPrefix; // } // String hostname; // try { // hostname = InetAddress.getLocalHost().getHostName().replaceAll("\\.", "_"); // } catch (UnknownHostException e) { // hostname = "#unknown#"; // } // return String.format(DEFAULT_METRIC_PATH_PREFIX_FORMAT, hostname); // } // // public String getPrefix() { // return metricPathPrefix; // } // // } // Path: src/test/java/org/jmxtrans/agent/GraphiteMetricMessageBuilderTest.java import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.jmxtrans.agent.graphite.GraphiteMetricMessageBuilder; import org.junit.Test; /* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent; /** * @author Kristoffer Erlandsson */ public class GraphiteMetricMessageBuilderTest { @Test public void configuredPrefix() throws Exception {
GraphiteMetricMessageBuilder builder = new GraphiteMetricMessageBuilder("foo.");
jmxtrans/jmxtrans-agent
src/main/java/org/jmxtrans/agent/Invocation.java
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // }
import javax.management.ObjectName; import java.util.Arrays; import java.util.Set; import java.util.logging.Level; import org.jmxtrans.agent.util.Preconditions2; import org.jmxtrans.agent.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException;
/* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class Invocation implements Collector { @Nullable protected final ObjectName objectName; @Nonnull protected final String operationName; @Nullable protected final String resultAlias; @Nullable protected final String type; @Nonnull protected final Object[] params; @Nonnull protected final String[] signature;
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // } // Path: src/main/java/org/jmxtrans/agent/Invocation.java import javax.management.ObjectName; import java.util.Arrays; import java.util.Set; import java.util.logging.Level; import org.jmxtrans.agent.util.Preconditions2; import org.jmxtrans.agent.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; /* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent; /** * @author <a href="mailto:[email protected]">Cyrille Le Clerc</a> */ public class Invocation implements Collector { @Nullable protected final ObjectName objectName; @Nonnull protected final String operationName; @Nullable protected final String resultAlias; @Nullable protected final String type; @Nonnull protected final Object[] params; @Nonnull protected final String[] signature;
private final Logger logger = Logger.getLogger(getClass().getName());
jmxtrans/jmxtrans-agent
src/main/java/org/jmxtrans/agent/google/Connection.java
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // }
import org.jmxtrans.agent.util.json.Json; import org.jmxtrans.agent.util.json.JsonObject; import org.jmxtrans.agent.util.json.JsonValue; import org.jmxtrans.agent.util.logging.Logger; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import static org.jmxtrans.agent.util.StringUtils2.isNullOrEmpty;
/* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent.google; /** * @author <a href="mailto:[email protected]">Evgeny Minkevich</a> * @author <a href="mailto:[email protected]">Mitch Simpson</a> */ public class Connection { private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/token"; private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; private static final String SCOPE = "https://www.googleapis.com/auth/monitoring"; private static final String API_URL = "https://monitoring.googleapis.com/v3";
// Path: src/main/java/org/jmxtrans/agent/util/logging/Logger.java // public class Logger { // // public static Logger getLogger(String name) { // return new Logger(name); // } // // private final String name; // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static PrintStream out; // // static { // if ("stderr".equalsIgnoreCase(System.getenv("JMX_TRANS_AGENT_CONSOLE")) || // "stderr".equalsIgnoreCase(System.getProperty(Logger.class.getName() + ".console"))) { // Logger.out = System.err; // } else { // Logger.out = System.out; // } // } // // @SuppressFBWarnings("MS_SHOULD_BE_REFACTORED_TO_BE_FINAL") // public static Level level = Level.INFO; // // @Nullable // public static Level parseLevel(@Nullable String level, @Nullable Level defaultValue) { // // Map<String, Level> julLevelsByName = new HashMap<String, Level>() { // { // put("TRACE", Level.FINEST); // put("FINEST", Level.FINEST); // put("FINER", Level.FINER); // put("FINE", Level.FINE); // put("DEBUG", Level.FINE); // put("INFO", Level.INFO); // put("WARNING", Level.WARNING); // put("WARN", Level.WARNING); // put("SEVERE", Level.SEVERE); // // } // }; // // for(Map.Entry<String, Level> entry: julLevelsByName.entrySet()) { // if(entry.getKey().equalsIgnoreCase(level)) // return entry.getValue(); // } // return defaultValue; // } // // static { // String level = System.getProperty(Logger.class.getName() + ".level", "INFO"); // Logger.level = parseLevel(level, Level.INFO); // } // // public Logger(String name) { // this.name = name; // } // // public void log(Level level, String msg) { // log(level, msg, null); // } // // public void log(Level level, String msg, Throwable thrown) { // if (!isLoggable(level)) { // return; // } // Logger.out.println(new Timestamp(System.currentTimeMillis()) + " " + level + " [" + Thread.currentThread().getName() + "] " + name + " - " + msg); // if (thrown != null) { // thrown.printStackTrace(Logger.out); // } // } // // public void finest(String msg) { // log(Level.FINEST, msg); // } // // public void finer(String msg) { // log(Level.FINER, msg); // } // // public void fine(String msg) { // log(Level.FINE, msg); // } // // public void info(String msg) { // log(Level.INFO, msg); // } // // public void warning(String msg) { // log(Level.WARNING, msg); // } // // public boolean isLoggable(Level level) { // if (level.intValue() < this.level.intValue()) { // return false; // } // return true; // } // } // Path: src/main/java/org/jmxtrans/agent/google/Connection.java import org.jmxtrans.agent.util.json.Json; import org.jmxtrans.agent.util.json.JsonObject; import org.jmxtrans.agent.util.json.JsonValue; import org.jmxtrans.agent.util.logging.Logger; import javax.xml.bind.DatatypeConverter; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.Charset; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import static org.jmxtrans.agent.util.StringUtils2.isNullOrEmpty; /* * Copyright (c) 2010-2013 the original author or authors * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.jmxtrans.agent.google; /** * @author <a href="mailto:[email protected]">Evgeny Minkevich</a> * @author <a href="mailto:[email protected]">Mitch Simpson</a> */ public class Connection { private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/token"; private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; private static final String SCOPE = "https://www.googleapis.com/auth/monitoring"; private static final String API_URL = "https://monitoring.googleapis.com/v3";
private static Logger logger = Logger.getLogger(Connection.class.getName());
kaltura/player-sdk-native-android
googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExtractorRendererBuilder.java
// Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExoplayerWrapper.java // public interface RendererBuilder { // /** // * Constructs the necessary components for playback. // * // * @param player The parent player. // */ // void buildRenderers(ExoplayerWrapper player); // // /** // * Cancels the current build operation, if there is one. Else does nothing. // */ // void cancel(); // } // // Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/layeredvideo/Util.java // public class Util { // // /** // * Create a LayoutParams object for the given view which enforces a given width and height. // * // * <p>This method is a bit complicated because the TYPE of the LayoutParams that a view must // * receive (ex. LinearLayout.LayoutParams, RelativeLayout.LayoutParams) depends on the type of its // * PARENT view. // * // * <p>Thus, in this method, we look at the parent view of the given view, determine its type, // * and create the appropriate LayoutParams for that type. // * // * <p>This method only supports views which are nested inside a FrameLayout, LinearLayout, or // * GridLayout. // */ // public static ViewGroup.LayoutParams getLayoutParamsBasedOnParent(View view, int width, int height) // throws IllegalArgumentException { // // // Get the parent of the given view. // ViewParent parent = view.getParent(); // // // Determine what is the parent's type and return the appropriate type of LayoutParams. // if (parent instanceof FrameLayout) { // return new FrameLayout.LayoutParams(width, height); // } // if (parent instanceof RelativeLayout) { // return new RelativeLayout.LayoutParams(width, height); // } // if (parent instanceof LinearLayout) { // return new LinearLayout.LayoutParams(width, height); // } // // // Throw this exception if the parent is not the correct type. // IllegalArgumentException exception = new IllegalArgumentException("The PARENT of a " + // "FrameLayout container used by the GoogleMediaFramework must be a LinearLayout, " + // "FrameLayout, or RelativeLayout. Please ensure that the container is inside one of these " + // "three supported view groups."); // // // If the parent is not one of the supported types, throw our exception. // throw exception; // } // // /** Returns the consumer friendly device name */ // public static String getDeviceInfo() { // return Build.MANUFACTURER + " " + Build.MODEL + " " + android.os.Build.VERSION.RELEASE; // } // }
import android.content.Context; import android.media.AudioManager; import android.media.MediaCodec; import android.net.Uri; import android.util.Log; import com.google.android.exoplayer.DecoderInfo; import com.google.android.exoplayer.MediaCodecAudioTrackRenderer; import com.google.android.exoplayer.MediaCodecSelector; import com.google.android.exoplayer.MediaCodecUtil; import com.google.android.exoplayer.MediaCodecVideoTrackRenderer; import com.google.android.exoplayer.TrackRenderer; import com.google.android.exoplayer.audio.AudioCapabilities; import com.google.android.exoplayer.extractor.Extractor; import com.google.android.exoplayer.extractor.ExtractorSampleSource; import com.google.android.exoplayer.text.TextTrackRenderer; import com.google.android.exoplayer.upstream.Allocator; import com.google.android.exoplayer.upstream.DataSource; import com.google.android.exoplayer.upstream.DefaultAllocator; import com.google.android.exoplayer.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer.upstream.DefaultUriDataSource; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerWrapper.RendererBuilder; import com.google.android.libraries.mediaframework.layeredvideo.Util;
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.mediaframework.exoplayerextensions; /** * A {@link RendererBuilder} for streams that can be read using an {@link Extractor}. */ public class ExtractorRendererBuilder implements RendererBuilder { private static final int BUFFER_SEGMENT_SIZE = 64 * 1024; private static final int BUFFER_SEGMENT_COUNT = 256; private final Context context; private final String userAgent; private final Uri uri; private final boolean preferSoftwareDecoder; public ExtractorRendererBuilder(Context context, String userAgent, Uri uri, boolean preferSoftwareDecoder) { this.context = context; this.userAgent = userAgent; this.uri = uri; this.preferSoftwareDecoder = preferSoftwareDecoder; } private MediaCodecSelector preferSoftwareMediaCodecSelector = new MediaCodecSelector() { @Override public DecoderInfo getDecoderInfo(String mimeType, boolean requiresSecureDecoder) throws MediaCodecUtil.DecoderQueryException {
// Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExoplayerWrapper.java // public interface RendererBuilder { // /** // * Constructs the necessary components for playback. // * // * @param player The parent player. // */ // void buildRenderers(ExoplayerWrapper player); // // /** // * Cancels the current build operation, if there is one. Else does nothing. // */ // void cancel(); // } // // Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/layeredvideo/Util.java // public class Util { // // /** // * Create a LayoutParams object for the given view which enforces a given width and height. // * // * <p>This method is a bit complicated because the TYPE of the LayoutParams that a view must // * receive (ex. LinearLayout.LayoutParams, RelativeLayout.LayoutParams) depends on the type of its // * PARENT view. // * // * <p>Thus, in this method, we look at the parent view of the given view, determine its type, // * and create the appropriate LayoutParams for that type. // * // * <p>This method only supports views which are nested inside a FrameLayout, LinearLayout, or // * GridLayout. // */ // public static ViewGroup.LayoutParams getLayoutParamsBasedOnParent(View view, int width, int height) // throws IllegalArgumentException { // // // Get the parent of the given view. // ViewParent parent = view.getParent(); // // // Determine what is the parent's type and return the appropriate type of LayoutParams. // if (parent instanceof FrameLayout) { // return new FrameLayout.LayoutParams(width, height); // } // if (parent instanceof RelativeLayout) { // return new RelativeLayout.LayoutParams(width, height); // } // if (parent instanceof LinearLayout) { // return new LinearLayout.LayoutParams(width, height); // } // // // Throw this exception if the parent is not the correct type. // IllegalArgumentException exception = new IllegalArgumentException("The PARENT of a " + // "FrameLayout container used by the GoogleMediaFramework must be a LinearLayout, " + // "FrameLayout, or RelativeLayout. Please ensure that the container is inside one of these " + // "three supported view groups."); // // // If the parent is not one of the supported types, throw our exception. // throw exception; // } // // /** Returns the consumer friendly device name */ // public static String getDeviceInfo() { // return Build.MANUFACTURER + " " + Build.MODEL + " " + android.os.Build.VERSION.RELEASE; // } // } // Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExtractorRendererBuilder.java import android.content.Context; import android.media.AudioManager; import android.media.MediaCodec; import android.net.Uri; import android.util.Log; import com.google.android.exoplayer.DecoderInfo; import com.google.android.exoplayer.MediaCodecAudioTrackRenderer; import com.google.android.exoplayer.MediaCodecSelector; import com.google.android.exoplayer.MediaCodecUtil; import com.google.android.exoplayer.MediaCodecVideoTrackRenderer; import com.google.android.exoplayer.TrackRenderer; import com.google.android.exoplayer.audio.AudioCapabilities; import com.google.android.exoplayer.extractor.Extractor; import com.google.android.exoplayer.extractor.ExtractorSampleSource; import com.google.android.exoplayer.text.TextTrackRenderer; import com.google.android.exoplayer.upstream.Allocator; import com.google.android.exoplayer.upstream.DataSource; import com.google.android.exoplayer.upstream.DefaultAllocator; import com.google.android.exoplayer.upstream.DefaultBandwidthMeter; import com.google.android.exoplayer.upstream.DefaultUriDataSource; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerWrapper.RendererBuilder; import com.google.android.libraries.mediaframework.layeredvideo.Util; /* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.mediaframework.exoplayerextensions; /** * A {@link RendererBuilder} for streams that can be read using an {@link Extractor}. */ public class ExtractorRendererBuilder implements RendererBuilder { private static final int BUFFER_SEGMENT_SIZE = 64 * 1024; private static final int BUFFER_SEGMENT_COUNT = 256; private final Context context; private final String userAgent; private final Uri uri; private final boolean preferSoftwareDecoder; public ExtractorRendererBuilder(Context context, String userAgent, Uri uri, boolean preferSoftwareDecoder) { this.context = context; this.userAgent = userAgent; this.uri = uri; this.preferSoftwareDecoder = preferSoftwareDecoder; } private MediaCodecSelector preferSoftwareMediaCodecSelector = new MediaCodecSelector() { @Override public DecoderInfo getDecoderInfo(String mimeType, boolean requiresSecureDecoder) throws MediaCodecUtil.DecoderQueryException {
Log.d("Kaltura", "DeviceInfo: " + Util.getDeviceInfo() + ", mimeType:" + mimeType + ", requiresSecureDecoder" + requiresSecureDecoder);
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/drm/OfflineDrmSessionManager.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // @NonNull // public static String toHexString(byte[] bytes) { // // Create Hex String // StringBuilder hexString = new StringBuilder(); // for (byte b : bytes) { // String h = Integer.toHexString(0xFF & b); // hexString.append(h.length() == 1 ? "0" : "").append(h); // } // return hexString.toString(); // }
import android.annotation.TargetApi; import android.media.MediaCrypto; import android.media.MediaCryptoException; import android.media.MediaDrm; import android.media.NotProvisionedException; import android.media.UnsupportedSchemeException; import android.os.Build; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.exoplayer.drm.DrmInitData; import com.google.android.exoplayer.drm.DrmSessionManager; import com.google.android.exoplayer.drm.UnsupportedDrmException; import java.util.LinkedHashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerUtil.WIDEVINE_UUID; import static com.kaltura.playersdk.helpers.KStringUtilities.toHexString;
package com.kaltura.playersdk.drm; /** * Created by noamt on 04/05/2016. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class OfflineDrmSessionManager implements DrmSessionManager { private static final String TAG = "OfflineDrmSessionMgr"; private final MediaDrm mMediaDrm; private final OfflineKeySetStorage mStorage; private MediaCrypto mMediaCrypto; private MediaDrmSession mSession; private int mState = STATE_CLOSED; private Exception mLastError; private AtomicInteger mOpenCount = new AtomicInteger(0); OfflineDrmSessionManager(OfflineKeySetStorage storage) throws UnsupportedDrmException { mStorage = storage; try { mMediaDrm = new MediaDrm(WIDEVINE_UUID); OfflineDrmManager.printAllProperties(mMediaDrm); mMediaDrm.setOnEventListener(new MediaDrm.OnEventListener() { @Override public void onEvent(@NonNull MediaDrm md, byte[] sessionId, int event, int extra, byte[] data) {
// Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // @NonNull // public static String toHexString(byte[] bytes) { // // Create Hex String // StringBuilder hexString = new StringBuilder(); // for (byte b : bytes) { // String h = Integer.toHexString(0xFF & b); // hexString.append(h.length() == 1 ? "0" : "").append(h); // } // return hexString.toString(); // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/drm/OfflineDrmSessionManager.java import android.annotation.TargetApi; import android.media.MediaCrypto; import android.media.MediaCryptoException; import android.media.MediaDrm; import android.media.NotProvisionedException; import android.media.UnsupportedSchemeException; import android.os.Build; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.exoplayer.drm.DrmInitData; import com.google.android.exoplayer.drm.DrmSessionManager; import com.google.android.exoplayer.drm.UnsupportedDrmException; import java.util.LinkedHashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerUtil.WIDEVINE_UUID; import static com.kaltura.playersdk.helpers.KStringUtilities.toHexString; package com.kaltura.playersdk.drm; /** * Created by noamt on 04/05/2016. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) class OfflineDrmSessionManager implements DrmSessionManager { private static final String TAG = "OfflineDrmSessionMgr"; private final MediaDrm mMediaDrm; private final OfflineKeySetStorage mStorage; private MediaCrypto mMediaCrypto; private MediaDrmSession mSession; private int mState = STATE_CLOSED; private Exception mLastError; private AtomicInteger mOpenCount = new AtomicInteger(0); OfflineDrmSessionManager(OfflineKeySetStorage storage) throws UnsupportedDrmException { mStorage = storage; try { mMediaDrm = new MediaDrm(WIDEVINE_UUID); OfflineDrmManager.printAllProperties(mMediaDrm); mMediaDrm.setOnEventListener(new MediaDrm.OnEventListener() { @Override public void onEvent(@NonNull MediaDrm md, byte[] sessionId, int event, int extra, byte[] data) {
Log.d(TAG, "onEvent:" + toHexString(sessionId) + ":" + event + ":" + extra + ":" + toHexString(data));
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/actionHandlers/ShareStrategies/WebShareStrategy.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/BrowserActivity.java // public class BrowserActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_browser); // Bundle extras = getIntent().getExtras(); // String shareLink = extras.getString("ShareLink"); // if (shareLink != null) { // WebView webView = (WebView)findViewById(R.id.browserWebView); // webView.setWebViewClient(new WebViewClient()); // webView.loadUrl(shareLink); // } // ActionBar actionBar = getActionBar(); // if(actionBar != null) { // actionBar.setHomeButtonEnabled(true); // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(extras.getString("VideoName")); // String barColor = extras.getString("BarColor"); // if(barColor != null && !barColor.isEmpty()){ // actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(barColor))); // } // } // // } // // // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // //getMenuInflater().inflate(R.menu.menu_browser, menu); // return true; // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // // return super.onPrepareOptionsMenu(menu); // // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // finish(); // overridePendingTransition(R.animator.trans_right_in, R.animator.trans_right_out); // return super.onOptionsItemSelected(item); // } // // // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/actionHandlers/ShareManager.java // public class ShareManager { // // public static final String TAG = ShareManager.class.getSimpleName(); // // public static void share(JSONObject dataSource, Activity activity) { // KPShareStrategy strategy = ShareStrategyFactory.getStrategy(dataSource); // if (strategy != null) // { // strategy.share(dataSource, activity); // } // // } // // public interface KPShareStrategy { // public void share(JSONObject dataSource, Activity activity); // } // // public static enum SharingType{ // SHARE_FACEBOOK("Facebook"), // SHARE_TWITTER("Twitter"), // SHARE_LINKEDIN("Linkedin"), // SHARE_EMAIL("Email"), // SHARE_SMS("Sms"), // SHARE_GOOGLE_PLUS("Googleplus"); // // private String label; // // private SharingType(String str) { // this.label = str; // } // // public String toString() { // return this.label; // } // // public static SharingType fromString(String label) { // if (label != null) { // for (SharingType sharingKey : SharingType.values()) { // if (label.equalsIgnoreCase(sharingKey.label)) { // return sharingKey; // } // } // } // // return null; // } // // } // // }
import android.app.Activity; import android.content.Intent; import com.kaltura.playersdk.R; import com.kaltura.playersdk.BrowserActivity; import com.kaltura.playersdk.actionHandlers.ShareManager; import org.json.JSONException; import org.json.JSONObject;
package com.kaltura.playersdk.actionHandlers.ShareStrategies; /** * Created by itayi on 3/5/15. */ public class WebShareStrategy implements ShareManager.KPShareStrategy { @Override public void share(JSONObject shareParams, Activity activity) { String sharePrefix = ""; String videoLink = ""; String videoName = ""; String barColor = ""; try { sharePrefix = ((String)((JSONObject)shareParams.get("shareNetwork")).get("template")).replace("{share.shareURL}", ""); videoLink = (String)shareParams.get("sharedLink"); videoName = (String)shareParams.get("videoName"); barColor = (String)((JSONObject)shareParams.get("shareNetwork")).get("barColor"); } catch (JSONException e) { e.printStackTrace(); } String shareScheme = sharePrefix + videoLink;
// Path: playerSDK/src/main/java/com/kaltura/playersdk/BrowserActivity.java // public class BrowserActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_browser); // Bundle extras = getIntent().getExtras(); // String shareLink = extras.getString("ShareLink"); // if (shareLink != null) { // WebView webView = (WebView)findViewById(R.id.browserWebView); // webView.setWebViewClient(new WebViewClient()); // webView.loadUrl(shareLink); // } // ActionBar actionBar = getActionBar(); // if(actionBar != null) { // actionBar.setHomeButtonEnabled(true); // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setTitle(extras.getString("VideoName")); // String barColor = extras.getString("BarColor"); // if(barColor != null && !barColor.isEmpty()){ // actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(barColor))); // } // } // // } // // // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // //getMenuInflater().inflate(R.menu.menu_browser, menu); // return true; // } // // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // // return super.onPrepareOptionsMenu(menu); // // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // finish(); // overridePendingTransition(R.animator.trans_right_in, R.animator.trans_right_out); // return super.onOptionsItemSelected(item); // } // // // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/actionHandlers/ShareManager.java // public class ShareManager { // // public static final String TAG = ShareManager.class.getSimpleName(); // // public static void share(JSONObject dataSource, Activity activity) { // KPShareStrategy strategy = ShareStrategyFactory.getStrategy(dataSource); // if (strategy != null) // { // strategy.share(dataSource, activity); // } // // } // // public interface KPShareStrategy { // public void share(JSONObject dataSource, Activity activity); // } // // public static enum SharingType{ // SHARE_FACEBOOK("Facebook"), // SHARE_TWITTER("Twitter"), // SHARE_LINKEDIN("Linkedin"), // SHARE_EMAIL("Email"), // SHARE_SMS("Sms"), // SHARE_GOOGLE_PLUS("Googleplus"); // // private String label; // // private SharingType(String str) { // this.label = str; // } // // public String toString() { // return this.label; // } // // public static SharingType fromString(String label) { // if (label != null) { // for (SharingType sharingKey : SharingType.values()) { // if (label.equalsIgnoreCase(sharingKey.label)) { // return sharingKey; // } // } // } // // return null; // } // // } // // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/actionHandlers/ShareStrategies/WebShareStrategy.java import android.app.Activity; import android.content.Intent; import com.kaltura.playersdk.R; import com.kaltura.playersdk.BrowserActivity; import com.kaltura.playersdk.actionHandlers.ShareManager; import org.json.JSONException; import org.json.JSONObject; package com.kaltura.playersdk.actionHandlers.ShareStrategies; /** * Created by itayi on 3/5/15. */ public class WebShareStrategy implements ShareManager.KPShareStrategy { @Override public void share(JSONObject shareParams, Activity activity) { String sharePrefix = ""; String videoLink = ""; String videoName = ""; String barColor = ""; try { sharePrefix = ((String)((JSONObject)shareParams.get("shareNetwork")).get("template")).replace("{share.shareURL}", ""); videoLink = (String)shareParams.get("sharedLink"); videoName = (String)shareParams.get("videoName"); barColor = (String)((JSONObject)shareParams.get("shareNetwork")).get("barColor"); } catch (JSONException e) { e.printStackTrace(); } String shareScheme = sharePrefix + videoLink;
Intent shareIntent = new Intent(activity, BrowserActivity.class);
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/helpers/KIMAManager.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KIMAManagerListener.java // public interface KIMAManagerListener { // void onAdEvent(AdEvent.AdEventType eventType, String jsonValue); // void onAdUpdateProgress(String jsonValue); // void onAdError(String errorMsg); // }
import android.app.Activity; import android.view.ViewGroup; import android.widget.FrameLayout; import com.google.ads.interactivemedia.v3.api.Ad; import com.google.ads.interactivemedia.v3.api.AdDisplayContainer; import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.ads.interactivemedia.v3.api.AdEvent; import com.google.ads.interactivemedia.v3.api.AdsLoader; import com.google.ads.interactivemedia.v3.api.AdsManager; import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent; import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings; import com.google.ads.interactivemedia.v3.api.AdsRequest; import com.google.ads.interactivemedia.v3.api.ImaSdkFactory; import com.google.ads.interactivemedia.v3.api.UiElement; import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider; import com.kaltura.playersdk.interfaces.KIMAManagerListener; import com.kaltura.playersdk.players.KIMAAdPlayer; import com.kaltura.playersdk.players.KMediaFormat; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE;
package com.kaltura.playersdk.helpers; /** * Created by nissopa on 6/30/15. */ public class KIMAManager implements AdErrorEvent.AdErrorListener, AdsLoader.AdsLoadedListener, AdEvent.AdEventListener, KIMAAdPlayer.KIMAAdPlayerEvents { private static final String TAG = "KIMAManager"; // Container with references to video player and ad UI ViewGroup. private AdDisplayContainer mAdDisplayContainer; // The AdsLoader instance exposes the requestAds method. private AdsLoader mAdsLoader; // AdsManager exposes methods to control ad playback and listen to ad events. private AdsManager mAdsManager; // Factory class for creating SDK objects. private ImaSdkFactory mSdkFactory; // Ad-enabled video player. private KIMAAdPlayer mIMAPlayer; // Default VAST ad tag; more complex apps might select ad tag based on content video criteria. private String mDefaultAdTagUrl; private String mAdMimeType; private int mAdPreferredBitrate;
// Path: playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KIMAManagerListener.java // public interface KIMAManagerListener { // void onAdEvent(AdEvent.AdEventType eventType, String jsonValue); // void onAdUpdateProgress(String jsonValue); // void onAdError(String errorMsg); // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KIMAManager.java import android.app.Activity; import android.view.ViewGroup; import android.widget.FrameLayout; import com.google.ads.interactivemedia.v3.api.Ad; import com.google.ads.interactivemedia.v3.api.AdDisplayContainer; import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.ads.interactivemedia.v3.api.AdEvent; import com.google.ads.interactivemedia.v3.api.AdsLoader; import com.google.ads.interactivemedia.v3.api.AdsManager; import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent; import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings; import com.google.ads.interactivemedia.v3.api.AdsRequest; import com.google.ads.interactivemedia.v3.api.ImaSdkFactory; import com.google.ads.interactivemedia.v3.api.UiElement; import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider; import com.kaltura.playersdk.interfaces.KIMAManagerListener; import com.kaltura.playersdk.players.KIMAAdPlayer; import com.kaltura.playersdk.players.KMediaFormat; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE; package com.kaltura.playersdk.helpers; /** * Created by nissopa on 6/30/15. */ public class KIMAManager implements AdErrorEvent.AdErrorListener, AdsLoader.AdsLoadedListener, AdEvent.AdEventListener, KIMAAdPlayer.KIMAAdPlayerEvents { private static final String TAG = "KIMAManager"; // Container with references to video player and ad UI ViewGroup. private AdDisplayContainer mAdDisplayContainer; // The AdsLoader instance exposes the requestAds method. private AdsLoader mAdsLoader; // AdsManager exposes methods to control ad playback and listen to ad events. private AdsManager mAdsManager; // Factory class for creating SDK objects. private ImaSdkFactory mSdkFactory; // Ad-enabled video player. private KIMAAdPlayer mIMAPlayer; // Default VAST ad tag; more complex apps might select ad tag based on content video criteria. private String mDefaultAdTagUrl; private String mAdMimeType; private int mAdPreferredBitrate;
private KIMAManagerListener mListener;
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KMediaControl.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/events/KPlayerState.java // public enum KPlayerState { // UNKNOWN("unknown"), // LOADED("loadedmetadata"), // PRE_LOADED("loadedmetadata"), // READY("canplay"), // CC_READY("canplay"), // PLAYING("play"), // PAUSED("pause"), // SEEKED("seeked"), // SEEKING("seeking"), // ENDED("ended"); // // // private String stringValue; // KPlayerState(String toString) { // stringValue = toString; // } // // public static KPlayerState getStateForEventName(String eventName) { // switch (eventName) { // case "loadedmetadata": // return LOADED; // case "canplay": // return READY; // case "play": // return PLAYING; // case "pause": // return PAUSED; // case "seeked": // return SEEKED; // case "seeking": // return SEEKING; // case "ended": // return ENDED; // } // return UNKNOWN; // } // // @Override // public String toString() { // return stringValue; // } // }
import com.kaltura.playersdk.events.KPlayerState;
package com.kaltura.playersdk.interfaces; /** * Created by nissimpardo on 23/02/16. */ public interface KMediaControl { void start(); void pause(); void seek(double seconds); void replay(); boolean canPause(); int getCurrentPosition(); int getDuration(); boolean isPlaying(); boolean canSeekBackward(); boolean canSeekForward(); void seek(long milliSeconds, SeekCallback callback); interface SeekCallback { void seeked(long milliSeconds); }
// Path: playerSDK/src/main/java/com/kaltura/playersdk/events/KPlayerState.java // public enum KPlayerState { // UNKNOWN("unknown"), // LOADED("loadedmetadata"), // PRE_LOADED("loadedmetadata"), // READY("canplay"), // CC_READY("canplay"), // PLAYING("play"), // PAUSED("pause"), // SEEKED("seeked"), // SEEKING("seeking"), // ENDED("ended"); // // // private String stringValue; // KPlayerState(String toString) { // stringValue = toString; // } // // public static KPlayerState getStateForEventName(String eventName) { // switch (eventName) { // case "loadedmetadata": // return LOADED; // case "canplay": // return READY; // case "play": // return PLAYING; // case "pause": // return PAUSED; // case "seeked": // return SEEKED; // case "seeking": // return SEEKING; // case "ended": // return ENDED; // } // return UNKNOWN; // } // // @Override // public String toString() { // return stringValue; // } // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KMediaControl.java import com.kaltura.playersdk.events.KPlayerState; package com.kaltura.playersdk.interfaces; /** * Created by nissimpardo on 23/02/16. */ public interface KMediaControl { void start(); void pause(); void seek(double seconds); void replay(); boolean canPause(); int getCurrentPosition(); int getDuration(); boolean isPlaying(); boolean canSeekBackward(); boolean canSeekForward(); void seek(long milliSeconds, SeekCallback callback); interface SeekCallback { void seeked(long milliSeconds); }
KPlayerState state();
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/players/KPlayerExoDrmCallback.java
// Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExtendedMediaDrmCallback.java // public interface ExtendedMediaDrmCallback extends MediaDrmCallback { // /** // * Optional DrmSessionManager. If not provided, the default (StreamingDrmSessionManager) is used. // * @return A DrmSessionManager, ready to be opened. // */ // DrmSessionManager getSessionManager(); // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/drm/OfflineDrmManager.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class OfflineDrmManager { // // private static final String TAG = "OfflineDrmManager"; // // // public static DrmSessionManager getSessionManager(Context context) { // try { // return new OfflineDrmSessionManager(getStorage(context)); // } catch (UnsupportedDrmException e) { // throw new WidevineNotSupportedException(e); // } // } // // public static OfflineKeySetStorage getStorage(Context context) { // return new OfflineKeySetStorage(context); // } // // // static void printAllProperties(MediaDrm mediaDrm) { // String[] stringProps = {MediaDrm.PROPERTY_VENDOR, MediaDrm.PROPERTY_VERSION, MediaDrm.PROPERTY_DESCRIPTION, MediaDrm.PROPERTY_ALGORITHMS, "securityLevel", "systemId", "privacyMode", "sessionSharing", "usageReportingSupport", "appId", "origin", "hdcpLevel", "maxHdcpLevel", "maxNumberOfSessions", "numberOfOpenSessions"}; // String[] byteArrayProps = {MediaDrm.PROPERTY_DEVICE_UNIQUE_ID, "provisioningUniqueId", "serviceCertificate"}; // // Map<String, String> map = new LinkedHashMap<>(); // // for (String prop : stringProps) { // try { // map.put(prop, mediaDrm.getPropertyString(prop)); // } catch (Exception e) { // Log.d(TAG, "Invalid property " + prop); // } // } // for (String prop : byteArrayProps) { // try { // map.put(prop, Base64.encodeToString(mediaDrm.getPropertyByteArray(prop), Base64.NO_WRAP)); // } catch (Exception e) { // Log.d(TAG, "Invalid property " + prop); // } // } // // Log.d(TAG, "MediaDrm properties: " + map); // } // // @Nullable // static DrmInitData.SchemeInitData getWidevineInitData(@Nullable DrmInitData drmInitData) { // // if (drmInitData == null) { // Log.e(TAG, "No PSSH in media"); // return null; // } // // DrmInitData.SchemeInitData schemeInitData = drmInitData.get(WIDEVINE_UUID); // if (schemeInitData == null) { // Log.e(TAG, "No Widevine PSSH in media"); // return null; // } // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // // Prior to L the Widevine CDM required data to be extracted from the PSSH atom. // byte[] psshData = PsshAtomUtil.parseSchemeSpecificData(schemeInitData.data, WIDEVINE_UUID); // if (psshData == null) { // // Extraction failed. schemeData isn't a Widevine PSSH atom, so leave it unchanged. // } else { // schemeInitData = new DrmInitData.SchemeInitData(schemeInitData.mimeType, psshData); // } // } // return schemeInitData; // } // // static MediaDrmSession openSessionWithKeys(MediaDrm mediaDrm, OfflineKeySetStorage storage, byte[] initData) throws MediaDrmException, MediaCryptoException, FileNotFoundException { // // byte[] keySetId = storage.loadKeySetId(initData); // // MediaDrmSession session = MediaDrmSession.open(mediaDrm); // session.restoreKeys(keySetId); // // Map<String, String> keyStatus = session.queryKeyStatus(); // Log.d(TAG, "keyStatus: " + keyStatus); // // return session; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.media.MediaDrm; import android.os.Build; import android.util.Base64; import android.util.Log; import com.google.android.exoplayer.drm.DrmSessionManager; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerUtil; import com.google.android.libraries.mediaframework.exoplayerextensions.ExtendedMediaDrmCallback; import com.kaltura.playersdk.BuildConfig; import com.kaltura.playersdk.drm.OfflineDrmManager; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID;
synchronized (mLicenseLock) { // No uri? wait. if (mLicenseUri == null) { try { mLicenseLock.wait(MAX_LICENCE_URI_WAIT); } catch (InterruptedException e) { Log.d(TAG, "Interrupted", e); } } // Still no uri? throw. if (mLicenseUri == null) { throw new IllegalStateException("licenseUri cannot be null"); } // Execute request. byte[] response = ExoplayerUtil.executePost(mLicenseUri, request.getData(), headers); Log.d(TAG, "response data (b64): " + Base64.encodeToString(response, 0)); return response; } } public void setLicenseUri(String licenseUri) { synchronized (mLicenseLock) { mLicenseUri = licenseUri; // notify executeKeyRequest() that we have the license uri. mLicenseLock.notify(); } } @Override public DrmSessionManager getSessionManager() {
// Path: googlemediaframework/src/main/java/com/google/android/libraries/mediaframework/exoplayerextensions/ExtendedMediaDrmCallback.java // public interface ExtendedMediaDrmCallback extends MediaDrmCallback { // /** // * Optional DrmSessionManager. If not provided, the default (StreamingDrmSessionManager) is used. // * @return A DrmSessionManager, ready to be opened. // */ // DrmSessionManager getSessionManager(); // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/drm/OfflineDrmManager.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class OfflineDrmManager { // // private static final String TAG = "OfflineDrmManager"; // // // public static DrmSessionManager getSessionManager(Context context) { // try { // return new OfflineDrmSessionManager(getStorage(context)); // } catch (UnsupportedDrmException e) { // throw new WidevineNotSupportedException(e); // } // } // // public static OfflineKeySetStorage getStorage(Context context) { // return new OfflineKeySetStorage(context); // } // // // static void printAllProperties(MediaDrm mediaDrm) { // String[] stringProps = {MediaDrm.PROPERTY_VENDOR, MediaDrm.PROPERTY_VERSION, MediaDrm.PROPERTY_DESCRIPTION, MediaDrm.PROPERTY_ALGORITHMS, "securityLevel", "systemId", "privacyMode", "sessionSharing", "usageReportingSupport", "appId", "origin", "hdcpLevel", "maxHdcpLevel", "maxNumberOfSessions", "numberOfOpenSessions"}; // String[] byteArrayProps = {MediaDrm.PROPERTY_DEVICE_UNIQUE_ID, "provisioningUniqueId", "serviceCertificate"}; // // Map<String, String> map = new LinkedHashMap<>(); // // for (String prop : stringProps) { // try { // map.put(prop, mediaDrm.getPropertyString(prop)); // } catch (Exception e) { // Log.d(TAG, "Invalid property " + prop); // } // } // for (String prop : byteArrayProps) { // try { // map.put(prop, Base64.encodeToString(mediaDrm.getPropertyByteArray(prop), Base64.NO_WRAP)); // } catch (Exception e) { // Log.d(TAG, "Invalid property " + prop); // } // } // // Log.d(TAG, "MediaDrm properties: " + map); // } // // @Nullable // static DrmInitData.SchemeInitData getWidevineInitData(@Nullable DrmInitData drmInitData) { // // if (drmInitData == null) { // Log.e(TAG, "No PSSH in media"); // return null; // } // // DrmInitData.SchemeInitData schemeInitData = drmInitData.get(WIDEVINE_UUID); // if (schemeInitData == null) { // Log.e(TAG, "No Widevine PSSH in media"); // return null; // } // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // // Prior to L the Widevine CDM required data to be extracted from the PSSH atom. // byte[] psshData = PsshAtomUtil.parseSchemeSpecificData(schemeInitData.data, WIDEVINE_UUID); // if (psshData == null) { // // Extraction failed. schemeData isn't a Widevine PSSH atom, so leave it unchanged. // } else { // schemeInitData = new DrmInitData.SchemeInitData(schemeInitData.mimeType, psshData); // } // } // return schemeInitData; // } // // static MediaDrmSession openSessionWithKeys(MediaDrm mediaDrm, OfflineKeySetStorage storage, byte[] initData) throws MediaDrmException, MediaCryptoException, FileNotFoundException { // // byte[] keySetId = storage.loadKeySetId(initData); // // MediaDrmSession session = MediaDrmSession.open(mediaDrm); // session.restoreKeys(keySetId); // // Map<String, String> keyStatus = session.queryKeyStatus(); // Log.d(TAG, "keyStatus: " + keyStatus); // // return session; // } // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/players/KPlayerExoDrmCallback.java import android.annotation.TargetApi; import android.content.Context; import android.media.MediaDrm; import android.os.Build; import android.util.Base64; import android.util.Log; import com.google.android.exoplayer.drm.DrmSessionManager; import com.google.android.libraries.mediaframework.exoplayerextensions.ExoplayerUtil; import com.google.android.libraries.mediaframework.exoplayerextensions.ExtendedMediaDrmCallback; import com.kaltura.playersdk.BuildConfig; import com.kaltura.playersdk.drm.OfflineDrmManager; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; synchronized (mLicenseLock) { // No uri? wait. if (mLicenseUri == null) { try { mLicenseLock.wait(MAX_LICENCE_URI_WAIT); } catch (InterruptedException e) { Log.d(TAG, "Interrupted", e); } } // Still no uri? throw. if (mLicenseUri == null) { throw new IllegalStateException("licenseUri cannot be null"); } // Execute request. byte[] response = ExoplayerUtil.executePost(mLicenseUri, request.getData(), headers); Log.d(TAG, "response data (b64): " + Base64.encodeToString(response, 0)); return response; } } public void setLicenseUri(String licenseUri) { synchronized (mLicenseLock) { mLicenseUri = licenseUri; // notify executeKeyRequest() that we have the license uri. mLicenseLock.notify(); } } @Override public DrmSessionManager getSessionManager() {
return mOffline ? OfflineDrmManager.getSessionManager(mContext) : null;
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/helpers/CacheManager.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/utils/Utilities.java // public class Utilities { // // private static final String TAG = "Utilities"; // // public static boolean doesPackageExist(String targetPackage, Context context){ // List<ApplicationInfo> packages; // PackageManager pm; // pm = context.getPackageManager(); // packages = pm.getInstalledApplications(0); // // for (ApplicationInfo packageInfo : packages) { // if(packageInfo.packageName.equals(targetPackage)){ // return true; // } // } // // return false; // } // // public static String readAssetToString(Context context, String asset) { // try { // InputStream assetStream = context.getAssets().open(asset); // return fullyReadInputStream(assetStream, 1024*1024).toString(); // } catch (IOException e) { // LOGE(TAG, "Failed reading asset " + asset, e); // return null; // } // } // // @NonNull // public static ByteArrayOutputStream fullyReadInputStream(InputStream inputStream, int byteLimit) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // int maxCount = byteLimit - bos.size(); // if (count > maxCount) { // bos.write(data, 0, maxCount); // break; // } else { // bos.write(data, 0, count); // } // } // bos.flush(); // bos.close(); // inputStream.close(); // return bos; // } // // public static Uri stripLastUriPathSegment(Uri uri) { // String path = uri.getPath(); // if (TextUtils.isEmpty(path)) { // return uri; // } // path = stripLastPathSegment(path); // return uri.buildUpon().path(path).clearQuery().fragment(null).build(); // } // // public static String stripLastUriPathSegment(String uri) { // return stripLastUriPathSegment(Uri.parse(uri)).toString(); // } // // @NonNull // public static String stripLastPathSegment(String path) { // path = path.substring(0, path.lastIndexOf('/', path.length() - 2)); // return path; // } // // public static String loadStringFromURL(Uri url, int byteLimit) throws IOException { // HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection(); // conn.setRequestMethod("GET"); // conn.connect(); // InputStream is = conn.getInputStream(); // return fullyReadInputStream(is, byteLimit).toString(); // } // // public static boolean isOnline(Context context) { // ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); // return !(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()); // } // // public static void quietClose(Closeable... closeables) { // for (Closeable c : closeables) { // try { // if (c != null) { // c.close(); // } // } catch (Exception e) { // LOGE(TAG, "Failed closing " + c); // } // } // } // // public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // if (count > 0) { // outputStream.write(data, 0, count); // } // } // } // // public static String optString(JSONObject jsonObject, String key) { // return jsonObject.isNull(key) ? null : jsonObject.optString(key); // } // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // static public String md5(String string) { // return md5(string.getBytes()); // }
import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.webkit.WebResourceResponse; import com.kaltura.playersdk.utils.Utilities; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.kaltura.playersdk.helpers.KStringUtilities.md5; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE;
private void logCacheHit(Uri url, String fileId) { LOGD(TAG, "CACHE HIT: " + fileId + " : " + url); } private void logCacheMiss(Uri url, String fileId) { LOGD(TAG, "CACHE MISS: " + fileId + " : " + url); } private void logCacheIgnored(Uri url, String method) { LOGD(TAG, "CACHE IGNORE: " + method + " " + url); } private void logCacheSaved(Uri url, String fileId) { LOGD(TAG, "CACHE SAVED: " + fileId + " : " + url); } private void logCacheDeleted(String fileId) { LOGD(TAG, "CACHE DELETE: " + fileId); } public CacheManager(Context context) { mAppContext = context.getApplicationContext(); mFilesDir = mAppContext.getFilesDir(); mCachePath = mFilesDir + "/kaltura/"; File cacheDir = new File(mCachePath); if (!cacheDir.exists()) { cacheDir.mkdirs(); } mSQLHelper = new CacheSQLHelper(context);
// Path: playerSDK/src/main/java/com/kaltura/playersdk/utils/Utilities.java // public class Utilities { // // private static final String TAG = "Utilities"; // // public static boolean doesPackageExist(String targetPackage, Context context){ // List<ApplicationInfo> packages; // PackageManager pm; // pm = context.getPackageManager(); // packages = pm.getInstalledApplications(0); // // for (ApplicationInfo packageInfo : packages) { // if(packageInfo.packageName.equals(targetPackage)){ // return true; // } // } // // return false; // } // // public static String readAssetToString(Context context, String asset) { // try { // InputStream assetStream = context.getAssets().open(asset); // return fullyReadInputStream(assetStream, 1024*1024).toString(); // } catch (IOException e) { // LOGE(TAG, "Failed reading asset " + asset, e); // return null; // } // } // // @NonNull // public static ByteArrayOutputStream fullyReadInputStream(InputStream inputStream, int byteLimit) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // int maxCount = byteLimit - bos.size(); // if (count > maxCount) { // bos.write(data, 0, maxCount); // break; // } else { // bos.write(data, 0, count); // } // } // bos.flush(); // bos.close(); // inputStream.close(); // return bos; // } // // public static Uri stripLastUriPathSegment(Uri uri) { // String path = uri.getPath(); // if (TextUtils.isEmpty(path)) { // return uri; // } // path = stripLastPathSegment(path); // return uri.buildUpon().path(path).clearQuery().fragment(null).build(); // } // // public static String stripLastUriPathSegment(String uri) { // return stripLastUriPathSegment(Uri.parse(uri)).toString(); // } // // @NonNull // public static String stripLastPathSegment(String path) { // path = path.substring(0, path.lastIndexOf('/', path.length() - 2)); // return path; // } // // public static String loadStringFromURL(Uri url, int byteLimit) throws IOException { // HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection(); // conn.setRequestMethod("GET"); // conn.connect(); // InputStream is = conn.getInputStream(); // return fullyReadInputStream(is, byteLimit).toString(); // } // // public static boolean isOnline(Context context) { // ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); // return !(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()); // } // // public static void quietClose(Closeable... closeables) { // for (Closeable c : closeables) { // try { // if (c != null) { // c.close(); // } // } catch (Exception e) { // LOGE(TAG, "Failed closing " + c); // } // } // } // // public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // if (count > 0) { // outputStream.write(data, 0, count); // } // } // } // // public static String optString(JSONObject jsonObject, String key) { // return jsonObject.isNull(key) ? null : jsonObject.optString(key); // } // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // static public String md5(String string) { // return md5(string.getBytes()); // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/CacheManager.java import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.webkit.WebResourceResponse; import com.kaltura.playersdk.utils.Utilities; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.kaltura.playersdk.helpers.KStringUtilities.md5; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE; private void logCacheHit(Uri url, String fileId) { LOGD(TAG, "CACHE HIT: " + fileId + " : " + url); } private void logCacheMiss(Uri url, String fileId) { LOGD(TAG, "CACHE MISS: " + fileId + " : " + url); } private void logCacheIgnored(Uri url, String method) { LOGD(TAG, "CACHE IGNORE: " + method + " " + url); } private void logCacheSaved(Uri url, String fileId) { LOGD(TAG, "CACHE SAVED: " + fileId + " : " + url); } private void logCacheDeleted(String fileId) { LOGD(TAG, "CACHE DELETE: " + fileId); } public CacheManager(Context context) { mAppContext = context.getApplicationContext(); mFilesDir = mAppContext.getFilesDir(); mCachePath = mFilesDir + "/kaltura/"; File cacheDir = new File(mCachePath); if (!cacheDir.exists()) { cacheDir.mkdirs(); } mSQLHelper = new CacheSQLHelper(context);
String string = Utilities.readAssetToString(mAppContext, CACHED_STRINGS_JSON);
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/helpers/CacheManager.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/utils/Utilities.java // public class Utilities { // // private static final String TAG = "Utilities"; // // public static boolean doesPackageExist(String targetPackage, Context context){ // List<ApplicationInfo> packages; // PackageManager pm; // pm = context.getPackageManager(); // packages = pm.getInstalledApplications(0); // // for (ApplicationInfo packageInfo : packages) { // if(packageInfo.packageName.equals(targetPackage)){ // return true; // } // } // // return false; // } // // public static String readAssetToString(Context context, String asset) { // try { // InputStream assetStream = context.getAssets().open(asset); // return fullyReadInputStream(assetStream, 1024*1024).toString(); // } catch (IOException e) { // LOGE(TAG, "Failed reading asset " + asset, e); // return null; // } // } // // @NonNull // public static ByteArrayOutputStream fullyReadInputStream(InputStream inputStream, int byteLimit) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // int maxCount = byteLimit - bos.size(); // if (count > maxCount) { // bos.write(data, 0, maxCount); // break; // } else { // bos.write(data, 0, count); // } // } // bos.flush(); // bos.close(); // inputStream.close(); // return bos; // } // // public static Uri stripLastUriPathSegment(Uri uri) { // String path = uri.getPath(); // if (TextUtils.isEmpty(path)) { // return uri; // } // path = stripLastPathSegment(path); // return uri.buildUpon().path(path).clearQuery().fragment(null).build(); // } // // public static String stripLastUriPathSegment(String uri) { // return stripLastUriPathSegment(Uri.parse(uri)).toString(); // } // // @NonNull // public static String stripLastPathSegment(String path) { // path = path.substring(0, path.lastIndexOf('/', path.length() - 2)); // return path; // } // // public static String loadStringFromURL(Uri url, int byteLimit) throws IOException { // HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection(); // conn.setRequestMethod("GET"); // conn.connect(); // InputStream is = conn.getInputStream(); // return fullyReadInputStream(is, byteLimit).toString(); // } // // public static boolean isOnline(Context context) { // ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); // return !(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()); // } // // public static void quietClose(Closeable... closeables) { // for (Closeable c : closeables) { // try { // if (c != null) { // c.close(); // } // } catch (Exception e) { // LOGE(TAG, "Failed closing " + c); // } // } // } // // public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // if (count > 0) { // outputStream.write(data, 0, count); // } // } // } // // public static String optString(JSONObject jsonObject, String key) { // return jsonObject.isNull(key) ? null : jsonObject.optString(key); // } // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // static public String md5(String string) { // return md5(string.getBytes()); // }
import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.webkit.WebResourceResponse; import com.kaltura.playersdk.utils.Utilities; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.kaltura.playersdk.helpers.KStringUtilities.md5; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE;
@Override public void streamClosed(long fileSize, String filePath) { int trimLength = mCachePath.length(); String fileId = filePath.substring(trimLength); mSQLHelper.updateFileSize(fileId, fileSize); logCacheSaved(requestUrl, fileId); deleteLessUsedFiles(fileSize); connection.disconnect(); } }); return webResourceResponse(contentType, encoding, inputStream); } finally { // if inputStream wasn't created, streamClosed() will not get called and the connection may leak. if (inputStream == null) { connection.disconnect(); } } } @NonNull private static WebResourceResponse webResourceResponse(String contentType, String encoding, InputStream inputStream) { return new WebResourceResponse(contentType, encoding, inputStream); } @NonNull private String getCacheFileId(Uri requestUrl) { if (requestUrl.getFragment() != null) { String localContentId = getLocalContentId(requestUrl); if (!TextUtils.isEmpty(localContentId)) {
// Path: playerSDK/src/main/java/com/kaltura/playersdk/utils/Utilities.java // public class Utilities { // // private static final String TAG = "Utilities"; // // public static boolean doesPackageExist(String targetPackage, Context context){ // List<ApplicationInfo> packages; // PackageManager pm; // pm = context.getPackageManager(); // packages = pm.getInstalledApplications(0); // // for (ApplicationInfo packageInfo : packages) { // if(packageInfo.packageName.equals(targetPackage)){ // return true; // } // } // // return false; // } // // public static String readAssetToString(Context context, String asset) { // try { // InputStream assetStream = context.getAssets().open(asset); // return fullyReadInputStream(assetStream, 1024*1024).toString(); // } catch (IOException e) { // LOGE(TAG, "Failed reading asset " + asset, e); // return null; // } // } // // @NonNull // public static ByteArrayOutputStream fullyReadInputStream(InputStream inputStream, int byteLimit) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // int maxCount = byteLimit - bos.size(); // if (count > maxCount) { // bos.write(data, 0, maxCount); // break; // } else { // bos.write(data, 0, count); // } // } // bos.flush(); // bos.close(); // inputStream.close(); // return bos; // } // // public static Uri stripLastUriPathSegment(Uri uri) { // String path = uri.getPath(); // if (TextUtils.isEmpty(path)) { // return uri; // } // path = stripLastPathSegment(path); // return uri.buildUpon().path(path).clearQuery().fragment(null).build(); // } // // public static String stripLastUriPathSegment(String uri) { // return stripLastUriPathSegment(Uri.parse(uri)).toString(); // } // // @NonNull // public static String stripLastPathSegment(String path) { // path = path.substring(0, path.lastIndexOf('/', path.length() - 2)); // return path; // } // // public static String loadStringFromURL(Uri url, int byteLimit) throws IOException { // HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection(); // conn.setRequestMethod("GET"); // conn.connect(); // InputStream is = conn.getInputStream(); // return fullyReadInputStream(is, byteLimit).toString(); // } // // public static boolean isOnline(Context context) { // ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); // return !(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()); // } // // public static void quietClose(Closeable... closeables) { // for (Closeable c : closeables) { // try { // if (c != null) { // c.close(); // } // } catch (Exception e) { // LOGE(TAG, "Failed closing " + c); // } // } // } // // public static void copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { // byte data[] = new byte[1024]; // int count; // // while ((count = inputStream.read(data)) != -1) { // if (count > 0) { // outputStream.write(data, 0, count); // } // } // } // // public static String optString(JSONObject jsonObject, String key) { // return jsonObject.isNull(key) ? null : jsonObject.optString(key); // } // } // // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/KStringUtilities.java // static public String md5(String string) { // return md5(string.getBytes()); // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/helpers/CacheManager.java import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.text.TextUtils; import android.webkit.WebResourceResponse; import com.kaltura.playersdk.utils.Utilities; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.kaltura.playersdk.helpers.KStringUtilities.md5; import static com.kaltura.playersdk.utils.LogUtils.LOGD; import static com.kaltura.playersdk.utils.LogUtils.LOGE; @Override public void streamClosed(long fileSize, String filePath) { int trimLength = mCachePath.length(); String fileId = filePath.substring(trimLength); mSQLHelper.updateFileSize(fileId, fileSize); logCacheSaved(requestUrl, fileId); deleteLessUsedFiles(fileSize); connection.disconnect(); } }); return webResourceResponse(contentType, encoding, inputStream); } finally { // if inputStream wasn't created, streamClosed() will not get called and the connection may leak. if (inputStream == null) { connection.disconnect(); } } } @NonNull private static WebResourceResponse webResourceResponse(String contentType, String encoding, InputStream inputStream) { return new WebResourceResponse(contentType, encoding, inputStream); } @NonNull private String getCacheFileId(Uri requestUrl) { if (requestUrl.getFragment() != null) { String localContentId = getLocalContentId(requestUrl); if (!TextUtils.isEmpty(localContentId)) {
return md5("contentId:" + localContentId);
kaltura/player-sdk-native-android
playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KCastProvider.java
// Path: playerSDK/src/main/java/com/kaltura/playersdk/casting/KCastDevice.java // public class KCastDevice { // private String routerName; // private String modelName; // private String deviceVersion; // private String routerId; // // public KCastDevice(MediaRouter.RouteInfo info) { // routerName = info.getName(); // routerId = info.getId(); // } // // public KCastDevice(CastDevice castDevice) { // routerName = castDevice.getFriendlyName(); // modelName = castDevice.getModelName(); // deviceVersion = castDevice.getDeviceVersion(); // routerId = castDevice.getDeviceId(); // } // // public String getRouterName() { // return routerName; // } // // public void setRouterName(String routerName) { // this.routerName = routerName; // } // // public String getRouterId() { // return routerId; // } // // public void setRouterId(String routerId) { // this.routerId = routerId; // } // // public String getModelName() { // return modelName; // } // // public void setModelName(String modelName) { // this.modelName = modelName; // } // // public String getDeviceVersion() { // return deviceVersion; // } // // public void setDeviceVersion(String deviceVersion) { // this.deviceVersion = deviceVersion; // } // // @Override // public String toString() { // return routerName; // } // }
import android.content.Context; import com.kaltura.playersdk.casting.KCastDevice;
package com.kaltura.playersdk.interfaces; /** * Created by nissimpardo on 29/05/16. */ public interface KCastProvider { void init(Context context); void startReceiver(Context context, boolean guestModeEnabled); void startReceiver(Context context); void showLogo(); void hideLogo(); void disconnectFromCastDevice();
// Path: playerSDK/src/main/java/com/kaltura/playersdk/casting/KCastDevice.java // public class KCastDevice { // private String routerName; // private String modelName; // private String deviceVersion; // private String routerId; // // public KCastDevice(MediaRouter.RouteInfo info) { // routerName = info.getName(); // routerId = info.getId(); // } // // public KCastDevice(CastDevice castDevice) { // routerName = castDevice.getFriendlyName(); // modelName = castDevice.getModelName(); // deviceVersion = castDevice.getDeviceVersion(); // routerId = castDevice.getDeviceId(); // } // // public String getRouterName() { // return routerName; // } // // public void setRouterName(String routerName) { // this.routerName = routerName; // } // // public String getRouterId() { // return routerId; // } // // public void setRouterId(String routerId) { // this.routerId = routerId; // } // // public String getModelName() { // return modelName; // } // // public void setModelName(String modelName) { // this.modelName = modelName; // } // // public String getDeviceVersion() { // return deviceVersion; // } // // public void setDeviceVersion(String deviceVersion) { // this.deviceVersion = deviceVersion; // } // // @Override // public String toString() { // return routerName; // } // } // Path: playerSDK/src/main/java/com/kaltura/playersdk/interfaces/KCastProvider.java import android.content.Context; import com.kaltura.playersdk.casting.KCastDevice; package com.kaltura.playersdk.interfaces; /** * Created by nissimpardo on 29/05/16. */ public interface KCastProvider { void init(Context context); void startReceiver(Context context, boolean guestModeEnabled); void startReceiver(Context context); void showLogo(); void hideLogo(); void disconnectFromCastDevice();
KCastDevice getSelectedCastDevice();
NessComputing/components-ness-httpclient
client/src/test/java/com/nesscomputing/httpclient/testsupport/StringResponseConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/response/ContentConverter.java // public interface ContentConverter<T> // { // /** // * Called when the ContentResponseHandler wants to convert an input stream // * into a response object. Calling this method does *not* imply a 2xx response code, // * this method will be called for all response codes if no error occurs while processing // * the response. // * // * @param response The response object from the Http client. // * @param inputStream The response body as stream. // * @return The result object. Can be null. // * @throws IOException // */ // T convert(HttpClientResponse response, InputStream inputStream) throws IOException; // // /** // * Called if an exception occured while trying to convert the response data stream // * into a response object. // * // * @param response The response object from the Http client. // * @param ex Exception triggering this call. // * @return A response object or null. // * @throws IOException // */ // T handleError(HttpClientResponse response, IOException ex) throws IOException; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import java.io.IOException; import java.io.InputStream; import javax.annotation.concurrent.Immutable; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.junit.Assert; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.response.ContentConverter;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; @Immutable public class StringResponseConverter implements ContentConverter<String> { private final int responseCode; public StringResponseConverter() { this(HttpServletResponse.SC_OK); } public StringResponseConverter(final int responseCode) { this.responseCode = responseCode; } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/response/ContentConverter.java // public interface ContentConverter<T> // { // /** // * Called when the ContentResponseHandler wants to convert an input stream // * into a response object. Calling this method does *not* imply a 2xx response code, // * this method will be called for all response codes if no error occurs while processing // * the response. // * // * @param response The response object from the Http client. // * @param inputStream The response body as stream. // * @return The result object. Can be null. // * @throws IOException // */ // T convert(HttpClientResponse response, InputStream inputStream) throws IOException; // // /** // * Called if an exception occured while trying to convert the response data stream // * into a response object. // * // * @param response The response object from the Http client. // * @param ex Exception triggering this call. // * @return A response object or null. // * @throws IOException // */ // T handleError(HttpClientResponse response, IOException ex) throws IOException; // } // Path: client/src/test/java/com/nesscomputing/httpclient/testsupport/StringResponseConverter.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import java.io.IOException; import java.io.InputStream; import javax.annotation.concurrent.Immutable; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.junit.Assert; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.response.ContentConverter; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; @Immutable public class StringResponseConverter implements ContentConverter<String> { private final int responseCode; public StringResponseConverter() { this(HttpServletResponse.SC_OK); } public StringResponseConverter(final int responseCode) { this.responseCode = responseCode; } @Override
public String convert(final HttpClientResponse response, final InputStream inputStream)
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/StringContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import javax.annotation.concurrent.Immutable; import com.google.common.base.Objects; import com.google.common.io.CharStreams; import com.google.common.io.Closeables;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * A basic implementation of ContentConverter when you only want a string back. */ @Immutable public class StringContentConverter extends AbstractErrorHandlingContentConverter<String> { public static final ContentConverter<String> DEFAULT_CONVERTER = new StringContentConverter(); public static final ContentConverter<String> DEFAULT_404OK_CONVERTER = new StringContentConverter(true); public static final ContentResponseHandler<String> DEFAULT_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_CONVERTER); public static final ContentResponseHandler<String> DEFAULT_404OK_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_404OK_CONVERTER); private final boolean ignore404; protected StringContentConverter() { this(false); } protected StringContentConverter(final boolean ignore404) { this.ignore404 = ignore404; } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/StringContentConverter.java import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import javax.annotation.concurrent.Immutable; import com.google.common.base.Objects; import com.google.common.io.CharStreams; import com.google.common.io.Closeables; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * A basic implementation of ContentConverter when you only want a string back. */ @Immutable public class StringContentConverter extends AbstractErrorHandlingContentConverter<String> { public static final ContentConverter<String> DEFAULT_CONVERTER = new StringContentConverter(); public static final ContentConverter<String> DEFAULT_404OK_CONVERTER = new StringContentConverter(true); public static final ContentResponseHandler<String> DEFAULT_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_CONVERTER); public static final ContentResponseHandler<String> DEFAULT_404OK_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_404OK_CONVERTER); private final boolean ignore404; protected StringContentConverter() { this(false); } protected StringContentConverter(final boolean ignore404) { this.ignore404 = ignore404; } @Override
public String convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/NumberContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.google.common.io.CharStreams; import com.google.common.io.Closeables; import static java.lang.String.format; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.nio.charset.Charset; import javax.annotation.concurrent.Immutable; import com.google.common.base.Objects; import com.google.common.base.Throwables;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * A basic implementation of ContentConverter that returns a number. */ @Immutable public class NumberContentConverter<T extends Number> extends AbstractErrorHandlingContentConverter<T> { public static <N extends Number> ContentResponseHandler<N> getResponseHandler(final Class<N> numberClass, final boolean ignore404) { return ContentResponseHandler.forConverter(getConverter(numberClass, ignore404)); } public static <N extends Number> ContentConverter<N> getConverter(final Class<N> numberClass, final boolean ignore404) { return new NumberContentConverter<N>(numberClass, ignore404); } private static final Log LOG = Log.findLog(); private final boolean ignore404; private final Class<T> numberClass; private final Method valueOfMethod; private final T emptyValue; protected NumberContentConverter(final Class<T> numberClass, final boolean ignore404) { try { this.numberClass = numberClass; this.ignore404 = ignore404; this.valueOfMethod = numberClass.getMethod("valueOf", String.class); this.emptyValue = numberClass.cast(safeInvoke("0")); } catch (NoSuchMethodException nsme) { throw Throwables.propagate(nsme); } } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/NumberContentConverter.java import com.google.common.io.CharStreams; import com.google.common.io.Closeables; import static java.lang.String.format; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.nio.charset.Charset; import javax.annotation.concurrent.Immutable; import com.google.common.base.Objects; import com.google.common.base.Throwables; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * A basic implementation of ContentConverter that returns a number. */ @Immutable public class NumberContentConverter<T extends Number> extends AbstractErrorHandlingContentConverter<T> { public static <N extends Number> ContentResponseHandler<N> getResponseHandler(final Class<N> numberClass, final boolean ignore404) { return ContentResponseHandler.forConverter(getConverter(numberClass, ignore404)); } public static <N extends Number> ContentConverter<N> getConverter(final Class<N> numberClass, final boolean ignore404) { return new NumberContentConverter<N>(numberClass, ignore404); } private static final Log LOG = Log.findLog(); private final boolean ignore404; private final Class<T> numberClass; private final Method valueOfMethod; private final T emptyValue; protected NumberContentConverter(final Class<T> numberClass, final boolean ignore404) { try { this.numberClass = numberClass; this.ignore404 = ignore404; this.valueOfMethod = numberClass.getMethod("valueOf", String.class); this.emptyValue = numberClass.cast(safeInvoke("0")); } catch (NoSuchMethodException nsme) { throw Throwables.propagate(nsme); } } @Override
public T convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/Valid2xxContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import javax.annotation.concurrent.Immutable;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Returns true for a 200/201/204 response code, false otherwise. Can be set to explode if response code != 200/201/204. */ @Immutable public class Valid2xxContentConverter extends AbstractErrorHandlingContentConverter<Boolean> { public static final Valid2xxContentConverter DEFAULT_CONVERTER = new Valid2xxContentConverter(false); public static final Valid2xxContentConverter DEFAULT_FAILING_CONVERTER = new Valid2xxContentConverter(true); public static final Valid2xxContentConverter DEFAULT_404OK_CONVERTER = new Valid2xxContentConverter(true, true); public static final ContentResponseHandler<Boolean> DEFAULT_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_CONVERTER); public static final ContentResponseHandler<Boolean> DEFAULT_FAILING_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_FAILING_CONVERTER); public static final ContentResponseHandler<Boolean> DEFAULT_404OK_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_404OK_CONVERTER); private final boolean failOnError; private final boolean ignore404; protected Valid2xxContentConverter(final boolean failOnError) { this(failOnError, false); } protected Valid2xxContentConverter(final boolean failOnError, final boolean ignore404) { this.failOnError = failOnError; this.ignore404 = ignore404; } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/Valid2xxContentConverter.java import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import javax.annotation.concurrent.Immutable; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Returns true for a 200/201/204 response code, false otherwise. Can be set to explode if response code != 200/201/204. */ @Immutable public class Valid2xxContentConverter extends AbstractErrorHandlingContentConverter<Boolean> { public static final Valid2xxContentConverter DEFAULT_CONVERTER = new Valid2xxContentConverter(false); public static final Valid2xxContentConverter DEFAULT_FAILING_CONVERTER = new Valid2xxContentConverter(true); public static final Valid2xxContentConverter DEFAULT_404OK_CONVERTER = new Valid2xxContentConverter(true, true); public static final ContentResponseHandler<Boolean> DEFAULT_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_CONVERTER); public static final ContentResponseHandler<Boolean> DEFAULT_FAILING_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_FAILING_CONVERTER); public static final ContentResponseHandler<Boolean> DEFAULT_404OK_RESPONSE_HANDLER = ContentResponseHandler.forConverter(DEFAULT_404OK_CONVERTER); private final boolean failOnError; private final boolean ignore404; protected Valid2xxContentConverter(final boolean failOnError) { this(failOnError, false); } protected Valid2xxContentConverter(final boolean failOnError, final boolean ignore404) { this.failOnError = failOnError; this.ignore404 = ignore404; } @Override
public Boolean convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/HttpResponseContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import org.apache.commons.io.IOUtils; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * ContentConverter implementation that exposes the response directly. */ public class HttpResponseContentConverter implements ContentConverter<HttpResponse> { @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/HttpResponseContentConverter.java import org.apache.commons.io.IOUtils; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.HttpClientResponse; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * ContentConverter implementation that exposes the response directly. */ public class HttpResponseContentConverter implements ContentConverter<HttpResponse> { @Override
public HttpResponse convert(HttpClientResponse response, InputStream inputStream) throws IOException {
NessComputing/components-ness-httpclient
client/src/test/java/com/nesscomputing/httpclient/factory/httpclient4/ApacheHttpClientAccess.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientObserver.java // public abstract class HttpClientObserver { // // /** // * Called when a request was submitted to the client. Interception allows setting of // * headers by wrapping the request passed in (using HttpClientRequest.Builder#fromRequest). // */ // public <RequestType> HttpClientRequest<RequestType> onRequestSubmitted(final HttpClientRequest<RequestType> request) // throws IOException // { // return request; // } // // /** // * Inspect the incoming response. Called after the HTTP headers have been received, // * but before the response handler has been invoked. The response may be inspected, however // * consuming the response body (via {@link HttpClientResponse#getResponseBodyAsStream()}) would // * likely break things spectacularly. // */ // public HttpClientResponse onResponseReceived(final HttpClientResponse response) // throws IOException // { // return response; // } // }
import java.util.Set; import com.nesscomputing.httpclient.HttpClientObserver;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.factory.httpclient4; public class ApacheHttpClientAccess {
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientObserver.java // public abstract class HttpClientObserver { // // /** // * Called when a request was submitted to the client. Interception allows setting of // * headers by wrapping the request passed in (using HttpClientRequest.Builder#fromRequest). // */ // public <RequestType> HttpClientRequest<RequestType> onRequestSubmitted(final HttpClientRequest<RequestType> request) // throws IOException // { // return request; // } // // /** // * Inspect the incoming response. Called after the HTTP headers have been received, // * but before the response handler has been invoked. The response may be inspected, however // * consuming the response body (via {@link HttpClientResponse#getResponseBodyAsStream()}) would // * likely break things spectacularly. // */ // public HttpClientResponse onResponseReceived(final HttpClientResponse response) // throws IOException // { // return response; // } // } // Path: client/src/test/java/com/nesscomputing/httpclient/factory/httpclient4/ApacheHttpClientAccess.java import java.util.Set; import com.nesscomputing.httpclient.HttpClientObserver; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.factory.httpclient4; public class ApacheHttpClientAccess {
public static Set<? extends HttpClientObserver> getObservers(ApacheHttpClient4Factory factory)
NessComputing/components-ness-httpclient
client/src/test/java/com/nesscomputing/httpclient/response/TestStreamedJsonContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackCollector; import com.nesscomputing.callback.CallbackRefusedException; import com.nesscomputing.httpclient.HttpClientResponse; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.easymock.EasyMock; import org.junit.Test;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; public class TestStreamedJsonContentConverter { private static final TypeReference<Integer> INT_TYPE_REF = new TypeReference<Integer>() {}; public static final String TEST_JSON = "{\"results\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \"success\":true}"; public static final String EMPTY_JSON = "{\"results\": [], \"success\":true}"; private final ObjectMapper mapper = new ObjectMapper(); private static InputStream inputStream(String json) { return new ByteArrayInputStream(json.getBytes(Charsets.UTF_8)); }
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/test/java/com/nesscomputing/httpclient/response/TestStreamedJsonContentConverter.java import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackCollector; import com.nesscomputing.callback.CallbackRefusedException; import com.nesscomputing.httpclient.HttpClientResponse; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.easymock.EasyMock; import org.junit.Test; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; public class TestStreamedJsonContentConverter { private static final TypeReference<Integer> INT_TYPE_REF = new TypeReference<Integer>() {}; public static final String TEST_JSON = "{\"results\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], \"success\":true}"; public static final String EMPTY_JSON = "{\"results\": [], \"success\":true}"; private final ObjectMapper mapper = new ObjectMapper(); private static InputStream inputStream(String json) { return new ByteArrayInputStream(json.getBytes(Charsets.UTF_8)); }
private static HttpClientResponse response(int status)
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/InternalCredentialsProvider.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientAuthProvider.java // public interface HttpClientAuthProvider // { // /** // * Called by the HttpClient for checking authentication information. Should return true if the // * provided authentication parameters are deemed sufficient by the implementation. HttpClient // * will then use the getters to retrieve exact authentication information, login and password. // * // * @param authScheme The authentication scheme used. E.g. "BASIC" or "DIGEST". // * @param authHost The host requesting authentication. // * @param authPort Port for the requesting host. // * @param authRealm The authentication realm presented by the host. // * @return True If the implementation accepts the authentication. // * // */ // boolean acceptRequest(String authScheme, String authHost, int authPort, String authRealm); // // /** // * Return the accepted scheme. Can be null, then any scheme is accepted. // */ // String getScheme(); // // /** // * Return the accepted host. Can be null, then any host is accepted. // */ // String getHost(); // // /** // * Return the accepted port. Can be -1, then any port is accepted. // */ // int getPort(); // // /** // * Return the accepted realm. Can be null, then any realm is accepted. // */ // String getRealm(); // // /** // * Return an user name to present to the remote host. // */ // String getUser(); // // /** // * Return a password to present to the remote host. // */ // String getPassword(); // }
import java.security.Principal; import java.util.List; import org.apache.http.auth.AuthScope; import org.apache.http.auth.BasicUserPrincipal; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import com.nesscomputing.httpclient.HttpClientAuthProvider;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.factory.httpclient4; /** * An Apache Httpclient credentials provider that uses the internal structures of the tc-httpclient to provide * credentials. * */ public class InternalCredentialsProvider implements CredentialsProvider {
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientAuthProvider.java // public interface HttpClientAuthProvider // { // /** // * Called by the HttpClient for checking authentication information. Should return true if the // * provided authentication parameters are deemed sufficient by the implementation. HttpClient // * will then use the getters to retrieve exact authentication information, login and password. // * // * @param authScheme The authentication scheme used. E.g. "BASIC" or "DIGEST". // * @param authHost The host requesting authentication. // * @param authPort Port for the requesting host. // * @param authRealm The authentication realm presented by the host. // * @return True If the implementation accepts the authentication. // * // */ // boolean acceptRequest(String authScheme, String authHost, int authPort, String authRealm); // // /** // * Return the accepted scheme. Can be null, then any scheme is accepted. // */ // String getScheme(); // // /** // * Return the accepted host. Can be null, then any host is accepted. // */ // String getHost(); // // /** // * Return the accepted port. Can be -1, then any port is accepted. // */ // int getPort(); // // /** // * Return the accepted realm. Can be null, then any realm is accepted. // */ // String getRealm(); // // /** // * Return an user name to present to the remote host. // */ // String getUser(); // // /** // * Return a password to present to the remote host. // */ // String getPassword(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/InternalCredentialsProvider.java import java.security.Principal; import java.util.List; import org.apache.http.auth.AuthScope; import org.apache.http.auth.BasicUserPrincipal; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import com.nesscomputing.httpclient.HttpClientAuthProvider; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.factory.httpclient4; /** * An Apache Httpclient credentials provider that uses the internal structures of the tc-httpclient to provide * credentials. * */ public class InternalCredentialsProvider implements CredentialsProvider {
private final List<HttpClientAuthProvider> authProviders;
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // }
import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> {
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // } // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> {
private final HttpClientFactory httpClientFactory;
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // }
import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory;
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // } // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory;
private final HttpClientMethod httpMethod;
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // }
import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory; private final HttpClientMethod httpMethod; private final URI url; private final HttpClientResponseHandler<T> httpHandler;
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // } // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory; private final HttpClientMethod httpMethod; private final URI url; private final HttpClientResponseHandler<T> httpHandler;
private List<HttpClientHeader> headers = Collections.emptyList();
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // }
import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory; private final HttpClientMethod httpMethod; private final URI url; private final HttpClientResponseHandler<T> httpHandler; private List<HttpClientHeader> headers = Collections.emptyList(); private List<Cookie> cookies = Collections.emptyList(); private Map<String, Object> parameters = Collections.emptyMap(); private String virtualHost = null; private int virtualPort = -1;
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientBodySource.java // public interface HttpClientBodySource // { // void setContentType(String contentType); // // void setContentEncoding(String contentEncoding); // // InputStream getContent() throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientFactory.java // public interface HttpClientFactory // { // /** // * Start the Factory. Must be called before any other method can be used. // */ // void start(); // // /** // * Stop the Factory. Should free all resources and shut down all connections. After stop() has been called, // * the factory should throw exceptions on all related method calls. // */ // void stop(); // // /** // * True if the start() method was invoked successfully. // */ // boolean isStarted(); // // /** // * True if the stop() method was invoked successfully. // */ // boolean isStopped(); // // /** // * @return a {@link HttpClientConnectionContext} object to modify settings for this factory. // */ // HttpClientConnectionContext getConnectionContext(); // // /** // * For requests that accept a body, generate a {@link HttpClientBodySource} object that wraps // * the content object. Can return null if no appropriate body source is available. // */ // @CheckForNull // HttpClientBodySource getHttpBodySourceFor(Object content); // // /** // * Execute a request to a remote server. // */ // <T> T performRequest(HttpClientRequest<T> request) throws IOException; // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // // Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientMethod.java // public enum HttpClientMethod // { // GET, POST, PUT, DELETE, HEAD, OPTIONS; // } // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientRequest.java import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.servlet.http.Cookie; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientFactory; import com.nesscomputing.httpclient.internal.HttpClientHeader; import com.nesscomputing.httpclient.internal.HttpClientMethod; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient; /** * A request to a remote server. Composed step-by-step using a builder. */ public class HttpClientRequest<T> { private final HttpClientFactory httpClientFactory; private final HttpClientMethod httpMethod; private final URI url; private final HttpClientResponseHandler<T> httpHandler; private List<HttpClientHeader> headers = Collections.emptyList(); private List<Cookie> cookies = Collections.emptyList(); private Map<String, Object> parameters = Collections.emptyMap(); private String virtualHost = null; private int virtualPort = -1;
private HttpClientBodySource httpBodySource = null;
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/JsonContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log;
{ return new JsonContentConverter<Type>(typeReference, objectMapper); } public static <CC> ContentResponseHandler<CC> getResponseHandler(final TypeReference<CC> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { return ContentResponseHandler.forConverter(getConverter(typeReference, objectMapper, ignore404)); } public static <Type> ContentConverter<Type> getConverter(final TypeReference<Type> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { return new JsonContentConverter<Type>(typeReference, objectMapper, ignore404); } public JsonContentConverter(final TypeReference<T> typeReference, final ObjectMapper objectMapper) { this(typeReference, objectMapper, false); } public JsonContentConverter(final TypeReference<T> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { this.typeReference = typeReference; this.objectMapper = objectMapper; this.ignore404 = ignore404; } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/JsonContentConverter.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log; { return new JsonContentConverter<Type>(typeReference, objectMapper); } public static <CC> ContentResponseHandler<CC> getResponseHandler(final TypeReference<CC> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { return ContentResponseHandler.forConverter(getConverter(typeReference, objectMapper, ignore404)); } public static <Type> ContentConverter<Type> getConverter(final TypeReference<Type> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { return new JsonContentConverter<Type>(typeReference, objectMapper, ignore404); } public JsonContentConverter(final TypeReference<T> typeReference, final ObjectMapper objectMapper) { this(typeReference, objectMapper, false); } public JsonContentConverter(final TypeReference<T> typeReference, final ObjectMapper objectMapper, final boolean ignore404) { this.typeReference = typeReference; this.objectMapper = objectMapper; this.ignore404 = ignore404; } @Override
public T convert(final HttpClientResponse httpClientResponse,
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/RedirectedException.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.nesscomputing.httpclient.HttpClientResponse;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Indicates a redirection response from a server. */ public class RedirectedException extends RuntimeException { private static final long serialVersionUID = 1L; private final int statusCode; private final String url; /** * Creates a new Redirection execption. */ public RedirectedException(final int statusCode, final String url) { super(); this.statusCode = statusCode; this.url = url; } /** * Creates a new Redirection execption with message. */ public RedirectedException(final int statusCode, final String url, final String message) { super(message); this.statusCode = statusCode; this.url = url; } /** * Creates a new Redirection execption from a {@link HttpClientResponse}. */
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/RedirectedException.java import com.nesscomputing.httpclient.HttpClientResponse; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Indicates a redirection response from a server. */ public class RedirectedException extends RuntimeException { private static final long serialVersionUID = 1L; private final int statusCode; private final String url; /** * Creates a new Redirection execption. */ public RedirectedException(final int statusCode, final String url) { super(); this.statusCode = statusCode; this.url = url; } /** * Creates a new Redirection execption with message. */ public RedirectedException(final int statusCode, final String url, final String message) { super(message); this.statusCode = statusCode; this.url = url; } /** * Creates a new Redirection execption from a {@link HttpClientResponse}. */
public RedirectedException(final HttpClientResponse response)
NessComputing/components-ness-httpclient
client/src/test/java/com/nesscomputing/httpclient/testsupport/GenericReadingHandler.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // }
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import com.nesscomputing.httpclient.internal.HttpClientHeader;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; public class GenericReadingHandler extends AbstractHandler { private String content = ""; private String contentType = "text/html";
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // Path: client/src/test/java/com/nesscomputing/httpclient/testsupport/GenericReadingHandler.java import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import com.nesscomputing.httpclient.internal.HttpClientHeader; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; public class GenericReadingHandler extends AbstractHandler { private String content = ""; private String contentType = "text/html";
private List<HttpClientHeader> headers = new ArrayList<HttpClientHeader>();
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/ContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import java.io.IOException; import java.io.InputStream; import com.nesscomputing.httpclient.HttpClientResponse;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Convert an Input Stream and content type into a result object. */ public interface ContentConverter<T> { /** * Called when the ContentResponseHandler wants to convert an input stream * into a response object. Calling this method does *not* imply a 2xx response code, * this method will be called for all response codes if no error occurs while processing * the response. * * @param response The response object from the Http client. * @param inputStream The response body as stream. * @return The result object. Can be null. * @throws IOException */
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/ContentConverter.java import java.io.IOException; import java.io.InputStream; import com.nesscomputing.httpclient.HttpClientResponse; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Convert an Input Stream and content type into a result object. */ public interface ContentConverter<T> { /** * Called when the ContentResponseHandler wants to convert an input stream * into a response object. Calling this method does *not* imply a 2xx response code, * this method will be called for all response codes if no error occurs while processing * the response. * * @param response The response object from the Http client. * @param inputStream The response body as stream. * @return The result object. Can be null. * @throws IOException */
T convert(HttpClientResponse response, InputStream inputStream) throws IOException;
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponseHandler.java // public interface HttpClientResponseHandler<T> // { // /** // * Process the {@link HttpClientResponse} object and generate an appropriate // * response object. // */ // T handle(HttpClientResponse response) throws IOException; // }
import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.HttpClientResponseHandler; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackRefusedException;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Accepts an incoming JSON data stream and converts it into objects on the fly. The JSON data stream must be structured in a special format: * <pre> * { "results": [ .... stream of data ], * "success": true * } * </pre> * * No other fields must be present in the JSON object besides <tt>results</tt> and <tt>success</tt> and the <tt>success</tt> field must immediately follow * the <tt>results</tt> field to mark its end. */ public class StreamedJsonContentConverter<T> extends AbstractErrorHandlingContentConverter<Void> { private static final Log LOG = Log.findLog(); private static final TypeReference<Map<String, ? extends Object>> JSON_MAP_TYPE_REF = new TypeReference<Map<String, ? extends Object>>() {}; public static StreamedJsonContentConverter<Map<String, ? extends Object>> of(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF); }
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponseHandler.java // public interface HttpClientResponseHandler<T> // { // /** // * Process the {@link HttpClientResponse} object and generate an appropriate // * response object. // */ // T handle(HttpClientResponse response) throws IOException; // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.HttpClientResponseHandler; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackRefusedException; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Accepts an incoming JSON data stream and converts it into objects on the fly. The JSON data stream must be structured in a special format: * <pre> * { "results": [ .... stream of data ], * "success": true * } * </pre> * * No other fields must be present in the JSON object besides <tt>results</tt> and <tt>success</tt> and the <tt>success</tt> field must immediately follow * the <tt>results</tt> field to mark its end. */ public class StreamedJsonContentConverter<T> extends AbstractErrorHandlingContentConverter<Void> { private static final Log LOG = Log.findLog(); private static final TypeReference<Map<String, ? extends Object>> JSON_MAP_TYPE_REF = new TypeReference<Map<String, ? extends Object>>() {}; public static StreamedJsonContentConverter<Map<String, ? extends Object>> of(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF); }
public static HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback)
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponseHandler.java // public interface HttpClientResponseHandler<T> // { // /** // * Process the {@link HttpClientResponse} object and generate an appropriate // * response object. // */ // T handle(HttpClientResponse response) throws IOException; // }
import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.HttpClientResponseHandler; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackRefusedException;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Accepts an incoming JSON data stream and converts it into objects on the fly. The JSON data stream must be structured in a special format: * <pre> * { "results": [ .... stream of data ], * "success": true * } * </pre> * * No other fields must be present in the JSON object besides <tt>results</tt> and <tt>success</tt> and the <tt>success</tt> field must immediately follow * the <tt>results</tt> field to mark its end. */ public class StreamedJsonContentConverter<T> extends AbstractErrorHandlingContentConverter<Void> { private static final Log LOG = Log.findLog(); private static final TypeReference<Map<String, ? extends Object>> JSON_MAP_TYPE_REF = new TypeReference<Map<String, ? extends Object>>() {}; public static StreamedJsonContentConverter<Map<String, ? extends Object>> of(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF); } public static HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF)); } public static <T> HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeReference) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<T>(mapper, callback, typeReference)); } private final ObjectMapper mapper; private final TypeReference<T> typeRef; private final Callback<? super T> callback; StreamedJsonContentConverter(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeRef) { this.mapper = mapper; this.typeRef = typeRef; this.callback = callback; } @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // // Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponseHandler.java // public interface HttpClientResponseHandler<T> // { // /** // * Process the {@link HttpClientResponse} object and generate an appropriate // * response object. // */ // T handle(HttpClientResponse response) throws IOException; // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/StreamedJsonContentConverter.java import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.HttpClientResponseHandler; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.nesscomputing.callback.Callback; import com.nesscomputing.callback.CallbackRefusedException; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Accepts an incoming JSON data stream and converts it into objects on the fly. The JSON data stream must be structured in a special format: * <pre> * { "results": [ .... stream of data ], * "success": true * } * </pre> * * No other fields must be present in the JSON object besides <tt>results</tt> and <tt>success</tt> and the <tt>success</tt> field must immediately follow * the <tt>results</tt> field to mark its end. */ public class StreamedJsonContentConverter<T> extends AbstractErrorHandlingContentConverter<Void> { private static final Log LOG = Log.findLog(); private static final TypeReference<Map<String, ? extends Object>> JSON_MAP_TYPE_REF = new TypeReference<Map<String, ? extends Object>>() {}; public static StreamedJsonContentConverter<Map<String, ? extends Object>> of(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF); } public static HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<Map<String, ? extends Object>> callback) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<Map<String, ? extends Object>>(mapper, callback, JSON_MAP_TYPE_REF)); } public static <T> HttpClientResponseHandler<Void> handle(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeReference) { return ContentResponseHandler.forConverter(new StreamedJsonContentConverter<T>(mapper, callback, typeReference)); } private final ObjectMapper mapper; private final TypeReference<T> typeRef; private final Callback<? super T> callback; StreamedJsonContentConverter(final ObjectMapper mapper, final Callback<? super T> callback, final TypeReference<T> typeRef) { this.mapper = mapper; this.typeRef = typeRef; this.callback = callback; } @Override
public Void convert(final HttpClientResponse response, final InputStream inputStream)
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/AbstractErrorHandlingContentConverter.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import com.google.common.base.Charsets; import com.google.common.base.Objects; import org.apache.commons.io.IOUtils;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Base class to get rid of the repetitive "throw the exception out" method. */ public abstract class AbstractErrorHandlingContentConverter<T> implements ContentConverter<T> { private static final int MAX_RESPONSE_PRINT_CHARS = 4096; private static final Log LOG = Log.findLog(); @Override
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/AbstractErrorHandlingContentConverter.java import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.logging.Log; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import com.google.common.base.Charsets; import com.google.common.base.Objects; import org.apache.commons.io.IOUtils; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; /** * Base class to get rid of the repetitive "throw the exception out" method. */ public abstract class AbstractErrorHandlingContentConverter<T> implements ContentConverter<T> { private static final int MAX_RESPONSE_PRINT_CHARS = 4096; private static final Log LOG = Log.findLog(); @Override
public T handleError(final HttpClientResponse httpClientResponse, final IOException ex)
NessComputing/components-ness-httpclient
client/src/test/java/com/nesscomputing/httpclient/testsupport/GenericTestHandler.java
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // }
import org.eclipse.jetty.server.handler.AbstractHandler; import com.nesscomputing.httpclient.internal.HttpClientHeader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; public class GenericTestHandler extends AbstractHandler { private String content = ""; private String contentType = "text/html";
// Path: client/src/main/java/com/nesscomputing/httpclient/internal/HttpClientHeader.java // @Immutable // public class HttpClientHeader // { // private final String name; // private final String value; // // /** // * Create a new header. // * @param name header name // * @param value header value // */ // public HttpClientHeader(final String name, final String value) // { // this.name = name; // this.value = value; // } // // /** // * @return the header name. // */ // public String getName() // { // return name; // } // // /** // * @return the header value. // */ // public String getValue() // { // return value; // } // } // Path: client/src/test/java/com/nesscomputing/httpclient/testsupport/GenericTestHandler.java import org.eclipse.jetty.server.handler.AbstractHandler; import com.nesscomputing.httpclient.internal.HttpClientHeader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testsupport; public class GenericTestHandler extends AbstractHandler { private String content = ""; private String contentType = "text/html";
private final Map<String, List<HttpClientHeader>> reqHeaders = new HashMap<String, List<HttpClientHeader>>();
NessComputing/components-ness-httpclient
client/src/main/java/com/nesscomputing/httpclient/response/HttpResponseException.java
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // }
import static java.lang.String.format; import java.io.IOException; import com.nesscomputing.httpclient.HttpClientResponse;
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; public class HttpResponseException extends IOException { private static final long serialVersionUID = 1L;
// Path: client/src/main/java/com/nesscomputing/httpclient/HttpClientResponse.java // public interface HttpClientResponse { // /** // * Returns the status code for the request. // * // * @return the status code, use the related {@link HttpServletRequest} constants // */ // int getStatusCode(); // // /** // * Returns the status text for the request. // * // * @return the status text // */ // String getStatusText(); // // /** // * Returns an input stream for the response body. // * // * @return the input stream // * @throws IOException on error // */ // InputStream getResponseBodyAsStream() throws IOException; // // /** @return the URI of the request. */ // URI getUri(); // // /** @return Content type of the response. */ // String getContentType(); // // /** // * @return Length of the content, if present. Can be null (not present), -1 (chunked) or 0 (no // * content). // */ // @CheckForNull // Long getContentLength(); // // /** @return Content charset if present in the header. Can be null. */ // @CheckForNull // String getCharset(); // // /** // * @param name the header name // * @return The named header from the response. Response can be null. // */ // @CheckForNull // String getHeader(String name); // // /** // * @param name the header name // * @return all values for the given header. Response can be null. // */ // @CheckForNull // List<String> getHeaders(String name); // // /** @return Map of header name -> list of values for each header name */ // @Nonnull // public Map<String, List<String>> getAllHeaders(); // // /** @return true if the response redirects to another object. */ // boolean isRedirected(); // } // Path: client/src/main/java/com/nesscomputing/httpclient/response/HttpResponseException.java import static java.lang.String.format; import java.io.IOException; import com.nesscomputing.httpclient.HttpClientResponse; /** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.response; public class HttpResponseException extends IOException { private static final long serialVersionUID = 1L;
private final HttpClientResponse httpResponse;
ksiomelo/twitter-crawling-tools
src/utils/ClearLineBreaks.java
// Path: src/crawler/Constants.java // public interface Constants { // // // //ENTER YOUR KEYS HERE // public static final String YAHOO_API_KEY = ""; // public static final String ALCHEMY_API_KEY = ""; // // // // public static final String[] STOP_WORDS = {"day", "rt", "new","youtube","happy", "time", "best", "birthday", "good", "love", "yeah"}; // // // // public static final String TERM_EXTRACTOR_INPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/T_nico-rosberg_content_ouput.txt"; // public static final String SEARCH_TWEETS_BY_LOCATION_USERS_OUTPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/T_nico-rosberg_users_ouput.txt"; // // public static final String TERM_EXTRACTOR_OUTPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/TE-nico-rosberg_output.txt"; // // // network crawl // public static final String NETWORK_CONTENT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter.txt"; // public static final String NETWORK_TERM_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter_term.txt"; // // // // // // public static final String FORMAL_CONTEXT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter.cxt"; // // // // similarity // public static final String SIMILARITY_NETWORK_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter_sim.csv"; // // // public static final String IDENTIFIER = "#\\*#"; //"#\\*#" // public static final String NEW_IDENTIFIER = "#~#"; // // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.nio.channels.FileChannel; import crawler.Constants;
package utils; public class ClearLineBreaks { public static void clearLineBreaks(String file) throws IOException { File temp = File.createTempFile("clearlinebreaks", Long.toString(System.nanoTime())); File orig = new File(file); // read input file line by line BufferedReader reader = new BufferedReader(new FileReader(orig)); FileOutputStream fout = new FileOutputStream(temp); PrintStream ps = new PrintStream(fout); String line = null; line = reader.readLine(); while (line != null) { ps.println(line.replace("\n", "").replace("\r", "")); line = reader.readLine(); } ps.close(); fout.close(); // Copy the contents from temp to original file FileChannel src = new FileInputStream(temp).getChannel(); FileChannel dest = new FileOutputStream(orig).getChannel(); dest.transferFrom(src, 0, src.size()); } public static void fixLineBreaks(String file) throws IOException { File temp = File.createTempFile("fixlinebreaks", Long.toString(System.nanoTime())); File orig = new File(file); // read input file line by line BufferedReader reader = new BufferedReader(new FileReader(orig)); FileOutputStream fout = new FileOutputStream(temp); PrintStream ps = new PrintStream(fout); String line = null; line = reader.readLine(); while (line != null) {
// Path: src/crawler/Constants.java // public interface Constants { // // // //ENTER YOUR KEYS HERE // public static final String YAHOO_API_KEY = ""; // public static final String ALCHEMY_API_KEY = ""; // // // // public static final String[] STOP_WORDS = {"day", "rt", "new","youtube","happy", "time", "best", "birthday", "good", "love", "yeah"}; // // // // public static final String TERM_EXTRACTOR_INPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/T_nico-rosberg_content_ouput.txt"; // public static final String SEARCH_TWEETS_BY_LOCATION_USERS_OUTPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/T_nico-rosberg_users_ouput.txt"; // // public static final String TERM_EXTRACTOR_OUTPUT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/TE-nico-rosberg_output.txt"; // // // network crawl // public static final String NETWORK_CONTENT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter.txt"; // public static final String NETWORK_TERM_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter_term.txt"; // // // // // // public static final String FORMAL_CONTEXT_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter.cxt"; // // // // similarity // public static final String SIMILARITY_NETWORK_FILE = "/Users/cassiomelo/Dropbox/code/twittertest/data/twitter_sim.csv"; // // // public static final String IDENTIFIER = "#\\*#"; //"#\\*#" // public static final String NEW_IDENTIFIER = "#~#"; // // // } // Path: src/utils/ClearLineBreaks.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.nio.channels.FileChannel; import crawler.Constants; package utils; public class ClearLineBreaks { public static void clearLineBreaks(String file) throws IOException { File temp = File.createTempFile("clearlinebreaks", Long.toString(System.nanoTime())); File orig = new File(file); // read input file line by line BufferedReader reader = new BufferedReader(new FileReader(orig)); FileOutputStream fout = new FileOutputStream(temp); PrintStream ps = new PrintStream(fout); String line = null; line = reader.readLine(); while (line != null) { ps.println(line.replace("\n", "").replace("\r", "")); line = reader.readLine(); } ps.close(); fout.close(); // Copy the contents from temp to original file FileChannel src = new FileInputStream(temp).getChannel(); FileChannel dest = new FileOutputStream(orig).getChannel(); dest.transferFrom(src, 0, src.size()); } public static void fixLineBreaks(String file) throws IOException { File temp = File.createTempFile("fixlinebreaks", Long.toString(System.nanoTime())); File orig = new File(file); // read input file line by line BufferedReader reader = new BufferedReader(new FileReader(orig)); FileOutputStream fout = new FileOutputStream(temp); PrintStream ps = new PrintStream(fout); String line = null; line = reader.readLine(); while (line != null) {
String [] lineArray = line.split(Constants.IDENTIFIER);
ksiomelo/twitter-crawling-tools
src/crawler/CrawlerNetwork.java
// Path: src/twitter4j/Status.java // public interface Status extends Comparable<Status>, TwitterResponse, // EntitySupport, java.io.Serializable { // /** // * Return the created_at // * // * @return created_at // * @since Twitter4J 1.1.0 // */ // // Date getCreatedAt(); // // /** // * Returns the id of the status // * // * @return the id // */ // long getId(); // // /** // * Returns the text of the status // * // * @return the text // */ // String getText(); // // /** // * Returns the source // * // * @return the source // * @since Twitter4J 1.0.4 // */ // String getSource(); // // // /** // * Test if the status is truncated // * // * @return true if truncated // * @since Twitter4J 1.0.4 // */ // boolean isTruncated(); // // /** // * Returns the in_reply_tostatus_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToStatusId(); // // /** // * Returns the in_reply_user_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToUserId(); // // /** // * Returns the in_reply_to_screen_name // * // * @return the in_in_reply_to_screen_name // * @since Twitter4J 2.0.4 // */ // String getInReplyToScreenName(); // // /** // * Returns The location that this tweet refers to if available. // * // * @return returns The location that this tweet refers to if available (can be null) // * @since Twitter4J 2.1.0 // */ // GeoLocation getGeoLocation(); // // /** // * Returns the place attached to this status // * // * @return The place attached to this status // * @since Twitter4J 2.1.1 // */ // Place getPlace(); // // /** // * Test if the status is favorited // * // * @return true if favorited // * @since Twitter4J 1.0.4 // */ // boolean isFavorited(); // // /** // * Return the user associated with the status.<br> // * This can be null if the instance if from User.getStatus(). // * // * @return the user // */ // User getUser(); // // /** // * @since Twitter4J 2.0.10 // */ // boolean isRetweet(); // // /** // * @since Twitter4J 2.1.0 // */ // Status getRetweetedStatus(); // // /** // * Returns an array of contributors, or null if no contributor is associated with this status. // * // * @since Twitter4J 2.2.3 // */ // long[] getContributors(); // // /** // * Returns the number of times this tweet has been retweeted, or -1 when the tweet was // * created before this feature was enabled. // * // * @return the retweet count. // */ // long getRetweetCount(); // // /** // * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was // * created before this feature was enabled. // * // * @return whether the authenticating user has retweeted this tweet. // * @since Twitter4J 2.1.4 // */ // boolean isRetweetedByMe(); // // /** // * Returns the annotations, or null if no annotations are associated with this status. // * // * @since Twitter4J 2.1.4 // * @deprecated Annotations is not available for now. <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/4d5ff2ec4d2ce4a7">Annotations - Twitter Development Talk | Google Groups</a> // */ // Annotations getAnnotations(); // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import twitter4j.IDs; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken;
public HashSet<User> getFriends(User u, int max) throws Exception { HashSet<User> ret = new HashSet<User>(); long cursor = -1; IDs ids; int count = 0; do { ids = twitter.getFriendsIDs(u.getScreenName(), cursor); for (int i = 0; i < ids.getIDs().length && i < max; i++) { long id = ids.getIDs()[i]; ret.add(twitter.showUser(id)); } count++; } while ((cursor = ids.getNextCursor()) != 0 && count < max); return ret; } public void crawl() throws TwitterException, IOException{ ArrayList<User> ret = new ArrayList<User>(); HashMap<User,HashSet<Link>> links = new HashMap<User,HashSet<Link>>();
// Path: src/twitter4j/Status.java // public interface Status extends Comparable<Status>, TwitterResponse, // EntitySupport, java.io.Serializable { // /** // * Return the created_at // * // * @return created_at // * @since Twitter4J 1.1.0 // */ // // Date getCreatedAt(); // // /** // * Returns the id of the status // * // * @return the id // */ // long getId(); // // /** // * Returns the text of the status // * // * @return the text // */ // String getText(); // // /** // * Returns the source // * // * @return the source // * @since Twitter4J 1.0.4 // */ // String getSource(); // // // /** // * Test if the status is truncated // * // * @return true if truncated // * @since Twitter4J 1.0.4 // */ // boolean isTruncated(); // // /** // * Returns the in_reply_tostatus_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToStatusId(); // // /** // * Returns the in_reply_user_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToUserId(); // // /** // * Returns the in_reply_to_screen_name // * // * @return the in_in_reply_to_screen_name // * @since Twitter4J 2.0.4 // */ // String getInReplyToScreenName(); // // /** // * Returns The location that this tweet refers to if available. // * // * @return returns The location that this tweet refers to if available (can be null) // * @since Twitter4J 2.1.0 // */ // GeoLocation getGeoLocation(); // // /** // * Returns the place attached to this status // * // * @return The place attached to this status // * @since Twitter4J 2.1.1 // */ // Place getPlace(); // // /** // * Test if the status is favorited // * // * @return true if favorited // * @since Twitter4J 1.0.4 // */ // boolean isFavorited(); // // /** // * Return the user associated with the status.<br> // * This can be null if the instance if from User.getStatus(). // * // * @return the user // */ // User getUser(); // // /** // * @since Twitter4J 2.0.10 // */ // boolean isRetweet(); // // /** // * @since Twitter4J 2.1.0 // */ // Status getRetweetedStatus(); // // /** // * Returns an array of contributors, or null if no contributor is associated with this status. // * // * @since Twitter4J 2.2.3 // */ // long[] getContributors(); // // /** // * Returns the number of times this tweet has been retweeted, or -1 when the tweet was // * created before this feature was enabled. // * // * @return the retweet count. // */ // long getRetweetCount(); // // /** // * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was // * created before this feature was enabled. // * // * @return whether the authenticating user has retweeted this tweet. // * @since Twitter4J 2.1.4 // */ // boolean isRetweetedByMe(); // // /** // * Returns the annotations, or null if no annotations are associated with this status. // * // * @since Twitter4J 2.1.4 // * @deprecated Annotations is not available for now. <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/4d5ff2ec4d2ce4a7">Annotations - Twitter Development Talk | Google Groups</a> // */ // Annotations getAnnotations(); // } // Path: src/crawler/CrawlerNetwork.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import twitter4j.IDs; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken; public HashSet<User> getFriends(User u, int max) throws Exception { HashSet<User> ret = new HashSet<User>(); long cursor = -1; IDs ids; int count = 0; do { ids = twitter.getFriendsIDs(u.getScreenName(), cursor); for (int i = 0; i < ids.getIDs().length && i < max; i++) { long id = ids.getIDs()[i]; ret.add(twitter.showUser(id)); } count++; } while ((cursor = ids.getNextCursor()) != 0 && count < max); return ret; } public void crawl() throws TwitterException, IOException{ ArrayList<User> ret = new ArrayList<User>(); HashMap<User,HashSet<Link>> links = new HashMap<User,HashSet<Link>>();
HashMap<User,ResponseList<Status>> statuses = new HashMap<User,ResponseList<Status>>();
ksiomelo/twitter-crawling-tools
src/twitter/TwitterRetry.java
// Path: src/twitter4j/Status.java // public interface Status extends Comparable<Status>, TwitterResponse, // EntitySupport, java.io.Serializable { // /** // * Return the created_at // * // * @return created_at // * @since Twitter4J 1.1.0 // */ // // Date getCreatedAt(); // // /** // * Returns the id of the status // * // * @return the id // */ // long getId(); // // /** // * Returns the text of the status // * // * @return the text // */ // String getText(); // // /** // * Returns the source // * // * @return the source // * @since Twitter4J 1.0.4 // */ // String getSource(); // // // /** // * Test if the status is truncated // * // * @return true if truncated // * @since Twitter4J 1.0.4 // */ // boolean isTruncated(); // // /** // * Returns the in_reply_tostatus_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToStatusId(); // // /** // * Returns the in_reply_user_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToUserId(); // // /** // * Returns the in_reply_to_screen_name // * // * @return the in_in_reply_to_screen_name // * @since Twitter4J 2.0.4 // */ // String getInReplyToScreenName(); // // /** // * Returns The location that this tweet refers to if available. // * // * @return returns The location that this tweet refers to if available (can be null) // * @since Twitter4J 2.1.0 // */ // GeoLocation getGeoLocation(); // // /** // * Returns the place attached to this status // * // * @return The place attached to this status // * @since Twitter4J 2.1.1 // */ // Place getPlace(); // // /** // * Test if the status is favorited // * // * @return true if favorited // * @since Twitter4J 1.0.4 // */ // boolean isFavorited(); // // /** // * Return the user associated with the status.<br> // * This can be null if the instance if from User.getStatus(). // * // * @return the user // */ // User getUser(); // // /** // * @since Twitter4J 2.0.10 // */ // boolean isRetweet(); // // /** // * @since Twitter4J 2.1.0 // */ // Status getRetweetedStatus(); // // /** // * Returns an array of contributors, or null if no contributor is associated with this status. // * // * @since Twitter4J 2.2.3 // */ // long[] getContributors(); // // /** // * Returns the number of times this tweet has been retweeted, or -1 when the tweet was // * created before this feature was enabled. // * // * @return the retweet count. // */ // long getRetweetCount(); // // /** // * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was // * created before this feature was enabled. // * // * @return whether the authenticating user has retweeted this tweet. // * @since Twitter4J 2.1.4 // */ // boolean isRetweetedByMe(); // // /** // * Returns the annotations, or null if no annotations are associated with this status. // * // * @since Twitter4J 2.1.4 // * @deprecated Annotations is not available for now. <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/4d5ff2ec4d2ce4a7">Annotations - Twitter Development Talk | Google Groups</a> // */ // Annotations getAnnotations(); // }
import java.util.HashSet; import twitter4j.IDs; import twitter4j.Paging; import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken;
} public IDs getFriendsIDs(String screename, Long cursor) throws TwitterException { System.out.print("[request] getFriendsIDs:"+screename +" "); checkRateLimitStatus(); return twitter.getFriendsIDs(screename, cursor); } public User showUser(Long userId) throws TwitterException { System.out.print("[request] showUser:"+userId +" "); checkRateLimitStatus(); return twitter.showUser(userId); } public User showUser(String userId) throws TwitterException { System.out.print("[request] showUser:"+userId +" "); checkRateLimitStatus(); return twitter.showUser(userId); } public ResponseList<User> lookupUsers(long[] userIds) throws TwitterException { System.out.print("[request] lookupUsers "); checkRateLimitStatus(); return twitter.lookupUsers(userIds); } public ResponseList<User> lookupUsers(String[] screenames) throws TwitterException { System.out.print("[request] lookupUsers "); checkRateLimitStatus(); return twitter.lookupUsers(screenames); }
// Path: src/twitter4j/Status.java // public interface Status extends Comparable<Status>, TwitterResponse, // EntitySupport, java.io.Serializable { // /** // * Return the created_at // * // * @return created_at // * @since Twitter4J 1.1.0 // */ // // Date getCreatedAt(); // // /** // * Returns the id of the status // * // * @return the id // */ // long getId(); // // /** // * Returns the text of the status // * // * @return the text // */ // String getText(); // // /** // * Returns the source // * // * @return the source // * @since Twitter4J 1.0.4 // */ // String getSource(); // // // /** // * Test if the status is truncated // * // * @return true if truncated // * @since Twitter4J 1.0.4 // */ // boolean isTruncated(); // // /** // * Returns the in_reply_tostatus_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToStatusId(); // // /** // * Returns the in_reply_user_id // * // * @return the in_reply_tostatus_id // * @since Twitter4J 1.0.4 // */ // long getInReplyToUserId(); // // /** // * Returns the in_reply_to_screen_name // * // * @return the in_in_reply_to_screen_name // * @since Twitter4J 2.0.4 // */ // String getInReplyToScreenName(); // // /** // * Returns The location that this tweet refers to if available. // * // * @return returns The location that this tweet refers to if available (can be null) // * @since Twitter4J 2.1.0 // */ // GeoLocation getGeoLocation(); // // /** // * Returns the place attached to this status // * // * @return The place attached to this status // * @since Twitter4J 2.1.1 // */ // Place getPlace(); // // /** // * Test if the status is favorited // * // * @return true if favorited // * @since Twitter4J 1.0.4 // */ // boolean isFavorited(); // // /** // * Return the user associated with the status.<br> // * This can be null if the instance if from User.getStatus(). // * // * @return the user // */ // User getUser(); // // /** // * @since Twitter4J 2.0.10 // */ // boolean isRetweet(); // // /** // * @since Twitter4J 2.1.0 // */ // Status getRetweetedStatus(); // // /** // * Returns an array of contributors, or null if no contributor is associated with this status. // * // * @since Twitter4J 2.2.3 // */ // long[] getContributors(); // // /** // * Returns the number of times this tweet has been retweeted, or -1 when the tweet was // * created before this feature was enabled. // * // * @return the retweet count. // */ // long getRetweetCount(); // // /** // * Returns true if the authenticating user has retweeted this tweet, or false when the tweet was // * created before this feature was enabled. // * // * @return whether the authenticating user has retweeted this tweet. // * @since Twitter4J 2.1.4 // */ // boolean isRetweetedByMe(); // // /** // * Returns the annotations, or null if no annotations are associated with this status. // * // * @since Twitter4J 2.1.4 // * @deprecated Annotations is not available for now. <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/4d5ff2ec4d2ce4a7">Annotations - Twitter Development Talk | Google Groups</a> // */ // Annotations getAnnotations(); // } // Path: src/twitter/TwitterRetry.java import java.util.HashSet; import twitter4j.IDs; import twitter4j.Paging; import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken; } public IDs getFriendsIDs(String screename, Long cursor) throws TwitterException { System.out.print("[request] getFriendsIDs:"+screename +" "); checkRateLimitStatus(); return twitter.getFriendsIDs(screename, cursor); } public User showUser(Long userId) throws TwitterException { System.out.print("[request] showUser:"+userId +" "); checkRateLimitStatus(); return twitter.showUser(userId); } public User showUser(String userId) throws TwitterException { System.out.print("[request] showUser:"+userId +" "); checkRateLimitStatus(); return twitter.showUser(userId); } public ResponseList<User> lookupUsers(long[] userIds) throws TwitterException { System.out.print("[request] lookupUsers "); checkRateLimitStatus(); return twitter.lookupUsers(userIds); } public ResponseList<User> lookupUsers(String[] screenames) throws TwitterException { System.out.print("[request] lookupUsers "); checkRateLimitStatus(); return twitter.lookupUsers(screenames); }
public ResponseList<Status> getUserTimeline(long userId, Paging paging) throws TwitterException {
ksiomelo/twitter-crawling-tools
src/twitter4j/conf/ConfigurationBase.java
// Path: src/twitter4j/Version.java // public final class Version { // private static final String VERSION = "2.2.5"; // private static final String TITLE = "Twitter4J"; // // private Version() { // throw new AssertionError(); // } // // public static String getVersion() { // return VERSION; // } // // /** // * prints the version string // * // * @param args will be just ignored. // */ // public static void main(String[] args) { // System.out.println(TITLE + " " + VERSION); // } // }
import twitter4j.Version; import java.io.ObjectStreamException; import java.util.*;
Class.forName("com.google.appengine.api.urlfetch.URLFetchService"); gaeDetected = "true"; } catch (ClassNotFoundException cnfe) { gaeDetected = "false"; } } protected ConfigurationBase() { setDebug(false); setUser(null); setPassword(null); setUseSSL(false); setPrettyDebugEnabled(false); setGZIPEnabled(true); setHttpProxyHost(null); setHttpProxyUser(null); setHttpProxyPassword(null); setHttpProxyPort(-1); setHttpConnectionTimeout(20000); setHttpReadTimeout(120000); setHttpStreamingReadTimeout(40 * 1000); setHttpRetryCount(0); setHttpRetryIntervalSeconds(5); setHttpMaxTotalConnections(20); setHttpDefaultMaxPerRoute(2); setOAuthConsumerKey(null); setOAuthConsumerSecret(null); setOAuthAccessToken(null); setOAuthAccessTokenSecret(null); setAsyncNumThreads(1);
// Path: src/twitter4j/Version.java // public final class Version { // private static final String VERSION = "2.2.5"; // private static final String TITLE = "Twitter4J"; // // private Version() { // throw new AssertionError(); // } // // public static String getVersion() { // return VERSION; // } // // /** // * prints the version string // * // * @param args will be just ignored. // */ // public static void main(String[] args) { // System.out.println(TITLE + " " + VERSION); // } // } // Path: src/twitter4j/conf/ConfigurationBase.java import twitter4j.Version; import java.io.ObjectStreamException; import java.util.*; Class.forName("com.google.appengine.api.urlfetch.URLFetchService"); gaeDetected = "true"; } catch (ClassNotFoundException cnfe) { gaeDetected = "false"; } } protected ConfigurationBase() { setDebug(false); setUser(null); setPassword(null); setUseSSL(false); setPrettyDebugEnabled(false); setGZIPEnabled(true); setHttpProxyHost(null); setHttpProxyUser(null); setHttpProxyPassword(null); setHttpProxyPort(-1); setHttpConnectionTimeout(20000); setHttpReadTimeout(120000); setHttpStreamingReadTimeout(40 * 1000); setHttpRetryCount(0); setHttpRetryIntervalSeconds(5); setHttpMaxTotalConnections(20); setHttpDefaultMaxPerRoute(2); setOAuthConsumerKey(null); setOAuthConsumerSecret(null); setOAuthAccessToken(null); setOAuthAccessTokenSecret(null); setAsyncNumThreads(1);
setClientVersion(Version.getVersion());
jixieshi999/juahya
JuahyaLibrary/src/com/activity/PostJuahyaActivity.java
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.apis.util.Debug; import com.xml.inflate.inflater.IJuahya;
package com.activity; /** * ½«²É¼¯µÄÊý¾Ý·â×°³Éjson array ͨ¹ýpost´ò°üÉÏ´« * */ public class PostJuahyaActivity extends JuahyaActivity { static String ATTRPOSTURL="action_url"; String postUrl; @Override
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // } // Path: JuahyaLibrary/src/com/activity/PostJuahyaActivity.java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.apis.util.Debug; import com.xml.inflate.inflater.IJuahya; package com.activity; /** * ½«²É¼¯µÄÊý¾Ý·â×°³Éjson array ͨ¹ýpost´ò°üÉÏ´« * */ public class PostJuahyaActivity extends JuahyaActivity { static String ATTRPOSTURL="action_url"; String postUrl; @Override
public void onJuahyaLayoutInflate(IJuahya ijuahya) {
jixieshi999/juahya
JuahyaLibrary/src/com/activity/PostJuahyaActivity.java
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.apis.util.Debug; import com.xml.inflate.inflater.IJuahya;
package com.activity; /** * ½«²É¼¯µÄÊý¾Ý·â×°³Éjson array ͨ¹ýpost´ò°üÉÏ´« * */ public class PostJuahyaActivity extends JuahyaActivity { static String ATTRPOSTURL="action_url"; String postUrl; @Override public void onJuahyaLayoutInflate(IJuahya ijuahya) { if(ATTRPOSTURL.equals(ijuahya.getAttrKey())){ postUrl=ijuahya.getAttrDescription(); }else{ super.onJuahyaLayoutInflate(ijuahya); } } /**½«Êý¾Ý¸ñʽ»¯³Éjson array*/ protected String fomatData(){ ArrayList<IJuahya> IJuahyaList=getIJuahyaList(); JSONArray ja=new JSONArray(); JSONObject jo=new JSONObject(); for(IJuahya ij:IJuahyaList){ try { jo=new JSONObject(); jo.put(ij.getAttrKey(), ij.getValue()); ja.put(jo); } catch (JSONException e) {
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // } // Path: JuahyaLibrary/src/com/activity/PostJuahyaActivity.java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.android.apis.util.Debug; import com.xml.inflate.inflater.IJuahya; package com.activity; /** * ½«²É¼¯µÄÊý¾Ý·â×°³Éjson array ͨ¹ýpost´ò°üÉÏ´« * */ public class PostJuahyaActivity extends JuahyaActivity { static String ATTRPOSTURL="action_url"; String postUrl; @Override public void onJuahyaLayoutInflate(IJuahya ijuahya) { if(ATTRPOSTURL.equals(ijuahya.getAttrKey())){ postUrl=ijuahya.getAttrDescription(); }else{ super.onJuahyaLayoutInflate(ijuahya); } } /**½«Êý¾Ý¸ñʽ»¯³Éjson array*/ protected String fomatData(){ ArrayList<IJuahya> IJuahyaList=getIJuahyaList(); JSONArray ja=new JSONArray(); JSONObject jo=new JSONObject(); for(IJuahya ij:IJuahyaList){ try { jo=new JSONObject(); jo.put(ij.getAttrKey(), ij.getValue()); ja.put(jo); } catch (JSONException e) {
Debug.dLog(e);
jixieshi999/juahya
JuahyaLibrary/src/com/xml/inflate/inflater/juahya/IFJEditTextInFlater.java
// Path: JuahyaLibrary/src/com/juahya/guis/JEditText.java // public class JEditText extends EditText implements IJuahya{ // // protected String attrKey; // protected String attrDescription; // protected String attrType; // // public void setAttrType(String attrType) { // this.attrType = attrType; // } // // public String getAttrKey() { // return attrKey; // } // // public void setAttrKey(String attrKey) { // this.attrKey = attrKey; // } // // public String getAttrDescription() { // return attrDescription; // } // // public void setAttrDescription(String attrDescription) { // this.attrDescription = attrDescription; // } // // public JEditText(Context context) { // super(context); // } // // public JEditText(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // public JEditText(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public String getValue() { // return getText().toString(); // } // // @Override // public String getAttrType() { // return attrType; // } // // // // } // // Path: JuahyaLibrary/src/com/juahya/guis/JTextView.java // public class JTextView extends TextView implements IJuahya{ // // // // protected String attrKey; // protected String attrDescription; // protected String attrType; // // public void setAttrType(String attrType) { // this.attrType = attrType; // } // public String getAttrKey() { // return attrKey; // } // // public void setAttrKey(String attrKey) { // this.attrKey = attrKey; // } // // public String getAttrDescription() { // return attrDescription; // } // // public void setAttrDescription(String attrDescription) { // this.attrDescription = attrDescription; // } // // public JTextView(Context context) { // super(context); // } // // public JTextView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // public JTextView(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public String getValue() { // return getText().toString(); // } // // @Override // public String getAttrType() { // return attrType; // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IFEditTextInFlater.java // public class IFEditTextInFlater extends IFTextViewInFlater { // // @Override // public TextView inflate(XmlPullParser parser,Context context,LayoutParams paramParrent) { // super.inflate(parser, context,paramParrent); // EditText layout = new EditText(context); // return layout; // } // // @Override // public boolean shoulInflate(String name) { // return "EditText".equalsIgnoreCase(name); // } // }
import org.xmlpull.v1.XmlPullParser; import android.content.Context; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import com.juahya.guis.JEditText; import com.juahya.guis.JTextView; import com.xml.inflate.inflater.IFEditTextInFlater;
package com.xml.inflate.inflater.juahya; public class IFJEditTextInFlater extends IFEditTextInFlater { @Override public TextView inflate(XmlPullParser parser,Context context,LayoutParams paramParrent) { super.inflate(parser, context,paramParrent);
// Path: JuahyaLibrary/src/com/juahya/guis/JEditText.java // public class JEditText extends EditText implements IJuahya{ // // protected String attrKey; // protected String attrDescription; // protected String attrType; // // public void setAttrType(String attrType) { // this.attrType = attrType; // } // // public String getAttrKey() { // return attrKey; // } // // public void setAttrKey(String attrKey) { // this.attrKey = attrKey; // } // // public String getAttrDescription() { // return attrDescription; // } // // public void setAttrDescription(String attrDescription) { // this.attrDescription = attrDescription; // } // // public JEditText(Context context) { // super(context); // } // // public JEditText(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // public JEditText(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public String getValue() { // return getText().toString(); // } // // @Override // public String getAttrType() { // return attrType; // } // // // // } // // Path: JuahyaLibrary/src/com/juahya/guis/JTextView.java // public class JTextView extends TextView implements IJuahya{ // // // // protected String attrKey; // protected String attrDescription; // protected String attrType; // // public void setAttrType(String attrType) { // this.attrType = attrType; // } // public String getAttrKey() { // return attrKey; // } // // public void setAttrKey(String attrKey) { // this.attrKey = attrKey; // } // // public String getAttrDescription() { // return attrDescription; // } // // public void setAttrDescription(String attrDescription) { // this.attrDescription = attrDescription; // } // // public JTextView(Context context) { // super(context); // } // // public JTextView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // } // // public JTextView(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public String getValue() { // return getText().toString(); // } // // @Override // public String getAttrType() { // return attrType; // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IFEditTextInFlater.java // public class IFEditTextInFlater extends IFTextViewInFlater { // // @Override // public TextView inflate(XmlPullParser parser,Context context,LayoutParams paramParrent) { // super.inflate(parser, context,paramParrent); // EditText layout = new EditText(context); // return layout; // } // // @Override // public boolean shoulInflate(String name) { // return "EditText".equalsIgnoreCase(name); // } // } // Path: JuahyaLibrary/src/com/xml/inflate/inflater/juahya/IFJEditTextInFlater.java import org.xmlpull.v1.XmlPullParser; import android.content.Context; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import com.juahya.guis.JEditText; import com.juahya.guis.JTextView; import com.xml.inflate.inflater.IFEditTextInFlater; package com.xml.inflate.inflater.juahya; public class IFJEditTextInFlater extends IFEditTextInFlater { @Override public TextView inflate(XmlPullParser parser,Context context,LayoutParams paramParrent) { super.inflate(parser, context,paramParrent);
JEditText layout = new JEditText(context);
jixieshi999/juahya
JuahyaLibrary/src/com/xml/inflate/inflater/juahya/JuahyaInflater.java
// Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahyaFlateViewInFlaterAdapter.java // public abstract class IJuahyaFlateViewInFlaterAdapter extends IFlateViewInFlaterAdapter { // public String ATTRIBUTE_KEY="attrKey"; // public String ATTRIBUTE_DESCRIPTION="attrDescription"; // public String ATTRIBUTE_TYPE="attrType"; // public String attrKey; // public String attrDescription; // public String attrType; // // public IJuahyaFlateViewInFlaterAdapter() { // super(); // } // // @Override // public boolean inflate(String nameSpace,String attrName,String attrValue){ // super.inflate(nameSpace, attrName, attrValue); // if(IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA.equals(nameSpace)){ // if(ATTRIBUTE_KEY.equals(attrName)){ // attrKey = attrValue; // }else if((ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // }else{ // if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_KEY).equals(attrName)){ // attrKey=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // } // return false; // } // @Override // public void onFinishIFlate(final View lay){ // if(lay instanceof IJuahya){ // IJuahya layout = (IJuahya)lay; // if(null!=attrKey)layout.setAttrKey(attrKey); // if(null!=attrDescription){ // layout.setAttrDescription(attrDescription); // // layout.setHint(attrDescription); // } // if(null!=attrType){ // layout.setAttrType(attrType); // } // } // // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // }
import android.view.View; import com.xml.inflate.inflater.IJuahyaFlateViewInFlaterAdapter; import com.xml.inflate.inflater.IJuahya;
package com.xml.inflate.inflater.juahya; public class JuahyaInflater { public String ATTRIBUTE_KEY="attrKey"; public String ATTRIBUTE_DESCRIPTION="attrDescription"; public String ATTRIBUTE_TYPE="attrType"; public String attrKey; public String attrDescription; public String attrType; public void onFinishIFlate(View lay) {
// Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahyaFlateViewInFlaterAdapter.java // public abstract class IJuahyaFlateViewInFlaterAdapter extends IFlateViewInFlaterAdapter { // public String ATTRIBUTE_KEY="attrKey"; // public String ATTRIBUTE_DESCRIPTION="attrDescription"; // public String ATTRIBUTE_TYPE="attrType"; // public String attrKey; // public String attrDescription; // public String attrType; // // public IJuahyaFlateViewInFlaterAdapter() { // super(); // } // // @Override // public boolean inflate(String nameSpace,String attrName,String attrValue){ // super.inflate(nameSpace, attrName, attrValue); // if(IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA.equals(nameSpace)){ // if(ATTRIBUTE_KEY.equals(attrName)){ // attrKey = attrValue; // }else if((ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // }else{ // if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_KEY).equals(attrName)){ // attrKey=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // } // return false; // } // @Override // public void onFinishIFlate(final View lay){ // if(lay instanceof IJuahya){ // IJuahya layout = (IJuahya)lay; // if(null!=attrKey)layout.setAttrKey(attrKey); // if(null!=attrDescription){ // layout.setAttrDescription(attrDescription); // // layout.setHint(attrDescription); // } // if(null!=attrType){ // layout.setAttrType(attrType); // } // } // // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // } // Path: JuahyaLibrary/src/com/xml/inflate/inflater/juahya/JuahyaInflater.java import android.view.View; import com.xml.inflate.inflater.IJuahyaFlateViewInFlaterAdapter; import com.xml.inflate.inflater.IJuahya; package com.xml.inflate.inflater.juahya; public class JuahyaInflater { public String ATTRIBUTE_KEY="attrKey"; public String ATTRIBUTE_DESCRIPTION="attrDescription"; public String ATTRIBUTE_TYPE="attrType"; public String attrKey; public String attrDescription; public String attrType; public void onFinishIFlate(View lay) {
if(lay instanceof IJuahya){
jixieshi999/juahya
JuahyaLibrary/src/com/xml/inflate/inflater/juahya/JuahyaInflater.java
// Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahyaFlateViewInFlaterAdapter.java // public abstract class IJuahyaFlateViewInFlaterAdapter extends IFlateViewInFlaterAdapter { // public String ATTRIBUTE_KEY="attrKey"; // public String ATTRIBUTE_DESCRIPTION="attrDescription"; // public String ATTRIBUTE_TYPE="attrType"; // public String attrKey; // public String attrDescription; // public String attrType; // // public IJuahyaFlateViewInFlaterAdapter() { // super(); // } // // @Override // public boolean inflate(String nameSpace,String attrName,String attrValue){ // super.inflate(nameSpace, attrName, attrValue); // if(IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA.equals(nameSpace)){ // if(ATTRIBUTE_KEY.equals(attrName)){ // attrKey = attrValue; // }else if((ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // }else{ // if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_KEY).equals(attrName)){ // attrKey=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // } // return false; // } // @Override // public void onFinishIFlate(final View lay){ // if(lay instanceof IJuahya){ // IJuahya layout = (IJuahya)lay; // if(null!=attrKey)layout.setAttrKey(attrKey); // if(null!=attrDescription){ // layout.setAttrDescription(attrDescription); // // layout.setHint(attrDescription); // } // if(null!=attrType){ // layout.setAttrType(attrType); // } // } // // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // }
import android.view.View; import com.xml.inflate.inflater.IJuahyaFlateViewInFlaterAdapter; import com.xml.inflate.inflater.IJuahya;
package com.xml.inflate.inflater.juahya; public class JuahyaInflater { public String ATTRIBUTE_KEY="attrKey"; public String ATTRIBUTE_DESCRIPTION="attrDescription"; public String ATTRIBUTE_TYPE="attrType"; public String attrKey; public String attrDescription; public String attrType; public void onFinishIFlate(View lay) { if(lay instanceof IJuahya){ IJuahya layout = (IJuahya)lay; if(null!=attrKey)layout.setAttrKey(attrKey); if(null!=attrDescription){ layout.setAttrDescription(attrDescription); // layout.setHint(attrDescription); } if(null!=attrType){ layout.setAttrType(attrType); } } } public boolean inflate(String nameSpace, String attrName, String attrValue) {
// Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahyaFlateViewInFlaterAdapter.java // public abstract class IJuahyaFlateViewInFlaterAdapter extends IFlateViewInFlaterAdapter { // public String ATTRIBUTE_KEY="attrKey"; // public String ATTRIBUTE_DESCRIPTION="attrDescription"; // public String ATTRIBUTE_TYPE="attrType"; // public String attrKey; // public String attrDescription; // public String attrType; // // public IJuahyaFlateViewInFlaterAdapter() { // super(); // } // // @Override // public boolean inflate(String nameSpace,String attrName,String attrValue){ // super.inflate(nameSpace, attrName, attrValue); // if(IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA.equals(nameSpace)){ // if(ATTRIBUTE_KEY.equals(attrName)){ // attrKey = attrValue; // }else if((ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // }else{ // if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_KEY).equals(attrName)){ // attrKey=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_DESCRIPTION).equals(attrName)){ // attrDescription=attrValue; // }else if((IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA+":"+ATTRIBUTE_TYPE).equals(attrName)){ // attrType=attrValue; // } // } // return false; // } // @Override // public void onFinishIFlate(final View lay){ // if(lay instanceof IJuahya){ // IJuahya layout = (IJuahya)lay; // if(null!=attrKey)layout.setAttrKey(attrKey); // if(null!=attrDescription){ // layout.setAttrDescription(attrDescription); // // layout.setHint(attrDescription); // } // if(null!=attrType){ // layout.setAttrType(attrType); // } // } // // } // // // // } // // Path: JuahyaLibrary/src/com/xml/inflate/inflater/IJuahya.java // public interface IJuahya { // String getValue(); // String getAttrKey(); // String getAttrDescription(); // String getAttrType(); // // void setAttrType(String attrType) ; // void setAttrKey(String attrKey) ; // void setAttrDescription(String attrDescription); // } // Path: JuahyaLibrary/src/com/xml/inflate/inflater/juahya/JuahyaInflater.java import android.view.View; import com.xml.inflate.inflater.IJuahyaFlateViewInFlaterAdapter; import com.xml.inflate.inflater.IJuahya; package com.xml.inflate.inflater.juahya; public class JuahyaInflater { public String ATTRIBUTE_KEY="attrKey"; public String ATTRIBUTE_DESCRIPTION="attrDescription"; public String ATTRIBUTE_TYPE="attrType"; public String attrKey; public String attrDescription; public String attrType; public void onFinishIFlate(View lay) { if(lay instanceof IJuahya){ IJuahya layout = (IJuahya)lay; if(null!=attrKey)layout.setAttrKey(attrKey); if(null!=attrDescription){ layout.setAttrDescription(attrDescription); // layout.setHint(attrDescription); } if(null!=attrType){ layout.setAttrType(attrType); } } } public boolean inflate(String nameSpace, String attrName, String attrValue) {
if(IJuahyaFlateViewInFlaterAdapter.NAMESPACE_JUAHYA.equals(nameSpace)){
jixieshi999/juahya
JuahyaLibrary/src/com/android/apis/util/SmsTools.java
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import com.android.apis.util.Debug;
String.valueOf(data.length)); conn.setConnectTimeout(10000);// ÉèÖó¬Ê± conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Charset", "UTF-8"); conn.setReadTimeout(100000); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(data); out.flush(); out.close(); // »ñÈ¡ÏìÓ¦Êý¾Ý InputStream input = conn.getInputStream(); InputStreamReader inputreader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputreader); StringBuilder sb = new StringBuilder(); char[] downloadData = new char[4096]; int len = 0; while ((len = reader.read(downloadData, 0, downloadData.length)) > -1) { sb.append(downloadData, 0, len); } result=sb.toString(); reader.close(); inputreader.close(); input.close(); }catch(Exception e){
// Path: JuahyaLibrary/src/com/android/apis/util/Debug.java // public class Debug { // // static String TAG = "DebugTools"; // // public static boolean DEBUG = true; // public static void dLog(String tag,String str){ // if(!DEBUG){ // return; // } // // Log.v(tag, str); // // } // public static void log(String tag,String str){ // // Log.v(tag, str); // // } // public static void dLog(String str){ // dLog(TAG, str); // } // public static void dLog(Object o){ // dLog(TAG, o.toString()); // } // public static void dLog(Object[] os){ // for(Object o:os){ // dLog(TAG, o.toString()); // } // } // public static void dLog(Throwable t){ // if(!DEBUG){ // return; // } // // Log.e(TAG, "",t); // // } // public static void log(String str){ // log(TAG, str); // } // // /** // * init user for debug // * */ // public static void initUserForTest(EditText user,EditText pass){ // if(!DEBUG){ // return; // } // if(user!=null&&pass!=null){ // // pass.setText(AppSetting.PASSWORD); // // user.setText(AppSetting.USER); // // dLog("p : "+AppSetting.PASSWORD+" u: "+AppSetting.USER); // } // // } // public static void dLog(String tag,String str,Exception e){ // if(!DEBUG){ // return; // } // // Log.e(tag, str,e); // // } // // /** // * easy to modify control // * */ // public static void log(String tag,String str,Exception e){ // // Log.e(tag, str,e); // // } // // public static void dLog(String tag,Exception e){ // dLog(tag, "",e); // } // public static void dLog(Exception e){ // dLog(TAG, "",e); // } // public static void dLogCursor(Exception e){ // dLog("sfa_cursor", "cursor exception ",e); // } // // public static void log( Exception e){ // log(TAG, "",e); // } // public static void log(String tag,Exception e){ // log(tag, "",e); // } // // /******** // * ºÄʱ´òÓ¡ // */ // private static Map<String,Long> times=new HashMap<String, Long>(); // public static void beginTime(String name){ // times.put(name, System.currentTimeMillis()); // } // public static void traceTime(String name,String msg){ // Long start = times.get(name); // dLog(msg+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // } // public static void endTime(String name){ // Long start = times.get(name); // dLog(name+"----ºÄʱ:"+(System.currentTimeMillis()-start)); // times.remove(name); // } // } // Path: JuahyaLibrary/src/com/android/apis/util/SmsTools.java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import com.android.apis.util.Debug; String.valueOf(data.length)); conn.setConnectTimeout(10000);// ÉèÖó¬Ê± conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Charset", "UTF-8"); conn.setReadTimeout(100000); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(data); out.flush(); out.close(); // »ñÈ¡ÏìÓ¦Êý¾Ý InputStream input = conn.getInputStream(); InputStreamReader inputreader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputreader); StringBuilder sb = new StringBuilder(); char[] downloadData = new char[4096]; int len = 0; while ((len = reader.read(downloadData, 0, downloadData.length)) > -1) { sb.append(downloadData, 0, len); } result=sb.toString(); reader.close(); inputreader.close(); input.close(); }catch(Exception e){
Debug.dLog(e);
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/literal/LongNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/LongSyntax.java // public class LongSyntax extends Syntax<Long> { // public LongSyntax(long value, SourceSection source) { // super(value, source); // } // }
import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.LongSyntax; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle.node.literal; public class LongNode extends MumblerNode { public final long number;
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/LongSyntax.java // public class LongSyntax extends Syntax<Long> { // public LongSyntax(long value, SourceSection source) { // super(value, source); // } // } // Path: lang/src/main/java/mumbler/truffle/node/literal/LongNode.java import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.LongSyntax; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle.node.literal; public class LongNode extends MumblerNode { public final long number;
public LongNode(LongSyntax syntax) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/MulBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "*") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/MulBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "*") @GenerateNodeFactory
public abstract class MulBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java
// Path: lang/src/main/java/mumbler/truffle/MumblerException.java // public class MumblerException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public MumblerException(String message) { // super(message); // } // // @Override // public Throwable fillInStackTrace() { // CompilerAsserts.neverPartOfCompilation(); // return fillInMumblerStackTrace(this); // } // // public static Throwable fillInMumblerStackTrace(Throwable t) { // final List<StackTraceElement> stackTrace = new ArrayList<>(); // Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { // Node callNode = frame.getCallNode(); // if (callNode == null) { // return null; // } // RootNode root = callNode.getRootNode(); // // /* // * There should be no RootNodes other than SLRootNodes on the stack. Just for the // * case if this would change. // */ // String methodName = "$unknownFunction"; // if (root instanceof MumblerRootNode) { // methodName = ((MumblerRootNode) root).name; // } // // SourceSection sourceSection = callNode.getEncapsulatingSourceSection(); // Source source = sourceSection != null ? sourceSection.getSource() : null; // String sourceName = source != null ? source.getName() : null; // int lineNumber; // try { // lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1; // } catch (UnsupportedOperationException e) { // /* // * SourceSection#getLineLocation() may throw an UnsupportedOperationException. // */ // lineNumber = -1; // } // stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber)); // return null; // }); // t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()])); // return t; // } // } // // Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // }
import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.frame.VirtualFrame; import mumbler.truffle.MumblerException; import mumbler.truffle.node.MumblerNode;
package mumbler.truffle.node.read; public class ReadArgumentNode extends MumblerNode { public final int argumentIndex; public ReadArgumentNode(int argumentIndex) { this.argumentIndex = argumentIndex; } @Override public Object execute(VirtualFrame virtualFrame) { if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { CompilerDirectives.transferToInterpreterAndInvalidate();
// Path: lang/src/main/java/mumbler/truffle/MumblerException.java // public class MumblerException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public MumblerException(String message) { // super(message); // } // // @Override // public Throwable fillInStackTrace() { // CompilerAsserts.neverPartOfCompilation(); // return fillInMumblerStackTrace(this); // } // // public static Throwable fillInMumblerStackTrace(Throwable t) { // final List<StackTraceElement> stackTrace = new ArrayList<>(); // Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { // Node callNode = frame.getCallNode(); // if (callNode == null) { // return null; // } // RootNode root = callNode.getRootNode(); // // /* // * There should be no RootNodes other than SLRootNodes on the stack. Just for the // * case if this would change. // */ // String methodName = "$unknownFunction"; // if (root instanceof MumblerRootNode) { // methodName = ((MumblerRootNode) root).name; // } // // SourceSection sourceSection = callNode.getEncapsulatingSourceSection(); // Source source = sourceSection != null ? sourceSection.getSource() : null; // String sourceName = source != null ? source.getName() : null; // int lineNumber; // try { // lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1; // } catch (UnsupportedOperationException e) { // /* // * SourceSection#getLineLocation() may throw an UnsupportedOperationException. // */ // lineNumber = -1; // } // stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber)); // return null; // }); // t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()])); // return t; // } // } // // Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // Path: lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.frame.VirtualFrame; import mumbler.truffle.MumblerException; import mumbler.truffle.node.MumblerNode; package mumbler.truffle.node.read; public class ReadArgumentNode extends MumblerNode { public final int argumentIndex; public ReadArgumentNode(int argumentIndex) { this.argumentIndex = argumentIndex; } @Override public Object execute(VirtualFrame virtualFrame) { if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { CompilerDirectives.transferToInterpreterAndInvalidate();
throw new MumblerException("Not enough arguments passed. Missing " +
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/io/PrintlnBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "println") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/io/PrintlnBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "println") @GenerateNodeFactory
public abstract class PrintlnBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/AddBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "+") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/AddBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "+") @GenerateNodeFactory
public abstract class AddBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/special/DefineNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // }
import mumbler.truffle.node.MumblerNode; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.FrameSlotKind; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node;
package mumbler.truffle.node.special; @NodeChild("valueNode") @NodeField(name = "slot", type = FrameSlot.class)
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // Path: lang/src/main/java/mumbler/truffle/node/special/DefineNode.java import mumbler.truffle.node.MumblerNode; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeField; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.FrameSlotKind; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; package mumbler.truffle.node.special; @NodeChild("valueNode") @NodeField(name = "slot", type = FrameSlot.class)
public abstract class DefineNode extends MumblerNode {
cesquivias/mumbler
lang/src/test/java/mumbler/truffle/parser/AnalyzerTest.java
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // public static final String ID = "mumbler"; // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public static final String TOP_NS = "<top>"; // // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java // public class MumblerContext { // private final FrameDescriptor globalFrameDescriptor; // private final Namespace globalNamespace; // private final MaterializedFrame globalFrame; // private final MumblerLanguage lang; // // public MumblerContext() { // this(null); // } // // public MumblerContext(MumblerLanguage lang) { // this.globalFrameDescriptor = new FrameDescriptor(); // this.globalNamespace = new Namespace(this.globalFrameDescriptor); // this.globalFrame = this.initGlobalFrame(lang); // this.lang = lang; // } // // private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { // VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, // this.globalFrameDescriptor); // addGlobalFunctions(lang, frame); // return frame.materialize(); // } // // private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { // FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); // virtualFrame.setObject(frameDescriptor.addFrameSlot("println"), // createBuiltinFunction(lang, PrintlnBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("+"), // createBuiltinFunction(lang, AddBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("-"), // createBuiltinFunction(lang, SubBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("*"), // createBuiltinFunction(lang, MulBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("/"), // createBuiltinFunction(lang, DivBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("%"), // createBuiltinFunction(lang, ModBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("="), // createBuiltinFunction(lang, EqualBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("<"), // createBuiltinFunction(lang, LessThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot(">"), // createBuiltinFunction(lang, GreaterThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("list"), // createBuiltinFunction(lang, ListBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cons"), // createBuiltinFunction(lang, ConsBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("car"), // createBuiltinFunction(lang, CarBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cdr"), // createBuiltinFunction(lang, CdrBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("now"), // createBuiltinFunction(lang, NowBuiltinNodeFactory.getInstance(), // virtualFrame)); // // virtualFrame.setObject(frameDescriptor.addFrameSlot("eval"), // // createBuiltinFunction(EvalBuiltinNodeFactory.getInstance(), // // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("read"), // createBuiltinFunction(lang, ReadBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("sleep"), // createBuiltinFunction(lang, SleepBuiltinNodeFactory.getInstance(), // virtualFrame)); // } // // /** // * @return A {@link MaterializedFrame} on the heap that contains all global // * values. // */ // public MaterializedFrame getGlobalFrame() { // return this.globalFrame; // } // // public Namespace getGlobalNamespace() { // return this.globalNamespace; // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // }
import static mumbler.truffle.MumblerLanguage.ID; import static mumbler.truffle.parser.Namespace.TOP_NS; import java.io.IOException; import mumbler.truffle.MumblerContext; import mumbler.truffle.syntax.ListSyntax; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.source.Source;
package mumbler.truffle.parser; public class AnalyzerTest { MumblerContext context; Analyzer analyzer; Namespace fileNs; @Before public void setUp() { context = new MumblerContext();
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // public static final String ID = "mumbler"; // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public static final String TOP_NS = "<top>"; // // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java // public class MumblerContext { // private final FrameDescriptor globalFrameDescriptor; // private final Namespace globalNamespace; // private final MaterializedFrame globalFrame; // private final MumblerLanguage lang; // // public MumblerContext() { // this(null); // } // // public MumblerContext(MumblerLanguage lang) { // this.globalFrameDescriptor = new FrameDescriptor(); // this.globalNamespace = new Namespace(this.globalFrameDescriptor); // this.globalFrame = this.initGlobalFrame(lang); // this.lang = lang; // } // // private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { // VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, // this.globalFrameDescriptor); // addGlobalFunctions(lang, frame); // return frame.materialize(); // } // // private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { // FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); // virtualFrame.setObject(frameDescriptor.addFrameSlot("println"), // createBuiltinFunction(lang, PrintlnBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("+"), // createBuiltinFunction(lang, AddBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("-"), // createBuiltinFunction(lang, SubBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("*"), // createBuiltinFunction(lang, MulBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("/"), // createBuiltinFunction(lang, DivBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("%"), // createBuiltinFunction(lang, ModBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("="), // createBuiltinFunction(lang, EqualBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("<"), // createBuiltinFunction(lang, LessThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot(">"), // createBuiltinFunction(lang, GreaterThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("list"), // createBuiltinFunction(lang, ListBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cons"), // createBuiltinFunction(lang, ConsBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("car"), // createBuiltinFunction(lang, CarBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cdr"), // createBuiltinFunction(lang, CdrBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("now"), // createBuiltinFunction(lang, NowBuiltinNodeFactory.getInstance(), // virtualFrame)); // // virtualFrame.setObject(frameDescriptor.addFrameSlot("eval"), // // createBuiltinFunction(EvalBuiltinNodeFactory.getInstance(), // // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("read"), // createBuiltinFunction(lang, ReadBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("sleep"), // createBuiltinFunction(lang, SleepBuiltinNodeFactory.getInstance(), // virtualFrame)); // } // // /** // * @return A {@link MaterializedFrame} on the heap that contains all global // * values. // */ // public MaterializedFrame getGlobalFrame() { // return this.globalFrame; // } // // public Namespace getGlobalNamespace() { // return this.globalNamespace; // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // Path: lang/src/test/java/mumbler/truffle/parser/AnalyzerTest.java import static mumbler.truffle.MumblerLanguage.ID; import static mumbler.truffle.parser.Namespace.TOP_NS; import java.io.IOException; import mumbler.truffle.MumblerContext; import mumbler.truffle.syntax.ListSyntax; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.source.Source; package mumbler.truffle.parser; public class AnalyzerTest { MumblerContext context; Analyzer analyzer; Namespace fileNs; @Before public void setUp() { context = new MumblerContext();
fileNs = new Namespace(TOP_NS, context.getGlobalNamespace());
cesquivias/mumbler
lang/src/test/java/mumbler/truffle/parser/AnalyzerTest.java
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // public static final String ID = "mumbler"; // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public static final String TOP_NS = "<top>"; // // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java // public class MumblerContext { // private final FrameDescriptor globalFrameDescriptor; // private final Namespace globalNamespace; // private final MaterializedFrame globalFrame; // private final MumblerLanguage lang; // // public MumblerContext() { // this(null); // } // // public MumblerContext(MumblerLanguage lang) { // this.globalFrameDescriptor = new FrameDescriptor(); // this.globalNamespace = new Namespace(this.globalFrameDescriptor); // this.globalFrame = this.initGlobalFrame(lang); // this.lang = lang; // } // // private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { // VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, // this.globalFrameDescriptor); // addGlobalFunctions(lang, frame); // return frame.materialize(); // } // // private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { // FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); // virtualFrame.setObject(frameDescriptor.addFrameSlot("println"), // createBuiltinFunction(lang, PrintlnBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("+"), // createBuiltinFunction(lang, AddBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("-"), // createBuiltinFunction(lang, SubBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("*"), // createBuiltinFunction(lang, MulBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("/"), // createBuiltinFunction(lang, DivBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("%"), // createBuiltinFunction(lang, ModBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("="), // createBuiltinFunction(lang, EqualBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("<"), // createBuiltinFunction(lang, LessThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot(">"), // createBuiltinFunction(lang, GreaterThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("list"), // createBuiltinFunction(lang, ListBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cons"), // createBuiltinFunction(lang, ConsBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("car"), // createBuiltinFunction(lang, CarBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cdr"), // createBuiltinFunction(lang, CdrBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("now"), // createBuiltinFunction(lang, NowBuiltinNodeFactory.getInstance(), // virtualFrame)); // // virtualFrame.setObject(frameDescriptor.addFrameSlot("eval"), // // createBuiltinFunction(EvalBuiltinNodeFactory.getInstance(), // // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("read"), // createBuiltinFunction(lang, ReadBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("sleep"), // createBuiltinFunction(lang, SleepBuiltinNodeFactory.getInstance(), // virtualFrame)); // } // // /** // * @return A {@link MaterializedFrame} on the heap that contains all global // * values. // */ // public MaterializedFrame getGlobalFrame() { // return this.globalFrame; // } // // public Namespace getGlobalNamespace() { // return this.globalNamespace; // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // }
import static mumbler.truffle.MumblerLanguage.ID; import static mumbler.truffle.parser.Namespace.TOP_NS; import java.io.IOException; import mumbler.truffle.MumblerContext; import mumbler.truffle.syntax.ListSyntax; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.source.Source;
package mumbler.truffle.parser; public class AnalyzerTest { MumblerContext context; Analyzer analyzer; Namespace fileNs; @Before public void setUp() { context = new MumblerContext(); fileNs = new Namespace(TOP_NS, context.getGlobalNamespace()); analyzer = new Analyzer(this.fileNs); } @Test(expected = MumblerReadException.class) public void exceptionOnDefineTooManyArguments() {
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // public static final String ID = "mumbler"; // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public static final String TOP_NS = "<top>"; // // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java // public class MumblerContext { // private final FrameDescriptor globalFrameDescriptor; // private final Namespace globalNamespace; // private final MaterializedFrame globalFrame; // private final MumblerLanguage lang; // // public MumblerContext() { // this(null); // } // // public MumblerContext(MumblerLanguage lang) { // this.globalFrameDescriptor = new FrameDescriptor(); // this.globalNamespace = new Namespace(this.globalFrameDescriptor); // this.globalFrame = this.initGlobalFrame(lang); // this.lang = lang; // } // // private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { // VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, // this.globalFrameDescriptor); // addGlobalFunctions(lang, frame); // return frame.materialize(); // } // // private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { // FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); // virtualFrame.setObject(frameDescriptor.addFrameSlot("println"), // createBuiltinFunction(lang, PrintlnBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("+"), // createBuiltinFunction(lang, AddBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("-"), // createBuiltinFunction(lang, SubBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("*"), // createBuiltinFunction(lang, MulBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("/"), // createBuiltinFunction(lang, DivBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("%"), // createBuiltinFunction(lang, ModBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("="), // createBuiltinFunction(lang, EqualBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("<"), // createBuiltinFunction(lang, LessThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot(">"), // createBuiltinFunction(lang, GreaterThanBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("list"), // createBuiltinFunction(lang, ListBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cons"), // createBuiltinFunction(lang, ConsBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("car"), // createBuiltinFunction(lang, CarBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("cdr"), // createBuiltinFunction(lang, CdrBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("now"), // createBuiltinFunction(lang, NowBuiltinNodeFactory.getInstance(), // virtualFrame)); // // virtualFrame.setObject(frameDescriptor.addFrameSlot("eval"), // // createBuiltinFunction(EvalBuiltinNodeFactory.getInstance(), // // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("read"), // createBuiltinFunction(lang, ReadBuiltinNodeFactory.getInstance(), // virtualFrame)); // virtualFrame.setObject(frameDescriptor.addFrameSlot("sleep"), // createBuiltinFunction(lang, SleepBuiltinNodeFactory.getInstance(), // virtualFrame)); // } // // /** // * @return A {@link MaterializedFrame} on the heap that contains all global // * values. // */ // public MaterializedFrame getGlobalFrame() { // return this.globalFrame; // } // // public Namespace getGlobalNamespace() { // return this.globalNamespace; // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // Path: lang/src/test/java/mumbler/truffle/parser/AnalyzerTest.java import static mumbler.truffle.MumblerLanguage.ID; import static mumbler.truffle.parser.Namespace.TOP_NS; import java.io.IOException; import mumbler.truffle.MumblerContext; import mumbler.truffle.syntax.ListSyntax; import org.junit.Before; import org.junit.Test; import com.oracle.truffle.api.source.Source; package mumbler.truffle.parser; public class AnalyzerTest { MumblerContext context; Analyzer analyzer; Namespace fileNs; @Before public void setUp() { context = new MumblerContext(); fileNs = new Namespace(TOP_NS, context.getGlobalNamespace()); analyzer = new Analyzer(this.fileNs); } @Test(expected = MumblerReadException.class) public void exceptionOnDefineTooManyArguments() {
ListSyntax sexp = read("(define foo 1 bar)");
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/relational/LessThanBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName="<") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/relational/LessThanBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName="<") @GenerateNodeFactory
public abstract class LessThanBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/MumblerContext.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public class Namespace { // public static final int LEVEL_GLOBAL = -1; // public static final int LEVEL_UNDEFINED = -2; // // /** // * The name for the namespace at the top level of a file. // */ // public static final String TOP_NS = "<top>"; // // /** // * The name of the global namespace that contains all predefined variables. // */ // private static final String GLOBAL_NS = "<global>"; // // private final String functionName; // private final Namespace parent; // private final FrameDescriptor frameDescriptor; // // public Namespace(FrameDescriptor frameDescriptor) { // this.functionName = GLOBAL_NS; // this.parent = null; // this.frameDescriptor = frameDescriptor; // } // // public Namespace(String name, Namespace parent) { // this.functionName = name; // this.parent = parent; // this.frameDescriptor = new FrameDescriptor(); // } // // public String getFunctionName() { // return this.functionName; // } // // public Namespace getParent() { // return this.parent; // } // // public FrameDescriptor getFrameDescriptor() { // return this.frameDescriptor; // } // // public FrameSlot addIdentifier(String id) { // return this.frameDescriptor.addFrameSlot(id); // } // // public Pair<Integer, FrameSlot> getIdentifier(String id) { // int depth = 0; // Namespace current = this; // FrameSlot slot = current.frameDescriptor.findFrameSlot(id); // while (slot == null) { // depth++; // current = current.parent; // if (current == null) { // return new Pair<>(LEVEL_UNDEFINED, null); // } // slot = current.frameDescriptor.findFrameSlot(id); // } // if (current.parent == null) { // return new Pair<>(LEVEL_GLOBAL, slot); // } // return new Pair<>(depth, slot); // } // }
import static mumbler.truffle.node.builtin.BuiltinNode.createBuiltinFunction; import mumbler.truffle.node.builtin.arithmetic.AddBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.DivBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.ModBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.MulBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.SubBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.NowBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.PrintlnBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.SleepBuiltinNodeFactory; import mumbler.truffle.node.builtin.lang.ReadBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CarBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CdrBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ConsBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ListBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.EqualBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.GreaterThanBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.LessThanBuiltinNodeFactory; import mumbler.truffle.parser.Namespace; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle; public class MumblerContext { private final FrameDescriptor globalFrameDescriptor;
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public class Namespace { // public static final int LEVEL_GLOBAL = -1; // public static final int LEVEL_UNDEFINED = -2; // // /** // * The name for the namespace at the top level of a file. // */ // public static final String TOP_NS = "<top>"; // // /** // * The name of the global namespace that contains all predefined variables. // */ // private static final String GLOBAL_NS = "<global>"; // // private final String functionName; // private final Namespace parent; // private final FrameDescriptor frameDescriptor; // // public Namespace(FrameDescriptor frameDescriptor) { // this.functionName = GLOBAL_NS; // this.parent = null; // this.frameDescriptor = frameDescriptor; // } // // public Namespace(String name, Namespace parent) { // this.functionName = name; // this.parent = parent; // this.frameDescriptor = new FrameDescriptor(); // } // // public String getFunctionName() { // return this.functionName; // } // // public Namespace getParent() { // return this.parent; // } // // public FrameDescriptor getFrameDescriptor() { // return this.frameDescriptor; // } // // public FrameSlot addIdentifier(String id) { // return this.frameDescriptor.addFrameSlot(id); // } // // public Pair<Integer, FrameSlot> getIdentifier(String id) { // int depth = 0; // Namespace current = this; // FrameSlot slot = current.frameDescriptor.findFrameSlot(id); // while (slot == null) { // depth++; // current = current.parent; // if (current == null) { // return new Pair<>(LEVEL_UNDEFINED, null); // } // slot = current.frameDescriptor.findFrameSlot(id); // } // if (current.parent == null) { // return new Pair<>(LEVEL_GLOBAL, slot); // } // return new Pair<>(depth, slot); // } // } // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java import static mumbler.truffle.node.builtin.BuiltinNode.createBuiltinFunction; import mumbler.truffle.node.builtin.arithmetic.AddBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.DivBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.ModBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.MulBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.SubBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.NowBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.PrintlnBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.SleepBuiltinNodeFactory; import mumbler.truffle.node.builtin.lang.ReadBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CarBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CdrBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ConsBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ListBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.EqualBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.GreaterThanBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.LessThanBuiltinNodeFactory; import mumbler.truffle.parser.Namespace; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle; public class MumblerContext { private final FrameDescriptor globalFrameDescriptor;
private final Namespace globalNamespace;
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/MumblerContext.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public class Namespace { // public static final int LEVEL_GLOBAL = -1; // public static final int LEVEL_UNDEFINED = -2; // // /** // * The name for the namespace at the top level of a file. // */ // public static final String TOP_NS = "<top>"; // // /** // * The name of the global namespace that contains all predefined variables. // */ // private static final String GLOBAL_NS = "<global>"; // // private final String functionName; // private final Namespace parent; // private final FrameDescriptor frameDescriptor; // // public Namespace(FrameDescriptor frameDescriptor) { // this.functionName = GLOBAL_NS; // this.parent = null; // this.frameDescriptor = frameDescriptor; // } // // public Namespace(String name, Namespace parent) { // this.functionName = name; // this.parent = parent; // this.frameDescriptor = new FrameDescriptor(); // } // // public String getFunctionName() { // return this.functionName; // } // // public Namespace getParent() { // return this.parent; // } // // public FrameDescriptor getFrameDescriptor() { // return this.frameDescriptor; // } // // public FrameSlot addIdentifier(String id) { // return this.frameDescriptor.addFrameSlot(id); // } // // public Pair<Integer, FrameSlot> getIdentifier(String id) { // int depth = 0; // Namespace current = this; // FrameSlot slot = current.frameDescriptor.findFrameSlot(id); // while (slot == null) { // depth++; // current = current.parent; // if (current == null) { // return new Pair<>(LEVEL_UNDEFINED, null); // } // slot = current.frameDescriptor.findFrameSlot(id); // } // if (current.parent == null) { // return new Pair<>(LEVEL_GLOBAL, slot); // } // return new Pair<>(depth, slot); // } // }
import static mumbler.truffle.node.builtin.BuiltinNode.createBuiltinFunction; import mumbler.truffle.node.builtin.arithmetic.AddBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.DivBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.ModBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.MulBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.SubBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.NowBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.PrintlnBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.SleepBuiltinNodeFactory; import mumbler.truffle.node.builtin.lang.ReadBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CarBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CdrBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ConsBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ListBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.EqualBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.GreaterThanBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.LessThanBuiltinNodeFactory; import mumbler.truffle.parser.Namespace; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle; public class MumblerContext { private final FrameDescriptor globalFrameDescriptor; private final Namespace globalNamespace; private final MaterializedFrame globalFrame; private final MumblerLanguage lang; public MumblerContext() { this(null); } public MumblerContext(MumblerLanguage lang) { this.globalFrameDescriptor = new FrameDescriptor(); this.globalNamespace = new Namespace(this.globalFrameDescriptor); this.globalFrame = this.initGlobalFrame(lang); this.lang = lang; } private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, this.globalFrameDescriptor); addGlobalFunctions(lang, frame); return frame.materialize(); } private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); virtualFrame.setObject(frameDescriptor.addFrameSlot("println"),
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // // Path: lang/src/main/java/mumbler/truffle/parser/Namespace.java // public class Namespace { // public static final int LEVEL_GLOBAL = -1; // public static final int LEVEL_UNDEFINED = -2; // // /** // * The name for the namespace at the top level of a file. // */ // public static final String TOP_NS = "<top>"; // // /** // * The name of the global namespace that contains all predefined variables. // */ // private static final String GLOBAL_NS = "<global>"; // // private final String functionName; // private final Namespace parent; // private final FrameDescriptor frameDescriptor; // // public Namespace(FrameDescriptor frameDescriptor) { // this.functionName = GLOBAL_NS; // this.parent = null; // this.frameDescriptor = frameDescriptor; // } // // public Namespace(String name, Namespace parent) { // this.functionName = name; // this.parent = parent; // this.frameDescriptor = new FrameDescriptor(); // } // // public String getFunctionName() { // return this.functionName; // } // // public Namespace getParent() { // return this.parent; // } // // public FrameDescriptor getFrameDescriptor() { // return this.frameDescriptor; // } // // public FrameSlot addIdentifier(String id) { // return this.frameDescriptor.addFrameSlot(id); // } // // public Pair<Integer, FrameSlot> getIdentifier(String id) { // int depth = 0; // Namespace current = this; // FrameSlot slot = current.frameDescriptor.findFrameSlot(id); // while (slot == null) { // depth++; // current = current.parent; // if (current == null) { // return new Pair<>(LEVEL_UNDEFINED, null); // } // slot = current.frameDescriptor.findFrameSlot(id); // } // if (current.parent == null) { // return new Pair<>(LEVEL_GLOBAL, slot); // } // return new Pair<>(depth, slot); // } // } // Path: lang/src/main/java/mumbler/truffle/MumblerContext.java import static mumbler.truffle.node.builtin.BuiltinNode.createBuiltinFunction; import mumbler.truffle.node.builtin.arithmetic.AddBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.DivBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.ModBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.MulBuiltinNodeFactory; import mumbler.truffle.node.builtin.arithmetic.SubBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.NowBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.PrintlnBuiltinNodeFactory; import mumbler.truffle.node.builtin.io.SleepBuiltinNodeFactory; import mumbler.truffle.node.builtin.lang.ReadBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CarBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.CdrBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ConsBuiltinNodeFactory; import mumbler.truffle.node.builtin.list.ListBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.EqualBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.GreaterThanBuiltinNodeFactory; import mumbler.truffle.node.builtin.relational.LessThanBuiltinNodeFactory; import mumbler.truffle.parser.Namespace; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.MaterializedFrame; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle; public class MumblerContext { private final FrameDescriptor globalFrameDescriptor; private final Namespace globalNamespace; private final MaterializedFrame globalFrame; private final MumblerLanguage lang; public MumblerContext() { this(null); } public MumblerContext(MumblerLanguage lang) { this.globalFrameDescriptor = new FrameDescriptor(); this.globalNamespace = new Namespace(this.globalFrameDescriptor); this.globalFrame = this.initGlobalFrame(lang); this.lang = lang; } private MaterializedFrame initGlobalFrame(MumblerLanguage lang) { VirtualFrame frame = Truffle.getRuntime().createVirtualFrame(null, this.globalFrameDescriptor); addGlobalFunctions(lang, frame); return frame.materialize(); } private static void addGlobalFunctions(MumblerLanguage lang, VirtualFrame virtualFrame) { FrameDescriptor frameDescriptor = virtualFrame.getFrameDescriptor(); virtualFrame.setObject(frameDescriptor.addFrameSlot("println"),
createBuiltinFunction(lang, PrintlnBuiltinNodeFactory.getInstance(),
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/list/ConsBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="cons") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/list/ConsBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="cons") @GenerateNodeFactory
public abstract class ConsBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/list/ConsBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="cons") @GenerateNodeFactory public abstract class ConsBuiltinNode extends BuiltinNode { @Specialization @SuppressWarnings("unchecked")
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/list/ConsBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="cons") @GenerateNodeFactory public abstract class ConsBuiltinNode extends BuiltinNode { @Specialization @SuppressWarnings("unchecked")
protected MumblerList<?> cons(Object value, MumblerList<?> list) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/relational/EqualBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName = "=") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/relational/EqualBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName = "=") @GenerateNodeFactory
public abstract class EqualBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/relational/EqualBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName = "=") @GenerateNodeFactory public abstract class EqualBuiltinNode extends BuiltinNode { @Specialization protected boolean equals(long value0, long value1) { return value0 == value1; } @Specialization protected boolean equals(BigInteger value0, BigInteger value1) { return value0.equals(value1); } @Specialization protected boolean equals(boolean value0, boolean value1) { return value0 == value1; } @Specialization
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/relational/EqualBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName = "=") @GenerateNodeFactory public abstract class EqualBuiltinNode extends BuiltinNode { @Specialization protected boolean equals(long value0, long value1) { return value0 == value1; } @Specialization protected boolean equals(BigInteger value0, BigInteger value1) { return value0.equals(value1); } @Specialization protected boolean equals(boolean value0, boolean value1) { return value0 == value1; } @Specialization
protected boolean equals(MumblerList<?> value0, MumblerList<?> value1) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/call/InvokeNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerFunction.java // public class MumblerFunction { // public final RootCallTarget callTarget; // private MaterializedFrame lexicalScope; // // public MumblerFunction(RootCallTarget callTarget) { // this.callTarget = callTarget; // } // // public MaterializedFrame getLexicalScope() { // return lexicalScope; // } // // public void setLexicalScope(MaterializedFrame lexicalScope) { // this.lexicalScope = lexicalScope; // } // // public static MumblerFunction create(MumblerLanguage lang, FrameSlot[] arguments, // MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { // return new MumblerFunction( // Truffle.getRuntime().createCallTarget( // MumblerRootNode.create(lang, arguments, bodyNodes, frameDescriptor))); // } // }
import java.util.Arrays; import mumbler.truffle.node.MumblerNode; import mumbler.truffle.type.MumblerFunction; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.dsl.UnsupportedSpecializationException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.UnexpectedResultException; import com.oracle.truffle.api.source.SourceSection;
package mumbler.truffle.node.call; public class InvokeNode extends MumblerNode { @Child protected MumblerNode functionNode; @Children protected final MumblerNode[] argumentNodes; @Child protected DispatchNode dispatchNode; public InvokeNode(MumblerNode functionNode, MumblerNode[] argumentNodes, SourceSection sourceSection) { this.functionNode = functionNode; this.argumentNodes = argumentNodes; this.dispatchNode = new UninitializedDispatchNode(); setSourceSection(sourceSection); } @Override @ExplodeLoop public Object execute(VirtualFrame virtualFrame) {
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerFunction.java // public class MumblerFunction { // public final RootCallTarget callTarget; // private MaterializedFrame lexicalScope; // // public MumblerFunction(RootCallTarget callTarget) { // this.callTarget = callTarget; // } // // public MaterializedFrame getLexicalScope() { // return lexicalScope; // } // // public void setLexicalScope(MaterializedFrame lexicalScope) { // this.lexicalScope = lexicalScope; // } // // public static MumblerFunction create(MumblerLanguage lang, FrameSlot[] arguments, // MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { // return new MumblerFunction( // Truffle.getRuntime().createCallTarget( // MumblerRootNode.create(lang, arguments, bodyNodes, frameDescriptor))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/call/InvokeNode.java import java.util.Arrays; import mumbler.truffle.node.MumblerNode; import mumbler.truffle.type.MumblerFunction; import com.oracle.truffle.api.CallTarget; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.dsl.UnsupportedSpecializationException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.UnexpectedResultException; import com.oracle.truffle.api.source.SourceSection; package mumbler.truffle.node.call; public class InvokeNode extends MumblerNode { @Child protected MumblerNode functionNode; @Children protected final MumblerNode[] argumentNodes; @Child protected DispatchNode dispatchNode; public InvokeNode(MumblerNode functionNode, MumblerNode[] argumentNodes, SourceSection sourceSection) { this.functionNode = functionNode; this.argumentNodes = argumentNodes; this.dispatchNode = new UninitializedDispatchNode(); setSourceSection(sourceSection); } @Override @ExplodeLoop public Object execute(VirtualFrame virtualFrame) {
MumblerFunction function = this.evaluateFunction(virtualFrame);
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/DivBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "/") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/DivBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "/") @GenerateNodeFactory
public abstract class DivBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/literal/StringNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/StringSyntax.java // public class StringSyntax extends Syntax<String> { // public StringSyntax(String value, SourceSection source) { // super(value, source); // } // }
import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.StringSyntax; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle.node.literal; public class StringNode extends MumblerNode { public final String str;
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/StringSyntax.java // public class StringSyntax extends Syntax<String> { // public StringSyntax(String value, SourceSection source) { // super(value, source); // } // } // Path: lang/src/main/java/mumbler/truffle/node/literal/StringNode.java import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.StringSyntax; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle.node.literal; public class StringNode extends MumblerNode { public final String str;
public StringNode(StringSyntax str) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/literal/BigIntegerNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/BigIntegerSyntax.java // public class BigIntegerSyntax extends Syntax<BigInteger> { // public BigIntegerSyntax(BigInteger value, SourceSection source) { // super(value, source); // } // }
import java.math.BigInteger; import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.BigIntegerSyntax; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle.node.literal; public class BigIntegerNode extends MumblerNode { public final BigInteger value;
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/BigIntegerSyntax.java // public class BigIntegerSyntax extends Syntax<BigInteger> { // public BigIntegerSyntax(BigInteger value, SourceSection source) { // super(value, source); // } // } // Path: lang/src/main/java/mumbler/truffle/node/literal/BigIntegerNode.java import java.math.BigInteger; import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.BigIntegerSyntax; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle.node.literal; public class BigIntegerNode extends MumblerNode { public final BigInteger value;
public BigIntegerNode(BigIntegerSyntax number) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/parser/SexpListener.java
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList;
package mumbler.truffle.parser; /** * A simple walk through the syntax objects that is created by {@link Reader}. * Override the on- methods to be alerted when different types are encountered. * Convenience methods for special forms are included. * */ public abstract class SexpListener { private static enum ListType { LIST, DEFINE, LAMBDA, IF, QUOTE; } public void walk(Syntax<?> sexp) {
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/parser/SexpListener.java import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList; package mumbler.truffle.parser; /** * A simple walk through the syntax objects that is created by {@link Reader}. * Override the on- methods to be alerted when different types are encountered. * Convenience methods for special forms are included. * */ public abstract class SexpListener { private static enum ListType { LIST, DEFINE, LAMBDA, IF, QUOTE; } public void walk(Syntax<?> sexp) {
if (sexp instanceof ListSyntax) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/parser/SexpListener.java
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList;
onIf(list); listType = ListType.IF; } else if (isListOf("quote", list)) { onQuote(list); listType = ListType.QUOTE; } else { onList(list); } for (Syntax<?> sub : list.getValue()) { walk(sub); } switch (listType) { case DEFINE: onDefineExit(list); break; case LAMBDA: onLambdaExit(list); break; case IF: onIfExit(list); break; case QUOTE: onQuoteExit(list); break; case LIST: onListExit(list); break; }
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/parser/SexpListener.java import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList; onIf(list); listType = ListType.IF; } else if (isListOf("quote", list)) { onQuote(list); listType = ListType.QUOTE; } else { onList(list); } for (Syntax<?> sub : list.getValue()) { walk(sub); } switch (listType) { case DEFINE: onDefineExit(list); break; case LAMBDA: onLambdaExit(list); break; case IF: onIfExit(list); break; case QUOTE: onQuoteExit(list); break; case LIST: onListExit(list); break; }
} else if (sexp instanceof SymbolSyntax) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/parser/SexpListener.java
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList;
onList(list); } for (Syntax<?> sub : list.getValue()) { walk(sub); } switch (listType) { case DEFINE: onDefineExit(list); break; case LAMBDA: onLambdaExit(list); break; case IF: onIfExit(list); break; case QUOTE: onQuoteExit(list); break; case LIST: onListExit(list); break; } } else if (sexp instanceof SymbolSyntax) { onSymbol((SymbolSyntax) sexp); } } private boolean isListOf(String name, ListSyntax listSyntax) {
// Path: lang/src/main/java/mumbler/truffle/syntax/ListSyntax.java // public class ListSyntax extends Syntax<MumblerList<? extends Syntax<?>>> { // public ListSyntax(MumblerList<? extends Syntax<?>> value, // SourceSection sourceSection) { // super(value, sourceSection); // } // // @Override // public Object strip() { // List<Object> list = new ArrayList<Object>(); // for (Syntax<? extends Object> syntax : getValue()) { // list.add(syntax.strip()); // } // return MumblerList.list(list); // } // // @Override // public String getName() { // if (super.getName() != null) { // return super.getName(); // } // if (this.getValue().size() == 0) { // return "()"; // } // return this.getValue().car().getValue().toString() + "-" + this.hashCode(); // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/SymbolSyntax.java // public class SymbolSyntax extends Syntax<MumblerSymbol> { // public SymbolSyntax(MumblerSymbol value, SourceSection source) { // super(value, source); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/parser/SexpListener.java import mumbler.truffle.syntax.ListSyntax; import mumbler.truffle.syntax.SymbolSyntax; import mumbler.truffle.type.MumblerList; onList(list); } for (Syntax<?> sub : list.getValue()) { walk(sub); } switch (listType) { case DEFINE: onDefineExit(list); break; case LAMBDA: onLambdaExit(list); break; case IF: onIfExit(list); break; case QUOTE: onQuoteExit(list); break; case LIST: onListExit(list); break; } } else if (sexp instanceof SymbolSyntax) { onSymbol((SymbolSyntax) sexp); } } private boolean isListOf(String name, ListSyntax listSyntax) {
MumblerList<? extends Syntax<?>> list = listSyntax.getValue();
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/ModBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "%") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/arithmetic/ModBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.arithmetic; @NodeInfo(shortName = "%") @GenerateNodeFactory
public abstract class ModBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // @TruffleLanguage.Registration(id = ID, name = "Mumbler", version = "0.3", // characterMimeTypes = MumblerLanguage.MIME_TYPE, defaultMimeType = MumblerLanguage.MIME_TYPE) // public class MumblerLanguage extends TruffleLanguage<Object> { // public static final String ID = "mumbler"; // public static final String MIME_TYPE = "application/x-mumbler"; // // private static final boolean TAIL_CALL_OPTIMIZATION_ENABLED = false; // // public MumblerLanguage() { // } // // @Override // protected Object createContext(TruffleLanguage.Env env) { // return new MumblerContext(this); // } // // @Override // protected CallTarget parse(ParsingRequest parsingRequest) throws IOException { // MumblerContext context = new MumblerContext(this); // ListSyntax sexp = Reader.read(parsingRequest.getSource()); // Converter converter = new Converter(this, TAIL_CALL_OPTIMIZATION_ENABLED); // MumblerNode[] nodes = converter.convertSexp(context, sexp); // MumblerFunction function = MumblerFunction.create(this, new FrameSlot[] {}, // nodes, context.getGlobalFrame().getFrameDescriptor()); // return function.callTarget; // } // // @Override // protected boolean isObjectOfLanguage(Object obj) { // return false; // } // // } // // Path: lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java // public class ReadArgumentNode extends MumblerNode { // public final int argumentIndex; // // public ReadArgumentNode(int argumentIndex) { // this.argumentIndex = argumentIndex; // } // // @Override // public Object execute(VirtualFrame virtualFrame) { // if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { // CompilerDirectives.transferToInterpreterAndInvalidate(); // throw new MumblerException("Not enough arguments passed. Missing " + // (this.argumentIndex + 1) + "th argument"); // } // return this.getArgument(virtualFrame, this.argumentIndex); // } // // @Override // public String toString() { // return "(arg " + this.argumentIndex + ")"; // } // }
import java.util.Arrays; import mumbler.truffle.MumblerLanguage; import mumbler.truffle.node.read.ReadArgumentNode; import mumbler.truffle.node.special.DefineNodeGen; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.RootNode;
package mumbler.truffle.node; public class MumblerRootNode extends RootNode { @Children private final MumblerNode[] bodyNodes; @CompilationFinal public String name;
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // @TruffleLanguage.Registration(id = ID, name = "Mumbler", version = "0.3", // characterMimeTypes = MumblerLanguage.MIME_TYPE, defaultMimeType = MumblerLanguage.MIME_TYPE) // public class MumblerLanguage extends TruffleLanguage<Object> { // public static final String ID = "mumbler"; // public static final String MIME_TYPE = "application/x-mumbler"; // // private static final boolean TAIL_CALL_OPTIMIZATION_ENABLED = false; // // public MumblerLanguage() { // } // // @Override // protected Object createContext(TruffleLanguage.Env env) { // return new MumblerContext(this); // } // // @Override // protected CallTarget parse(ParsingRequest parsingRequest) throws IOException { // MumblerContext context = new MumblerContext(this); // ListSyntax sexp = Reader.read(parsingRequest.getSource()); // Converter converter = new Converter(this, TAIL_CALL_OPTIMIZATION_ENABLED); // MumblerNode[] nodes = converter.convertSexp(context, sexp); // MumblerFunction function = MumblerFunction.create(this, new FrameSlot[] {}, // nodes, context.getGlobalFrame().getFrameDescriptor()); // return function.callTarget; // } // // @Override // protected boolean isObjectOfLanguage(Object obj) { // return false; // } // // } // // Path: lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java // public class ReadArgumentNode extends MumblerNode { // public final int argumentIndex; // // public ReadArgumentNode(int argumentIndex) { // this.argumentIndex = argumentIndex; // } // // @Override // public Object execute(VirtualFrame virtualFrame) { // if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { // CompilerDirectives.transferToInterpreterAndInvalidate(); // throw new MumblerException("Not enough arguments passed. Missing " + // (this.argumentIndex + 1) + "th argument"); // } // return this.getArgument(virtualFrame, this.argumentIndex); // } // // @Override // public String toString() { // return "(arg " + this.argumentIndex + ")"; // } // } // Path: lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java import java.util.Arrays; import mumbler.truffle.MumblerLanguage; import mumbler.truffle.node.read.ReadArgumentNode; import mumbler.truffle.node.special.DefineNodeGen; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.RootNode; package mumbler.truffle.node; public class MumblerRootNode extends RootNode { @Children private final MumblerNode[] bodyNodes; @CompilationFinal public String name;
public MumblerRootNode(MumblerLanguage lang, MumblerNode[] bodyNodes,
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // @TruffleLanguage.Registration(id = ID, name = "Mumbler", version = "0.3", // characterMimeTypes = MumblerLanguage.MIME_TYPE, defaultMimeType = MumblerLanguage.MIME_TYPE) // public class MumblerLanguage extends TruffleLanguage<Object> { // public static final String ID = "mumbler"; // public static final String MIME_TYPE = "application/x-mumbler"; // // private static final boolean TAIL_CALL_OPTIMIZATION_ENABLED = false; // // public MumblerLanguage() { // } // // @Override // protected Object createContext(TruffleLanguage.Env env) { // return new MumblerContext(this); // } // // @Override // protected CallTarget parse(ParsingRequest parsingRequest) throws IOException { // MumblerContext context = new MumblerContext(this); // ListSyntax sexp = Reader.read(parsingRequest.getSource()); // Converter converter = new Converter(this, TAIL_CALL_OPTIMIZATION_ENABLED); // MumblerNode[] nodes = converter.convertSexp(context, sexp); // MumblerFunction function = MumblerFunction.create(this, new FrameSlot[] {}, // nodes, context.getGlobalFrame().getFrameDescriptor()); // return function.callTarget; // } // // @Override // protected boolean isObjectOfLanguage(Object obj) { // return false; // } // // } // // Path: lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java // public class ReadArgumentNode extends MumblerNode { // public final int argumentIndex; // // public ReadArgumentNode(int argumentIndex) { // this.argumentIndex = argumentIndex; // } // // @Override // public Object execute(VirtualFrame virtualFrame) { // if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { // CompilerDirectives.transferToInterpreterAndInvalidate(); // throw new MumblerException("Not enough arguments passed. Missing " + // (this.argumentIndex + 1) + "th argument"); // } // return this.getArgument(virtualFrame, this.argumentIndex); // } // // @Override // public String toString() { // return "(arg " + this.argumentIndex + ")"; // } // }
import java.util.Arrays; import mumbler.truffle.MumblerLanguage; import mumbler.truffle.node.read.ReadArgumentNode; import mumbler.truffle.node.special.DefineNodeGen; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.RootNode;
package mumbler.truffle.node; public class MumblerRootNode extends RootNode { @Children private final MumblerNode[] bodyNodes; @CompilationFinal public String name; public MumblerRootNode(MumblerLanguage lang, MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { super(lang, frameDescriptor); this.bodyNodes = bodyNodes; } @Override @ExplodeLoop public Object execute(VirtualFrame virtualFrame) { int last = this.bodyNodes.length - 1; CompilerAsserts.compilationConstant(last); for (int i=0; i<last; i++) { this.bodyNodes[i].execute(virtualFrame); } return this.bodyNodes[last].execute(virtualFrame); } public static MumblerRootNode create(MumblerLanguage lang, FrameSlot[] argumentNames, MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { MumblerNode[] allNodes = new MumblerNode[argumentNames.length + bodyNodes.length]; for (int i=0; i<argumentNames.length; i++) { allNodes[i] = DefineNodeGen.create(
// Path: lang/src/main/java/mumbler/truffle/MumblerLanguage.java // @TruffleLanguage.Registration(id = ID, name = "Mumbler", version = "0.3", // characterMimeTypes = MumblerLanguage.MIME_TYPE, defaultMimeType = MumblerLanguage.MIME_TYPE) // public class MumblerLanguage extends TruffleLanguage<Object> { // public static final String ID = "mumbler"; // public static final String MIME_TYPE = "application/x-mumbler"; // // private static final boolean TAIL_CALL_OPTIMIZATION_ENABLED = false; // // public MumblerLanguage() { // } // // @Override // protected Object createContext(TruffleLanguage.Env env) { // return new MumblerContext(this); // } // // @Override // protected CallTarget parse(ParsingRequest parsingRequest) throws IOException { // MumblerContext context = new MumblerContext(this); // ListSyntax sexp = Reader.read(parsingRequest.getSource()); // Converter converter = new Converter(this, TAIL_CALL_OPTIMIZATION_ENABLED); // MumblerNode[] nodes = converter.convertSexp(context, sexp); // MumblerFunction function = MumblerFunction.create(this, new FrameSlot[] {}, // nodes, context.getGlobalFrame().getFrameDescriptor()); // return function.callTarget; // } // // @Override // protected boolean isObjectOfLanguage(Object obj) { // return false; // } // // } // // Path: lang/src/main/java/mumbler/truffle/node/read/ReadArgumentNode.java // public class ReadArgumentNode extends MumblerNode { // public final int argumentIndex; // // public ReadArgumentNode(int argumentIndex) { // this.argumentIndex = argumentIndex; // } // // @Override // public Object execute(VirtualFrame virtualFrame) { // if (!this.isArgumentIndexInRange(virtualFrame, this.argumentIndex)) { // CompilerDirectives.transferToInterpreterAndInvalidate(); // throw new MumblerException("Not enough arguments passed. Missing " + // (this.argumentIndex + 1) + "th argument"); // } // return this.getArgument(virtualFrame, this.argumentIndex); // } // // @Override // public String toString() { // return "(arg " + this.argumentIndex + ")"; // } // } // Path: lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java import java.util.Arrays; import mumbler.truffle.MumblerLanguage; import mumbler.truffle.node.read.ReadArgumentNode; import mumbler.truffle.node.special.DefineNodeGen; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.RootNode; package mumbler.truffle.node; public class MumblerRootNode extends RootNode { @Children private final MumblerNode[] bodyNodes; @CompilationFinal public String name; public MumblerRootNode(MumblerLanguage lang, MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { super(lang, frameDescriptor); this.bodyNodes = bodyNodes; } @Override @ExplodeLoop public Object execute(VirtualFrame virtualFrame) { int last = this.bodyNodes.length - 1; CompilerAsserts.compilationConstant(last); for (int i=0; i<last; i++) { this.bodyNodes[i].execute(virtualFrame); } return this.bodyNodes[last].execute(virtualFrame); } public static MumblerRootNode create(MumblerLanguage lang, FrameSlot[] argumentNames, MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { MumblerNode[] allNodes = new MumblerNode[argumentNames.length + bodyNodes.length]; for (int i=0; i<argumentNames.length; i++) { allNodes[i] = DefineNodeGen.create(
new ReadArgumentNode(i), argumentNames[i]);
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/io/SleepBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "sleep") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/io/SleepBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "sleep") @GenerateNodeFactory
public abstract class SleepBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/type/MumblerList.java
// Path: lang/src/main/java/mumbler/truffle/MumblerException.java // public class MumblerException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public MumblerException(String message) { // super(message); // } // // @Override // public Throwable fillInStackTrace() { // CompilerAsserts.neverPartOfCompilation(); // return fillInMumblerStackTrace(this); // } // // public static Throwable fillInMumblerStackTrace(Throwable t) { // final List<StackTraceElement> stackTrace = new ArrayList<>(); // Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { // Node callNode = frame.getCallNode(); // if (callNode == null) { // return null; // } // RootNode root = callNode.getRootNode(); // // /* // * There should be no RootNodes other than SLRootNodes on the stack. Just for the // * case if this would change. // */ // String methodName = "$unknownFunction"; // if (root instanceof MumblerRootNode) { // methodName = ((MumblerRootNode) root).name; // } // // SourceSection sourceSection = callNode.getEncapsulatingSourceSection(); // Source source = sourceSection != null ? sourceSection.getSource() : null; // String sourceName = source != null ? source.getName() : null; // int lineNumber; // try { // lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1; // } catch (UnsupportedOperationException e) { // /* // * SourceSection#getLineLocation() may throw an UnsupportedOperationException. // */ // lineNumber = -1; // } // stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber)); // return null; // }); // t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()])); // return t; // } // }
import static java.util.Arrays.asList; import java.util.Iterator; import java.util.List; import mumbler.truffle.MumblerException;
} private MumblerList(T car, MumblerList<T> cdr) { this.car = car; this.cdr = cdr; this.length = cdr.length + 1; } @SafeVarargs public static <T> MumblerList<T> list(T... objs) { return list(asList(objs)); } public static <T> MumblerList<T> list(List<T> objs) { @SuppressWarnings("unchecked") MumblerList<T> l = (MumblerList<T>) EMPTY; for (int i=objs.size()-1; i>=0; i--) { l = l.cons(objs.get(i)); } return l; } public MumblerList<T> cons(T node) { return new MumblerList<T>(node, this); } public T car() { if (this != EMPTY) { return this.car; }
// Path: lang/src/main/java/mumbler/truffle/MumblerException.java // public class MumblerException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public MumblerException(String message) { // super(message); // } // // @Override // public Throwable fillInStackTrace() { // CompilerAsserts.neverPartOfCompilation(); // return fillInMumblerStackTrace(this); // } // // public static Throwable fillInMumblerStackTrace(Throwable t) { // final List<StackTraceElement> stackTrace = new ArrayList<>(); // Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { // Node callNode = frame.getCallNode(); // if (callNode == null) { // return null; // } // RootNode root = callNode.getRootNode(); // // /* // * There should be no RootNodes other than SLRootNodes on the stack. Just for the // * case if this would change. // */ // String methodName = "$unknownFunction"; // if (root instanceof MumblerRootNode) { // methodName = ((MumblerRootNode) root).name; // } // // SourceSection sourceSection = callNode.getEncapsulatingSourceSection(); // Source source = sourceSection != null ? sourceSection.getSource() : null; // String sourceName = source != null ? source.getName() : null; // int lineNumber; // try { // lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1; // } catch (UnsupportedOperationException e) { // /* // * SourceSection#getLineLocation() may throw an UnsupportedOperationException. // */ // lineNumber = -1; // } // stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber)); // return null; // }); // t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()])); // return t; // } // } // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java import static java.util.Arrays.asList; import java.util.Iterator; import java.util.List; import mumbler.truffle.MumblerException; } private MumblerList(T car, MumblerList<T> cdr) { this.car = car; this.cdr = cdr; this.length = cdr.length + 1; } @SafeVarargs public static <T> MumblerList<T> list(T... objs) { return list(asList(objs)); } public static <T> MumblerList<T> list(List<T> objs) { @SuppressWarnings("unchecked") MumblerList<T> l = (MumblerList<T>) EMPTY; for (int i=objs.size()-1; i>=0; i--) { l = l.cons(objs.get(i)); } return l; } public MumblerList<T> cons(T node) { return new MumblerList<T>(node, this); } public T car() { if (this != EMPTY) { return this.car; }
throw new MumblerException("Cannot car the empty list");
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/literal/BooleanNode.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/BooleanSyntax.java // public class BooleanSyntax extends Syntax<Boolean> { // public BooleanSyntax(boolean value, SourceSection source) { // super(value, source); // } // }
import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.BooleanSyntax; import com.oracle.truffle.api.frame.VirtualFrame;
package mumbler.truffle.node.literal; public class BooleanNode extends MumblerNode { public final boolean value;
// Path: lang/src/main/java/mumbler/truffle/node/MumblerNode.java // @TypeSystemReference(MumblerTypes.class) // @NodeInfo(language = "Mumbler Language", description = "The abstract base node for all expressions") // public abstract class MumblerNode extends Node { // @CompilationFinal // private SourceSection sourceSection; // // @CompilationFinal // private boolean isTail = false; // // @Override // public SourceSection getSourceSection() { // return this.sourceSection; // } // // public void setSourceSection(SourceSection sourceSection) { // this.sourceSection = sourceSection; // } // // public boolean isTail() { // return this.isTail; // } // // public void setIsTail() { // this.isTail = true; // } // // public abstract Object execute(VirtualFrame virtualFrame); // // public long executeLong(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectLong(this.execute(virtualFrame)); // } // // public boolean executeBoolean(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBoolean(this.execute(virtualFrame)); // } // // public BigInteger executeBigInteger(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectBigInteger(this.execute(virtualFrame)); // } // // public MumblerSymbol executeMumblerSymbol(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerSymbol(this.execute(virtualFrame)); // } // // public MumblerFunction executeMumblerFunction(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerFunction( // this.execute(virtualFrame)); // } // // public MumblerList<?> executeMumblerList(VirtualFrame virtualFrame) // throws UnexpectedResultException { // return MumblerTypesGen.expectMumblerList(this.execute(virtualFrame)); // } // // public String executeString(VirtualFrame virtualFrame) // throws UnexpectedResultException{ // return MumblerTypesGen.expectString(this.execute(virtualFrame)); // } // // protected boolean isArgumentIndexInRange(VirtualFrame virtualFrame, // int index) { // return (index + 1) < virtualFrame.getArguments().length; // } // // protected Object getArgument(VirtualFrame virtualFrame, int index) { // return virtualFrame.getArguments()[index + 1]; // } // // protected static MaterializedFrame getLexicalScope(Frame frame) { // Object[] args = frame.getArguments(); // if (args.length > 0) { // return (MaterializedFrame) frame.getArguments()[0]; // } else { // return null; // } // } // } // // Path: lang/src/main/java/mumbler/truffle/syntax/BooleanSyntax.java // public class BooleanSyntax extends Syntax<Boolean> { // public BooleanSyntax(boolean value, SourceSection source) { // super(value, source); // } // } // Path: lang/src/main/java/mumbler/truffle/node/literal/BooleanNode.java import mumbler.truffle.node.MumblerNode; import mumbler.truffle.syntax.BooleanSyntax; import com.oracle.truffle.api.frame.VirtualFrame; package mumbler.truffle.node.literal; public class BooleanNode extends MumblerNode { public final boolean value;
public BooleanNode(BooleanSyntax bool) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/list/ListBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization;
package mumbler.truffle.node.builtin.list; @GenerateNodeFactory public abstract class ListBuiltinNode extends BuiltinNode { @Specialization
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/list/ListBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; package mumbler.truffle.node.builtin.list; @GenerateNodeFactory public abstract class ListBuiltinNode extends BuiltinNode { @Specialization
protected MumblerList<Object> list(Object first, Object second) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/MumblerException.java
// Path: lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java // public class MumblerRootNode extends RootNode { // @Children private final MumblerNode[] bodyNodes; // @CompilationFinal public String name; // // public MumblerRootNode(MumblerLanguage lang, MumblerNode[] bodyNodes, // FrameDescriptor frameDescriptor) { // super(lang, frameDescriptor); // this.bodyNodes = bodyNodes; // } // // @Override // @ExplodeLoop // public Object execute(VirtualFrame virtualFrame) { // int last = this.bodyNodes.length - 1; // CompilerAsserts.compilationConstant(last); // for (int i=0; i<last; i++) { // this.bodyNodes[i].execute(virtualFrame); // } // return this.bodyNodes[last].execute(virtualFrame); // } // // public static MumblerRootNode create(MumblerLanguage lang, FrameSlot[] argumentNames, // MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { // MumblerNode[] allNodes = new MumblerNode[argumentNames.length // + bodyNodes.length]; // for (int i=0; i<argumentNames.length; i++) { // allNodes[i] = DefineNodeGen.create( // new ReadArgumentNode(i), argumentNames[i]); // } // System.arraycopy(bodyNodes, 0, allNodes, // argumentNames.length, bodyNodes.length); // return new MumblerRootNode(lang, allNodes, frameDescriptor); // } // // public void setName(String name) { // if (this.name == null) { // this.name = name; // } // } // // @Override // public String toString() { // return Arrays.toString(this.bodyNodes); // } // }
import java.util.ArrayList; import java.util.List; import mumbler.truffle.node.MumblerRootNode; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameInstance; import com.oracle.truffle.api.frame.FrameInstanceVisitor; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection;
package mumbler.truffle; /** * The base exception for any runtime errors. * */ public class MumblerException extends RuntimeException { private static final long serialVersionUID = 1L; public MumblerException(String message) { super(message); } @Override public Throwable fillInStackTrace() { CompilerAsserts.neverPartOfCompilation(); return fillInMumblerStackTrace(this); } public static Throwable fillInMumblerStackTrace(Throwable t) { final List<StackTraceElement> stackTrace = new ArrayList<>(); Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { Node callNode = frame.getCallNode(); if (callNode == null) { return null; } RootNode root = callNode.getRootNode(); /* * There should be no RootNodes other than SLRootNodes on the stack. Just for the * case if this would change. */ String methodName = "$unknownFunction";
// Path: lang/src/main/java/mumbler/truffle/node/MumblerRootNode.java // public class MumblerRootNode extends RootNode { // @Children private final MumblerNode[] bodyNodes; // @CompilationFinal public String name; // // public MumblerRootNode(MumblerLanguage lang, MumblerNode[] bodyNodes, // FrameDescriptor frameDescriptor) { // super(lang, frameDescriptor); // this.bodyNodes = bodyNodes; // } // // @Override // @ExplodeLoop // public Object execute(VirtualFrame virtualFrame) { // int last = this.bodyNodes.length - 1; // CompilerAsserts.compilationConstant(last); // for (int i=0; i<last; i++) { // this.bodyNodes[i].execute(virtualFrame); // } // return this.bodyNodes[last].execute(virtualFrame); // } // // public static MumblerRootNode create(MumblerLanguage lang, FrameSlot[] argumentNames, // MumblerNode[] bodyNodes, FrameDescriptor frameDescriptor) { // MumblerNode[] allNodes = new MumblerNode[argumentNames.length // + bodyNodes.length]; // for (int i=0; i<argumentNames.length; i++) { // allNodes[i] = DefineNodeGen.create( // new ReadArgumentNode(i), argumentNames[i]); // } // System.arraycopy(bodyNodes, 0, allNodes, // argumentNames.length, bodyNodes.length); // return new MumblerRootNode(lang, allNodes, frameDescriptor); // } // // public void setName(String name) { // if (this.name == null) { // this.name = name; // } // } // // @Override // public String toString() { // return Arrays.toString(this.bodyNodes); // } // } // Path: lang/src/main/java/mumbler/truffle/MumblerException.java import java.util.ArrayList; import java.util.List; import mumbler.truffle.node.MumblerRootNode; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.frame.FrameInstance; import com.oracle.truffle.api.frame.FrameInstanceVisitor; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; package mumbler.truffle; /** * The base exception for any runtime errors. * */ public class MumblerException extends RuntimeException { private static final long serialVersionUID = 1L; public MumblerException(String message) { super(message); } @Override public Throwable fillInStackTrace() { CompilerAsserts.neverPartOfCompilation(); return fillInMumblerStackTrace(this); } public static Throwable fillInMumblerStackTrace(Throwable t) { final List<StackTraceElement> stackTrace = new ArrayList<>(); Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> { Node callNode = frame.getCallNode(); if (callNode == null) { return null; } RootNode root = callNode.getRootNode(); /* * There should be no RootNodes other than SLRootNodes on the stack. Just for the * case if this would change. */ String methodName = "$unknownFunction";
if (root instanceof MumblerRootNode) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/list/CarBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="car") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/list/CarBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="car") @GenerateNodeFactory
public abstract class CarBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/list/CarBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="car") @GenerateNodeFactory public abstract class CarBuiltinNode extends BuiltinNode { @Specialization
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // // Path: lang/src/main/java/mumbler/truffle/type/MumblerList.java // public class MumblerList<T extends Object> implements Iterable<T> { // public static final MumblerList<?> EMPTY = new MumblerList<>(); // // private final T car; // private final MumblerList<T> cdr; // private final int length; // // private MumblerList() { // this.car = null; // this.cdr = null; // this.length = 0; // } // // private MumblerList(T car, MumblerList<T> cdr) { // this.car = car; // this.cdr = cdr; // this.length = cdr.length + 1; // } // // @SafeVarargs // public static <T> MumblerList<T> list(T... objs) { // return list(asList(objs)); // } // // public static <T> MumblerList<T> list(List<T> objs) { // @SuppressWarnings("unchecked") // MumblerList<T> l = (MumblerList<T>) EMPTY; // for (int i=objs.size()-1; i>=0; i--) { // l = l.cons(objs.get(i)); // } // return l; // } // // public MumblerList<T> cons(T node) { // return new MumblerList<T>(node, this); // } // // public T car() { // if (this != EMPTY) { // return this.car; // } // throw new MumblerException("Cannot car the empty list"); // } // // public MumblerList<T> cdr() { // if (this != EMPTY) { // return this.cdr; // } // throw new MumblerException("Cannot cdr the empty list"); // } // // public long size() { // return this.length; // } // // @Override // public Iterator<T> iterator() { // return new Iterator<T>() { // private MumblerList<T> l = MumblerList.this; // // @Override // public boolean hasNext() { // return this.l != EMPTY; // } // // @Override // public T next() { // if (this.l == EMPTY) { // throw new MumblerException("At end of list"); // } // T car = this.l.car; // this.l = this.l.cdr; // return car; // } // // @Override // public void remove() { // throw new MumblerException("Iterator is immutable"); // } // }; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof MumblerList)) { // return false; // } // if (this == EMPTY && other == EMPTY) { // return true; // } // // MumblerList<?> that = (MumblerList<?>) other; // if (this.cdr == EMPTY && that.cdr != EMPTY) { // return false; // } // return this.car.equals(that.car) && this.cdr.equals(that.cdr); // } // // @Override // public String toString() { // if (this == EMPTY) { // return "()"; // } // // StringBuilder b = new StringBuilder("(" + this.car); // MumblerList<T> rest = this.cdr; // while (rest != null && rest != EMPTY) { // b.append(" "); // b.append(rest.car); // rest = rest.cdr; // } // b.append(")"); // return b.toString(); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/list/CarBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import mumbler.truffle.type.MumblerList; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.list; @NodeInfo(shortName="car") @GenerateNodeFactory public abstract class CarBuiltinNode extends BuiltinNode { @Specialization
protected Object car(MumblerList<?> list) {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/relational/GreaterThanBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName=">") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/relational/GreaterThanBuiltinNode.java import java.math.BigInteger; import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.relational; @NodeInfo(shortName=">") @GenerateNodeFactory
public abstract class GreaterThanBuiltinNode extends BuiltinNode {
cesquivias/mumbler
lang/src/main/java/mumbler/truffle/node/builtin/io/NowBuiltinNode.java
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // }
import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo;
package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "now") @GenerateNodeFactory
// Path: lang/src/main/java/mumbler/truffle/node/builtin/BuiltinNode.java // @NodeChild(value = "arguments", type = MumblerNode[].class) // public abstract class BuiltinNode extends MumblerNode { // public static MumblerFunction createBuiltinFunction( // MumblerLanguage lang, // NodeFactory<? extends BuiltinNode> factory, // VirtualFrame outerFrame) { // int argumentCount = factory.getExecutionSignature().size(); // MumblerNode[] argumentNodes = new MumblerNode[argumentCount]; // for (int i=0; i<argumentCount; i++) { // argumentNodes[i] = new ReadArgumentNode(i); // } // BuiltinNode node = factory.createNode((Object) argumentNodes); // return new MumblerFunction(Truffle.getRuntime().createCallTarget( // new MumblerRootNode(lang, new MumblerNode[] {node}, // new FrameDescriptor()))); // } // } // Path: lang/src/main/java/mumbler/truffle/node/builtin/io/NowBuiltinNode.java import mumbler.truffle.node.builtin.BuiltinNode; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; package mumbler.truffle.node.builtin.io; @NodeInfo(shortName = "now") @GenerateNodeFactory
public abstract class NowBuiltinNode extends BuiltinNode {